posthog-js-lite 2.6.2 → 3.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs.js CHANGED
@@ -2,148 +2,6 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- /******************************************************************************
6
- Copyright (c) Microsoft Corporation.
7
-
8
- Permission to use, copy, modify, and/or distribute this software for any
9
- purpose with or without fee is hereby granted.
10
-
11
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
- PERFORMANCE OF THIS SOFTWARE.
18
- ***************************************************************************** */
19
- /* global Reflect, Promise */
20
- var extendStatics = function (d, b) {
21
- extendStatics = Object.setPrototypeOf ||
22
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23
- function (d, b) { for (var p in b)
24
- if (Object.prototype.hasOwnProperty.call(b, p))
25
- d[p] = b[p]; };
26
- return extendStatics(d, b);
27
- };
28
- function __extends(d, b) {
29
- if (typeof b !== "function" && b !== null)
30
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
31
- extendStatics(d, b);
32
- function __() { this.constructor = d; }
33
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34
- }
35
- var __assign = function () {
36
- __assign = Object.assign || function __assign(t) {
37
- for (var s, i = 1, n = arguments.length; i < n; i++) {
38
- s = arguments[i];
39
- for (var p in s)
40
- if (Object.prototype.hasOwnProperty.call(s, p))
41
- t[p] = s[p];
42
- }
43
- return t;
44
- };
45
- return __assign.apply(this, arguments);
46
- };
47
- function __awaiter(thisArg, _arguments, P, generator) {
48
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
49
- return new (P || (P = Promise))(function (resolve, reject) {
50
- function fulfilled(value) { try {
51
- step(generator.next(value));
52
- }
53
- catch (e) {
54
- reject(e);
55
- } }
56
- function rejected(value) { try {
57
- step(generator["throw"](value));
58
- }
59
- catch (e) {
60
- reject(e);
61
- } }
62
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
63
- step((generator = generator.apply(thisArg, _arguments || [])).next());
64
- });
65
- }
66
- function __generator(thisArg, body) {
67
- var _ = { label: 0, sent: function () { if (t[0] & 1)
68
- throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
69
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
70
- function verb(n) { return function (v) { return step([n, v]); }; }
71
- function step(op) {
72
- if (f)
73
- throw new TypeError("Generator is already executing.");
74
- while (_)
75
- try {
76
- 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)
77
- return t;
78
- if (y = 0, t)
79
- op = [op[0] & 2, t.value];
80
- switch (op[0]) {
81
- case 0:
82
- case 1:
83
- t = op;
84
- break;
85
- case 4:
86
- _.label++;
87
- return { value: op[1], done: false };
88
- case 5:
89
- _.label++;
90
- y = op[1];
91
- op = [0];
92
- continue;
93
- case 7:
94
- op = _.ops.pop();
95
- _.trys.pop();
96
- continue;
97
- default:
98
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
99
- _ = 0;
100
- continue;
101
- }
102
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
103
- _.label = op[1];
104
- break;
105
- }
106
- if (op[0] === 6 && _.label < t[1]) {
107
- _.label = t[1];
108
- t = op;
109
- break;
110
- }
111
- if (t && _.label < t[2]) {
112
- _.label = t[2];
113
- _.ops.push(op);
114
- break;
115
- }
116
- if (t[2])
117
- _.ops.pop();
118
- _.trys.pop();
119
- continue;
120
- }
121
- op = body.call(thisArg, _);
122
- }
123
- catch (e) {
124
- op = [6, e];
125
- y = 0;
126
- }
127
- finally {
128
- f = t = 0;
129
- }
130
- if (op[0] & 5)
131
- throw op[1];
132
- return { value: op[0] ? op[1] : void 0, done: true };
133
- }
134
- }
135
- function __spreadArray(to, from, pack) {
136
- if (pack || arguments.length === 2)
137
- for (var i = 0, l = from.length, ar; i < l; i++) {
138
- if (ar || !(i in from)) {
139
- if (!ar)
140
- ar = Array.prototype.slice.call(from, 0, i);
141
- ar[i] = from[i];
142
- }
143
- }
144
- return to.concat(ar || Array.prototype.slice.call(from));
145
- }
146
-
147
5
  var PostHogPersistedProperty;
148
6
  (function (PostHogPersistedProperty) {
149
7
  PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
@@ -168,48 +26,27 @@ function assert(truthyValue, message) {
168
26
  }
169
27
  }
170
28
  function removeTrailingSlash(url) {
171
- return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
29
+ return url?.replace(/\/+$/, '');
172
30
  }
173
- function retriable(fn, props) {
174
- if (props === void 0) { props = {}; }
175
- return __awaiter(this, void 0, void 0, function () {
176
- var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
177
- return __generator(this, function (_d) {
178
- switch (_d.label) {
179
- case 0:
180
- _a = props.retryCount, retryCount = _a === void 0 ? 3 : _a, _b = props.retryDelay, retryDelay = _b === void 0 ? 5000 : _b, _c = props.retryCheck, retryCheck = _c === void 0 ? function () { return true; } : _c;
181
- lastError = null;
182
- i = 0;
183
- _d.label = 1;
184
- case 1:
185
- if (!(i < retryCount + 1)) return [3 /*break*/, 7];
186
- if (!(i > 0)) return [3 /*break*/, 3];
187
- // don't wait when it's the last try
188
- return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
189
- case 2:
190
- // don't wait when it's the last try
191
- _d.sent();
192
- _d.label = 3;
193
- case 3:
194
- _d.trys.push([3, 5, , 6]);
195
- return [4 /*yield*/, fn()];
196
- case 4:
197
- res = _d.sent();
198
- return [2 /*return*/, res];
199
- case 5:
200
- e_1 = _d.sent();
201
- lastError = e_1;
202
- if (!retryCheck(e_1)) {
203
- throw e_1;
204
- }
205
- return [3 /*break*/, 6];
206
- case 6:
207
- i++;
208
- return [3 /*break*/, 1];
209
- case 7: throw lastError;
31
+ async function retriable(fn, props) {
32
+ let lastError = null;
33
+ for (let i = 0; i < props.retryCount + 1; i++) {
34
+ if (i > 0) {
35
+ // don't wait when it's the last try
36
+ await new Promise((r) => setTimeout(r, props.retryDelay));
37
+ }
38
+ try {
39
+ const res = await fn();
40
+ return res;
41
+ }
42
+ catch (e) {
43
+ lastError = e;
44
+ if (!props.retryCheck(e)) {
45
+ throw e;
210
46
  }
211
- });
212
- });
47
+ }
48
+ }
49
+ throw lastError;
213
50
  }
214
51
  function currentTimestamp() {
215
52
  return new Date().getTime();
@@ -220,9 +57,9 @@ function currentISOTime() {
220
57
  function safeSetTimeout(fn, timeout) {
221
58
  // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
222
59
  // rather than setImmediate.
223
- var t = setTimeout(fn, timeout);
60
+ const t = setTimeout(fn, timeout);
224
61
  // We unref if available to prevent Node.js hanging on exit
225
- (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
62
+ t?.unref && t?.unref();
226
63
  return t;
227
64
  }
228
65
 
@@ -236,24 +73,24 @@ function safeSetTimeout(fn, timeout) {
236
73
  //
237
74
  // LZ-based compression algorithm, version 1.4.4
238
75
  // private property
239
- var f = String.fromCharCode;
240
- var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
241
- var baseReverseDic = {};
76
+ const f = String.fromCharCode;
77
+ const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
78
+ const baseReverseDic = {};
242
79
  function getBaseValue(alphabet, character) {
243
80
  if (!baseReverseDic[alphabet]) {
244
81
  baseReverseDic[alphabet] = {};
245
- for (var i = 0; i < alphabet.length; i++) {
82
+ for (let i = 0; i < alphabet.length; i++) {
246
83
  baseReverseDic[alphabet][alphabet.charAt(i)] = i;
247
84
  }
248
85
  }
249
86
  return baseReverseDic[alphabet][character];
250
87
  }
251
- var LZString = {
88
+ const LZString = {
252
89
  compressToBase64: function (input) {
253
90
  if (input == null) {
254
91
  return '';
255
92
  }
256
- var res = LZString._compress(input, 6, function (a) {
93
+ const res = LZString._compress(input, 6, function (a) {
257
94
  return keyStrBase64.charAt(a);
258
95
  });
259
96
  switch (res.length % 4 // To produce valid Base64
@@ -289,8 +126,8 @@ var LZString = {
289
126
  if (uncompressed == null) {
290
127
  return '';
291
128
  }
292
- var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
293
- var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
129
+ const context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
130
+ let i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
294
131
  context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
295
132
  for (ii = 0; ii < uncompressed.length; ii += 1) {
296
133
  context_c = uncompressed.charAt(ii);
@@ -514,8 +351,8 @@ var LZString = {
514
351
  });
515
352
  },
516
353
  _decompress: function (length, resetValue, getNextValue) {
517
- var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
518
- var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
354
+ const dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
355
+ let enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
519
356
  for (i = 0; i < 3; i += 1) {
520
357
  dictionary[i] = i;
521
358
  }
@@ -657,33 +494,29 @@ var LZString = {
657
494
  },
658
495
  };
659
496
 
660
- var SimpleEventEmitter = /** @class */ (function () {
661
- function SimpleEventEmitter() {
497
+ class SimpleEventEmitter {
498
+ constructor() {
662
499
  this.events = {};
663
500
  this.events = {};
664
501
  }
665
- SimpleEventEmitter.prototype.on = function (event, listener) {
666
- var _this = this;
502
+ on(event, listener) {
667
503
  if (!this.events[event]) {
668
504
  this.events[event] = [];
669
505
  }
670
506
  this.events[event].push(listener);
671
- return function () {
672
- _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
507
+ return () => {
508
+ this.events[event] = this.events[event].filter((x) => x !== listener);
673
509
  };
674
- };
675
- SimpleEventEmitter.prototype.emit = function (event, payload) {
676
- for (var _i = 0, _a = this.events[event] || []; _i < _a.length; _i++) {
677
- var listener = _a[_i];
510
+ }
511
+ emit(event, payload) {
512
+ for (const listener of this.events[event] || []) {
678
513
  listener(payload);
679
514
  }
680
- for (var _b = 0, _c = this.events['*'] || []; _b < _c.length; _b++) {
681
- var listener = _c[_b];
515
+ for (const listener of this.events['*'] || []) {
682
516
  listener(event, payload);
683
517
  }
684
- };
685
- return SimpleEventEmitter;
686
- }());
518
+ }
519
+ }
687
520
 
688
521
  // vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts
689
522
  // https://github.com/LiosK/uuidv7#license
@@ -694,11 +527,11 @@ var SimpleEventEmitter = /** @class */ (function () {
694
527
  * @copyright 2021-2023 LiosK
695
528
  * @packageDocumentation
696
529
  */
697
- var DIGITS = "0123456789abcdef";
530
+ const DIGITS = "0123456789abcdef";
698
531
  /** Represents a UUID as a 16-byte byte array. */
699
- var UUID = /** @class */ (function () {
532
+ class UUID {
700
533
  /** @param bytes - The 16-byte byte array representation. */
701
- function UUID(bytes) {
534
+ constructor(bytes) {
702
535
  this.bytes = bytes;
703
536
  }
704
537
  /**
@@ -710,14 +543,14 @@ var UUID = /** @class */ (function () {
710
543
  *
711
544
  * @throws TypeError if the length of the argument is not 16.
712
545
  */
713
- UUID.ofInner = function (bytes) {
546
+ static ofInner(bytes) {
714
547
  if (bytes.length !== 16) {
715
548
  throw new TypeError("not 128-bit length");
716
549
  }
717
550
  else {
718
551
  return new UUID(bytes);
719
552
  }
720
- };
553
+ }
721
554
  /**
722
555
  * Builds a byte array from UUIDv7 field values.
723
556
  *
@@ -727,7 +560,7 @@ var UUID = /** @class */ (function () {
727
560
  * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
728
561
  * @throws RangeError if any field value is out of the specified range.
729
562
  */
730
- UUID.fromFieldsV7 = function (unixTsMs, randA, randBHi, randBLo) {
563
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
731
564
  if (!Number.isInteger(unixTsMs) ||
732
565
  !Number.isInteger(randA) ||
733
566
  !Number.isInteger(randBHi) ||
@@ -742,12 +575,12 @@ var UUID = /** @class */ (function () {
742
575
  randBLo > 4294967295) {
743
576
  throw new RangeError("invalid field value");
744
577
  }
745
- var bytes = new Uint8Array(16);
746
- bytes[0] = unixTsMs / Math.pow(2, 40);
747
- bytes[1] = unixTsMs / Math.pow(2, 32);
748
- bytes[2] = unixTsMs / Math.pow(2, 24);
749
- bytes[3] = unixTsMs / Math.pow(2, 16);
750
- bytes[4] = unixTsMs / Math.pow(2, 8);
578
+ const bytes = new Uint8Array(16);
579
+ bytes[0] = unixTsMs / 2 ** 40;
580
+ bytes[1] = unixTsMs / 2 ** 32;
581
+ bytes[2] = unixTsMs / 2 ** 24;
582
+ bytes[3] = unixTsMs / 2 ** 16;
583
+ bytes[4] = unixTsMs / 2 ** 8;
751
584
  bytes[5] = unixTsMs;
752
585
  bytes[6] = 0x70 | (randA >>> 8);
753
586
  bytes[7] = randA;
@@ -760,7 +593,7 @@ var UUID = /** @class */ (function () {
760
593
  bytes[14] = randBLo >>> 8;
761
594
  bytes[15] = randBLo;
762
595
  return new UUID(bytes);
763
- };
596
+ }
764
597
  /**
765
598
  * Builds a byte array from a string representation.
766
599
  *
@@ -775,33 +608,38 @@ var UUID = /** @class */ (function () {
775
608
  *
776
609
  * @throws SyntaxError if the argument could not parse as a valid UUID string.
777
610
  */
778
- UUID.parse = function (uuid) {
779
- var _a, _b, _c, _d;
780
- var hex = undefined;
611
+ static parse(uuid) {
612
+ let hex = undefined;
781
613
  switch (uuid.length) {
782
614
  case 32:
783
- hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
615
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
784
616
  break;
785
617
  case 36:
786
618
  hex =
787
- (_b = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
788
- .exec(uuid)) === null || _b === void 0 ? void 0 : _b.slice(1, 6).join("");
619
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
620
+ .exec(uuid)
621
+ ?.slice(1, 6)
622
+ .join("");
789
623
  break;
790
624
  case 38:
791
625
  hex =
792
- (_c = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
793
- .exec(uuid)) === null || _c === void 0 ? void 0 : _c.slice(1, 6).join("");
626
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
627
+ .exec(uuid)
628
+ ?.slice(1, 6)
629
+ .join("");
794
630
  break;
795
631
  case 45:
796
632
  hex =
797
- (_d = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
798
- .exec(uuid)) === null || _d === void 0 ? void 0 : _d.slice(1, 6).join("");
633
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
634
+ .exec(uuid)
635
+ ?.slice(1, 6)
636
+ .join("");
799
637
  break;
800
638
  }
801
639
  if (hex) {
802
- var inner = new Uint8Array(16);
803
- for (var i = 0; i < 16; i += 4) {
804
- var n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
640
+ const inner = new Uint8Array(16);
641
+ for (let i = 0; i < 16; i += 4) {
642
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
805
643
  inner[i + 0] = n >>> 24;
806
644
  inner[i + 1] = n >>> 16;
807
645
  inner[i + 2] = n >>> 8;
@@ -812,14 +650,14 @@ var UUID = /** @class */ (function () {
812
650
  else {
813
651
  throw new SyntaxError("could not parse UUID string");
814
652
  }
815
- };
653
+ }
816
654
  /**
817
655
  * @returns The 8-4-4-4-12 canonical hexadecimal string representation
818
656
  * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
819
657
  */
820
- UUID.prototype.toString = function () {
821
- var text = "";
822
- for (var i = 0; i < this.bytes.length; i++) {
658
+ toString() {
659
+ let text = "";
660
+ for (let i = 0; i < this.bytes.length; i++) {
823
661
  text += DIGITS.charAt(this.bytes[i] >>> 4);
824
662
  text += DIGITS.charAt(this.bytes[i] & 0xf);
825
663
  if (i === 3 || i === 5 || i === 7 || i === 9) {
@@ -827,23 +665,23 @@ var UUID = /** @class */ (function () {
827
665
  }
828
666
  }
829
667
  return text;
830
- };
668
+ }
831
669
  /**
832
670
  * @returns The 32-digit hexadecimal representation without hyphens
833
671
  * (`0189dcd553117d408db09496a2eef37b`).
834
672
  */
835
- UUID.prototype.toHex = function () {
836
- var text = "";
837
- for (var i = 0; i < this.bytes.length; i++) {
673
+ toHex() {
674
+ let text = "";
675
+ for (let i = 0; i < this.bytes.length; i++) {
838
676
  text += DIGITS.charAt(this.bytes[i] >>> 4);
839
677
  text += DIGITS.charAt(this.bytes[i] & 0xf);
840
678
  }
841
679
  return text;
842
- };
680
+ }
843
681
  /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
844
- UUID.prototype.toJSON = function () {
682
+ toJSON() {
845
683
  return this.toString();
846
- };
684
+ }
847
685
  /**
848
686
  * Reports the variant field value of the UUID or, if appropriate, "NIL" or
849
687
  * "MAX".
@@ -852,57 +690,56 @@ var UUID = /** @class */ (function () {
852
690
  * the Nil or Max UUID, although the Nil and Max UUIDs are technically
853
691
  * subsumed under the variants `0b0` and `0b111`, respectively.
854
692
  */
855
- UUID.prototype.getVariant = function () {
856
- var n = this.bytes[8] >>> 4;
693
+ getVariant() {
694
+ const n = this.bytes[8] >>> 4;
857
695
  if (n < 0) {
858
696
  throw new Error("unreachable");
859
697
  }
860
- else if (n <= 7) {
861
- return this.bytes.every(function (e) { return e === 0; }) ? "NIL" : "VAR_0";
698
+ else if (n <= 0b0111) {
699
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
862
700
  }
863
- else if (n <= 11) {
701
+ else if (n <= 0b1011) {
864
702
  return "VAR_10";
865
703
  }
866
- else if (n <= 13) {
704
+ else if (n <= 0b1101) {
867
705
  return "VAR_110";
868
706
  }
869
- else if (n <= 15) {
870
- return this.bytes.every(function (e) { return e === 0xff; }) ? "MAX" : "VAR_RESERVED";
707
+ else if (n <= 0b1111) {
708
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
871
709
  }
872
710
  else {
873
711
  throw new Error("unreachable");
874
712
  }
875
- };
713
+ }
876
714
  /**
877
715
  * Returns the version field value of the UUID or `undefined` if the UUID does
878
716
  * not have the variant field value of `0b10`.
879
717
  */
880
- UUID.prototype.getVersion = function () {
718
+ getVersion() {
881
719
  return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
882
- };
720
+ }
883
721
  /** Creates an object from `this`. */
884
- UUID.prototype.clone = function () {
722
+ clone() {
885
723
  return new UUID(this.bytes.slice(0));
886
- };
724
+ }
887
725
  /** Returns true if `this` is equivalent to `other`. */
888
- UUID.prototype.equals = function (other) {
726
+ equals(other) {
889
727
  return this.compareTo(other) === 0;
890
- };
728
+ }
891
729
  /**
892
730
  * Returns a negative integer, zero, or positive integer if `this` is less
893
731
  * than, equal to, or greater than `other`, respectively.
894
732
  */
895
- UUID.prototype.compareTo = function (other) {
896
- for (var i = 0; i < 16; i++) {
897
- var diff = this.bytes[i] - other.bytes[i];
733
+ compareTo(other) {
734
+ for (let i = 0; i < 16; i++) {
735
+ const diff = this.bytes[i] - other.bytes[i];
898
736
  if (diff !== 0) {
899
737
  return Math.sign(diff);
900
738
  }
901
739
  }
902
740
  return 0;
903
- };
904
- return UUID;
905
- }());
741
+ }
742
+ }
906
743
  /**
907
744
  * Encapsulates the monotonic counter state.
908
745
  *
@@ -912,16 +749,16 @@ var UUID = /** @class */ (function () {
912
749
  * that is useful to absolutely guarantee the monotonically increasing order of
913
750
  * generated UUIDs. See their respective documentation for details.
914
751
  */
915
- var V7Generator = /** @class */ (function () {
752
+ class V7Generator {
916
753
  /**
917
754
  * Creates a generator object with the default random number generator, or
918
755
  * with the specified one if passed as an argument. The specified random
919
756
  * number generator should be cryptographically strong and securely seeded.
920
757
  */
921
- function V7Generator(randomNumberGenerator) {
758
+ constructor(randomNumberGenerator) {
922
759
  this.timestamp = 0;
923
760
  this.counter = 0;
924
- this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
761
+ this.random = randomNumberGenerator ?? getDefaultRandom();
925
762
  }
926
763
  /**
927
764
  * Generates a new UUIDv7 object from the current timestamp, or resets the
@@ -937,9 +774,9 @@ var V7Generator = /** @class */ (function () {
937
774
  * See {@link generateOrAbort} for the other mode of generation and
938
775
  * {@link generateOrResetCore} for the low-level primitive.
939
776
  */
940
- V7Generator.prototype.generate = function () {
777
+ generate() {
941
778
  return this.generateOrResetCore(Date.now(), 10000);
942
- };
779
+ }
943
780
  /**
944
781
  * Generates a new UUIDv7 object from the current timestamp, or returns
945
782
  * `undefined` upon significant timestamp rollback.
@@ -953,9 +790,9 @@ var V7Generator = /** @class */ (function () {
953
790
  * See {@link generate} for the other mode of generation and
954
791
  * {@link generateOrAbortCore} for the low-level primitive.
955
792
  */
956
- V7Generator.prototype.generateOrAbort = function () {
793
+ generateOrAbort() {
957
794
  return this.generateOrAbortCore(Date.now(), 10000);
958
- };
795
+ }
959
796
  /**
960
797
  * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
961
798
  * generator upon significant timestamp rollback.
@@ -967,15 +804,15 @@ var V7Generator = /** @class */ (function () {
967
804
  * considered significant. A suggested value is `10_000` (milliseconds).
968
805
  * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
969
806
  */
970
- V7Generator.prototype.generateOrResetCore = function (unixTsMs, rollbackAllowance) {
971
- var value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
807
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
808
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
972
809
  if (value === undefined) {
973
810
  // reset state and resume
974
811
  this.timestamp = 0;
975
812
  value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
976
813
  }
977
814
  return value;
978
- };
815
+ }
979
816
  /**
980
817
  * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
981
818
  * `undefined` upon significant timestamp rollback.
@@ -987,8 +824,8 @@ var V7Generator = /** @class */ (function () {
987
824
  * considered significant. A suggested value is `10_000` (milliseconds).
988
825
  * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
989
826
  */
990
- V7Generator.prototype.generateOrAbortCore = function (unixTsMs, rollbackAllowance) {
991
- var MAX_COUNTER = 4398046511103;
827
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
828
+ const MAX_COUNTER = 4398046511103;
992
829
  if (!Number.isInteger(unixTsMs) ||
993
830
  unixTsMs < 1 ||
994
831
  unixTsMs > 281474976710655) {
@@ -1014,30 +851,29 @@ var V7Generator = /** @class */ (function () {
1014
851
  // abort if clock went backwards to unbearable extent
1015
852
  return undefined;
1016
853
  }
1017
- return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / Math.pow(2, 30)), this.counter & (Math.pow(2, 30) - 1), this.random.nextUint32());
1018
- };
854
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
855
+ }
1019
856
  /** Initializes the counter at a 42-bit random integer. */
1020
- V7Generator.prototype.resetCounter = function () {
857
+ resetCounter() {
1021
858
  this.counter =
1022
859
  this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
1023
- };
860
+ }
1024
861
  /**
1025
862
  * Generates a new UUIDv4 object utilizing the random number generator inside.
1026
863
  *
1027
864
  * @internal
1028
865
  */
1029
- V7Generator.prototype.generateV4 = function () {
1030
- var bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
866
+ generateV4() {
867
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
1031
868
  bytes[6] = 0x40 | (bytes[6] >>> 4);
1032
869
  bytes[8] = 0x80 | (bytes[8] >>> 2);
1033
870
  return UUID.ofInner(bytes);
1034
- };
1035
- return V7Generator;
1036
- }());
871
+ }
872
+ }
1037
873
  /** A global flag to force use of cryptographically strong RNG. */
1038
874
  // declare const UUIDV7_DENY_WEAK_RNG: boolean;
1039
875
  /** Returns the default random number generator available in the environment. */
1040
- var getDefaultRandom = function () {
876
+ const getDefaultRandom = () => {
1041
877
  // fix: crypto isn't available in react-native, always use Math.random
1042
878
  // // detect Web Crypto API
1043
879
  // if (
@@ -1057,10 +893,8 @@ var getDefaultRandom = function () {
1057
893
  // };
1058
894
  // }
1059
895
  return {
1060
- nextUint32: function () {
1061
- return Math.trunc(Math.random() * 65536) * 65536 +
1062
- Math.trunc(Math.random() * 65536);
1063
- },
896
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
897
+ Math.trunc(Math.random() * 65536),
1064
898
  };
1065
899
  };
1066
900
  // /**
@@ -1079,785 +913,813 @@ var getDefaultRandom = function () {
1079
913
  // return this.buffer[this.cursor++];
1080
914
  // }
1081
915
  // }
1082
- var defaultGenerator;
916
+ let defaultGenerator;
1083
917
  /**
1084
918
  * Generates a UUIDv7 string.
1085
919
  *
1086
920
  * @returns The 8-4-4-4-12 canonical hexadecimal string representation
1087
921
  * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
1088
922
  */
1089
- var uuidv7 = function () { return uuidv7obj().toString(); };
923
+ const uuidv7 = () => uuidv7obj().toString();
1090
924
  /** Generates a UUIDv7 object. */
1091
- var uuidv7obj = function () {
1092
- return (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
1093
- };
925
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
1094
926
 
1095
- var PostHogFetchHttpError = /** @class */ (function (_super) {
1096
- __extends(PostHogFetchHttpError, _super);
1097
- function PostHogFetchHttpError(response) {
1098
- var _this = _super.call(this, 'HTTP error while fetching PostHog: ' + response.status) || this;
1099
- _this.response = response;
1100
- _this.name = 'PostHogFetchHttpError';
1101
- return _this;
1102
- }
1103
- return PostHogFetchHttpError;
1104
- }(Error));
1105
- var PostHogFetchNetworkError = /** @class */ (function (_super) {
1106
- __extends(PostHogFetchNetworkError, _super);
1107
- function PostHogFetchNetworkError(error) {
1108
- var _this =
927
+ class PostHogFetchHttpError extends Error {
928
+ constructor(response) {
929
+ super('HTTP error while fetching PostHog: ' + response.status);
930
+ this.response = response;
931
+ this.name = 'PostHogFetchHttpError';
932
+ }
933
+ }
934
+ class PostHogFetchNetworkError extends Error {
935
+ constructor(error) {
1109
936
  // TRICKY: "cause" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.
937
+ // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1110
938
  // @ts-ignore
1111
- _super.call(this, 'Network error while fetching PostHog', error instanceof Error ? { cause: error } : {}) || this;
1112
- _this.error = error;
1113
- _this.name = 'PostHogFetchNetworkError';
1114
- return _this;
939
+ super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {});
940
+ this.error = error;
941
+ this.name = 'PostHogFetchNetworkError';
1115
942
  }
1116
- return PostHogFetchNetworkError;
1117
- }(Error));
943
+ }
1118
944
  function isPostHogFetchError(err) {
1119
- return typeof err === 'object' && (err.name === 'PostHogFetchHttpError' || err.name === 'PostHogFetchNetworkError');
945
+ return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
1120
946
  }
1121
- var PostHogCoreStateless = /** @class */ (function () {
1122
- function PostHogCoreStateless(apiKey, options) {
1123
- var _a, _b, _c, _d, _e;
1124
- this.debugMode = false;
947
+ class PostHogCoreStateless {
948
+ constructor(apiKey, options) {
949
+ this.flushPromise = null;
1125
950
  this.disableGeoip = true;
951
+ this.disabled = false;
952
+ this.defaultOptIn = true;
1126
953
  this.pendingPromises = {};
1127
954
  // internal
1128
955
  this._events = new SimpleEventEmitter();
956
+ this._isInitialized = false;
1129
957
  assert(apiKey, "You must pass your PostHog project's api key.");
1130
958
  this.apiKey = apiKey;
1131
- this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
1132
- this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
1133
- this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
1134
- this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
959
+ this.host = removeTrailingSlash(options?.host || 'https://app.posthog.com');
960
+ this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
961
+ this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
962
+ this.flushInterval = options?.flushInterval ?? 10000;
963
+ this.captureMode = options?.captureMode || 'form';
1135
964
  // If enable is explicitly set to false we override the optout
1136
- this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
965
+ this.defaultOptIn = options?.defaultOptIn ?? true;
1137
966
  this._retryOptions = {
1138
- retryCount: (_b = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _b !== void 0 ? _b : 3,
1139
- retryDelay: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _c !== void 0 ? _c : 3000,
967
+ retryCount: options?.fetchRetryCount ?? 3,
968
+ retryDelay: options?.fetchRetryDelay ?? 3000,
1140
969
  retryCheck: isPostHogFetchError,
1141
970
  };
1142
- this.requestTimeout = (_d = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _d !== void 0 ? _d : 10000; // 10 seconds
1143
- this.disableGeoip = (_e = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _e !== void 0 ? _e : true;
971
+ this.requestTimeout = options?.requestTimeout ?? 10000; // 10 seconds
972
+ this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
973
+ this.disableGeoip = options?.disableGeoip ?? true;
974
+ this.disabled = options?.disabled ?? false;
975
+ // Init promise allows the derived class to block calls until it is ready
976
+ this._initPromise = Promise.resolve();
977
+ this._isInitialized = true;
1144
978
  }
1145
- PostHogCoreStateless.prototype.getCommonEventProperties = function () {
979
+ wrap(fn) {
980
+ if (this.disabled) {
981
+ if (this.isDebug) {
982
+ console.warn('[PostHog] The client is disabled');
983
+ }
984
+ return;
985
+ }
986
+ if (this._isInitialized) {
987
+ // NOTE: We could also check for the "opt in" status here...
988
+ return fn();
989
+ }
990
+ this._initPromise.then(() => fn());
991
+ }
992
+ getCommonEventProperties() {
1146
993
  return {
1147
994
  $lib: this.getLibraryId(),
1148
995
  $lib_version: this.getLibraryVersion(),
1149
996
  };
1150
- };
1151
- Object.defineProperty(PostHogCoreStateless.prototype, "optedOut", {
1152
- get: function () {
1153
- var _a, _b;
1154
- return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
1155
- },
1156
- enumerable: false,
1157
- configurable: true
1158
- });
1159
- PostHogCoreStateless.prototype.optIn = function () {
1160
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1161
- };
1162
- PostHogCoreStateless.prototype.optOut = function () {
1163
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1164
- };
1165
- PostHogCoreStateless.prototype.on = function (event, cb) {
997
+ }
998
+ get optedOut() {
999
+ return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
1000
+ }
1001
+ async optIn() {
1002
+ this.wrap(() => {
1003
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1004
+ });
1005
+ }
1006
+ async optOut() {
1007
+ this.wrap(() => {
1008
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1009
+ });
1010
+ }
1011
+ on(event, cb) {
1166
1012
  return this._events.on(event, cb);
1167
- };
1168
- PostHogCoreStateless.prototype.debug = function (enabled) {
1169
- var _a;
1170
- if (enabled === void 0) { enabled = true; }
1171
- (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
1172
- this.debugMode = enabled;
1013
+ }
1014
+ debug(enabled = true) {
1015
+ this.removeDebugCallback?.();
1173
1016
  if (enabled) {
1174
- this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
1017
+ const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload));
1018
+ this.removeDebugCallback = () => {
1019
+ removeDebugCallback();
1020
+ this.removeDebugCallback = undefined;
1021
+ };
1175
1022
  }
1176
- };
1177
- PostHogCoreStateless.prototype.buildPayload = function (payload) {
1023
+ }
1024
+ get isDebug() {
1025
+ return !!this.removeDebugCallback;
1026
+ }
1027
+ buildPayload(payload) {
1178
1028
  return {
1179
1029
  distinct_id: payload.distinct_id,
1180
1030
  event: payload.event,
1181
- properties: __assign(__assign({}, (payload.properties || {})), this.getCommonEventProperties()),
1031
+ properties: {
1032
+ ...(payload.properties || {}),
1033
+ ...this.getCommonEventProperties(), // Common PH props
1034
+ },
1182
1035
  };
1183
- };
1184
- PostHogCoreStateless.prototype.addPendingPromise = function (promise) {
1185
- var _this = this;
1186
- var promiseUUID = uuidv7();
1036
+ }
1037
+ addPendingPromise(promise) {
1038
+ const promiseUUID = uuidv7();
1187
1039
  this.pendingPromises[promiseUUID] = promise;
1188
- promise.finally(function () {
1189
- delete _this.pendingPromises[promiseUUID];
1040
+ promise
1041
+ .catch(() => { })
1042
+ .finally(() => {
1043
+ delete this.pendingPromises[promiseUUID];
1190
1044
  });
1191
- };
1045
+ return promise;
1046
+ }
1192
1047
  /***
1193
1048
  *** TRACKING
1194
1049
  ***/
1195
- PostHogCoreStateless.prototype.identifyStateless = function (distinctId, properties, options) {
1196
- // The properties passed to identifyStateless are event properties.
1197
- // To add person properties, pass in all person properties to the `$set` key.
1198
- var payload = __assign({}, this.buildPayload({
1199
- distinct_id: distinctId,
1200
- event: '$identify',
1201
- properties: properties,
1202
- }));
1203
- this.enqueue('identify', payload, options);
1204
- return this;
1205
- };
1206
- PostHogCoreStateless.prototype.captureStateless = function (distinctId, event, properties, options) {
1207
- var payload = this.buildPayload({ distinct_id: distinctId, event: event, properties: properties });
1208
- this.enqueue('capture', payload, options);
1209
- return this;
1210
- };
1211
- PostHogCoreStateless.prototype.aliasStateless = function (alias, distinctId, properties, options) {
1212
- var payload = this.buildPayload({
1213
- event: '$create_alias',
1214
- distinct_id: distinctId,
1215
- properties: __assign(__assign({}, (properties || {})), { distinct_id: distinctId, alias: alias }),
1050
+ identifyStateless(distinctId, properties, options) {
1051
+ this.wrap(() => {
1052
+ // The properties passed to identifyStateless are event properties.
1053
+ // To add person properties, pass in all person properties to the `$set` key.
1054
+ const payload = {
1055
+ ...this.buildPayload({
1056
+ distinct_id: distinctId,
1057
+ event: '$identify',
1058
+ properties,
1059
+ }),
1060
+ };
1061
+ this.enqueue('identify', payload, options);
1216
1062
  });
1217
- this.enqueue('alias', payload, options);
1218
- return this;
1219
- };
1063
+ }
1064
+ captureStateless(distinctId, event, properties, options) {
1065
+ this.wrap(() => {
1066
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1067
+ this.enqueue('capture', payload, options);
1068
+ });
1069
+ }
1070
+ aliasStateless(alias, distinctId, properties, options) {
1071
+ this.wrap(() => {
1072
+ const payload = this.buildPayload({
1073
+ event: '$create_alias',
1074
+ distinct_id: distinctId,
1075
+ properties: {
1076
+ ...(properties || {}),
1077
+ distinct_id: distinctId,
1078
+ alias,
1079
+ },
1080
+ });
1081
+ this.enqueue('alias', payload, options);
1082
+ });
1083
+ }
1220
1084
  /***
1221
1085
  *** GROUPS
1222
1086
  ***/
1223
- PostHogCoreStateless.prototype.groupIdentifyStateless = function (groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1224
- var payload = this.buildPayload({
1225
- distinct_id: distinctId || "$".concat(groupType, "_").concat(groupKey),
1226
- event: '$groupidentify',
1227
- properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, (eventProperties || {})),
1087
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1088
+ this.wrap(() => {
1089
+ const payload = this.buildPayload({
1090
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
1091
+ event: '$groupidentify',
1092
+ properties: {
1093
+ $group_type: groupType,
1094
+ $group_key: groupKey,
1095
+ $group_set: groupProperties || {},
1096
+ ...(eventProperties || {}),
1097
+ },
1098
+ });
1099
+ this.enqueue('capture', payload, options);
1228
1100
  });
1229
- this.enqueue('capture', payload, options);
1230
- return this;
1231
- };
1101
+ }
1232
1102
  /***
1233
1103
  *** FEATURE FLAGS
1234
1104
  ***/
1235
- PostHogCoreStateless.prototype.getDecide = function (distinctId, groups, personProperties, groupProperties, extraPayload) {
1236
- if (groups === void 0) { groups = {}; }
1237
- if (personProperties === void 0) { personProperties = {}; }
1238
- if (groupProperties === void 0) { groupProperties = {}; }
1239
- if (extraPayload === void 0) { extraPayload = {}; }
1240
- return __awaiter(this, void 0, void 0, function () {
1241
- var url, fetchOptions;
1242
- var _this = this;
1243
- return __generator(this, function (_a) {
1244
- url = "".concat(this.host, "/decide/?v=3");
1245
- fetchOptions = {
1246
- method: 'POST',
1247
- headers: { 'Content-Type': 'application/json' },
1248
- body: JSON.stringify(__assign({ token: this.apiKey, distinct_id: distinctId, groups: groups, person_properties: personProperties, group_properties: groupProperties }, extraPayload)),
1249
- };
1250
- return [2 /*return*/, this.fetchWithRetry(url, fetchOptions)
1251
- .then(function (response) { return response.json(); })
1252
- .catch(function (error) {
1253
- _this._events.emit('error', error);
1254
- return undefined;
1255
- })];
1256
- });
1257
- });
1258
- };
1259
- PostHogCoreStateless.prototype.getFeatureFlagStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
1260
- if (groups === void 0) { groups = {}; }
1261
- if (personProperties === void 0) { personProperties = {}; }
1262
- if (groupProperties === void 0) { groupProperties = {}; }
1263
- return __awaiter(this, void 0, void 0, function () {
1264
- var featureFlags, response;
1265
- return __generator(this, function (_a) {
1266
- switch (_a.label) {
1267
- case 0: return [4 /*yield*/, this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1268
- case 1:
1269
- featureFlags = _a.sent();
1270
- if (!featureFlags) {
1271
- // If we haven't loaded flags yet, or errored out, we respond with undefined
1272
- return [2 /*return*/, undefined];
1273
- }
1274
- response = featureFlags[key];
1275
- // `/decide` v3 returns all flags
1276
- if (response === undefined) {
1277
- // For cases where the flag is unknown, return false
1278
- response = false;
1279
- }
1280
- // If we have flags we either return the value (true or string) or false
1281
- return [2 /*return*/, response];
1282
- }
1283
- });
1284
- });
1285
- };
1286
- PostHogCoreStateless.prototype.getFeatureFlagPayloadStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
1287
- if (groups === void 0) { groups = {}; }
1288
- if (personProperties === void 0) { personProperties = {}; }
1289
- if (groupProperties === void 0) { groupProperties = {}; }
1290
- return __awaiter(this, void 0, void 0, function () {
1291
- var payloads, response;
1292
- return __generator(this, function (_a) {
1293
- switch (_a.label) {
1294
- case 0: return [4 /*yield*/, this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1295
- case 1:
1296
- payloads = _a.sent();
1297
- if (!payloads) {
1298
- return [2 /*return*/, undefined];
1299
- }
1300
- response = payloads[key];
1301
- // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1302
- if (response === undefined) {
1303
- return [2 /*return*/, null];
1304
- }
1305
- return [2 /*return*/, this._parsePayload(response)];
1306
- }
1307
- });
1308
- });
1309
- };
1310
- PostHogCoreStateless.prototype.getFeatureFlagPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1311
- if (groups === void 0) { groups = {}; }
1312
- if (personProperties === void 0) { personProperties = {}; }
1313
- if (groupProperties === void 0) { groupProperties = {}; }
1314
- return __awaiter(this, void 0, void 0, function () {
1315
- var payloads;
1316
- var _this = this;
1317
- return __generator(this, function (_a) {
1318
- switch (_a.label) {
1319
- case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1320
- case 1:
1321
- payloads = (_a.sent()).payloads;
1322
- if (payloads) {
1323
- return [2 /*return*/, Object.fromEntries(Object.entries(payloads).map(function (_a) {
1324
- var k = _a[0], v = _a[1];
1325
- return [k, _this._parsePayload(v)];
1326
- }))];
1327
- }
1328
- return [2 /*return*/, payloads];
1329
- }
1330
- });
1105
+ async getDecide(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
1106
+ await this._initPromise;
1107
+ const url = `${this.host}/decide/?v=3`;
1108
+ const fetchOptions = {
1109
+ method: 'POST',
1110
+ headers: { 'Content-Type': 'application/json' },
1111
+ body: JSON.stringify({
1112
+ token: this.apiKey,
1113
+ distinct_id: distinctId,
1114
+ groups,
1115
+ person_properties: personProperties,
1116
+ group_properties: groupProperties,
1117
+ ...extraPayload,
1118
+ }),
1119
+ };
1120
+ // Don't retry /decide API calls
1121
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)
1122
+ .then((response) => response.json())
1123
+ .catch((error) => {
1124
+ this._events.emit('error', error);
1125
+ return undefined;
1331
1126
  });
1332
- };
1333
- PostHogCoreStateless.prototype._parsePayload = function (response) {
1127
+ }
1128
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1129
+ await this._initPromise;
1130
+ const featureFlags = await this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
1131
+ if (!featureFlags) {
1132
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
1133
+ return undefined;
1134
+ }
1135
+ let response = featureFlags[key];
1136
+ // `/decide` v3 returns all flags
1137
+ if (response === undefined) {
1138
+ // For cases where the flag is unknown, return false
1139
+ response = false;
1140
+ }
1141
+ // If we have flags we either return the value (true or string) or false
1142
+ return response;
1143
+ }
1144
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1145
+ await this._initPromise;
1146
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
1147
+ if (!payloads) {
1148
+ return undefined;
1149
+ }
1150
+ const response = payloads[key];
1151
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1152
+ if (response === undefined) {
1153
+ return null;
1154
+ }
1155
+ return this._parsePayload(response);
1156
+ }
1157
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1158
+ await this._initPromise;
1159
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)).payloads;
1160
+ if (payloads) {
1161
+ return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1162
+ }
1163
+ return payloads;
1164
+ }
1165
+ _parsePayload(response) {
1334
1166
  try {
1335
1167
  return JSON.parse(response);
1336
1168
  }
1337
- catch (_a) {
1169
+ catch {
1338
1170
  return response;
1339
1171
  }
1340
- };
1341
- PostHogCoreStateless.prototype.getFeatureFlagsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1342
- if (groups === void 0) { groups = {}; }
1343
- if (personProperties === void 0) { personProperties = {}; }
1344
- if (groupProperties === void 0) { groupProperties = {}; }
1345
- return __awaiter(this, void 0, void 0, function () {
1346
- return __generator(this, function (_a) {
1347
- switch (_a.label) {
1348
- case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
1349
- case 1: return [2 /*return*/, (_a.sent()).flags];
1350
- }
1351
- });
1352
- });
1353
- };
1354
- PostHogCoreStateless.prototype.getFeatureFlagsAndPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
1355
- if (groups === void 0) { groups = {}; }
1356
- if (personProperties === void 0) { personProperties = {}; }
1357
- if (groupProperties === void 0) { groupProperties = {}; }
1358
- return __awaiter(this, void 0, void 0, function () {
1359
- var extraPayload, decideResponse, flags, payloads;
1360
- return __generator(this, function (_a) {
1361
- switch (_a.label) {
1362
- case 0:
1363
- extraPayload = {};
1364
- if (disableGeoip !== null && disableGeoip !== void 0 ? disableGeoip : this.disableGeoip) {
1365
- extraPayload['geoip_disable'] = true;
1366
- }
1367
- return [4 /*yield*/, this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload)];
1368
- case 1:
1369
- decideResponse = _a.sent();
1370
- flags = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlags;
1371
- payloads = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlagPayloads;
1372
- return [2 /*return*/, {
1373
- flags: flags,
1374
- payloads: payloads,
1375
- }];
1376
- }
1377
- });
1378
- });
1379
- };
1172
+ }
1173
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1174
+ await this._initPromise;
1175
+ return (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)).flags;
1176
+ }
1177
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1178
+ await this._initPromise;
1179
+ const extraPayload = {};
1180
+ if (disableGeoip ?? this.disableGeoip) {
1181
+ extraPayload['geoip_disable'] = true;
1182
+ }
1183
+ const decideResponse = await this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload);
1184
+ const flags = decideResponse?.featureFlags;
1185
+ const payloads = decideResponse?.featureFlagPayloads;
1186
+ return {
1187
+ flags,
1188
+ payloads,
1189
+ };
1190
+ }
1380
1191
  /***
1381
1192
  *** QUEUEING AND FLUSHING
1382
1193
  ***/
1383
- PostHogCoreStateless.prototype.enqueue = function (type, _message, options) {
1384
- var _this = this;
1385
- var _a;
1386
- if (this.optedOut) {
1387
- this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1388
- return;
1389
- }
1390
- var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: (options === null || options === void 0 ? void 0 : options.timestamp) ? options === null || options === void 0 ? void 0 : options.timestamp : currentISOTime(), uuid: (options === null || options === void 0 ? void 0 : options.uuid) ? options.uuid : uuidv7() });
1391
- var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
1392
- if (addGeoipDisableProperty) {
1393
- if (!message.properties) {
1394
- message.properties = {};
1194
+ enqueue(type, _message, options) {
1195
+ this.wrap(() => {
1196
+ if (this.optedOut) {
1197
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
1198
+ return;
1199
+ }
1200
+ const message = {
1201
+ ..._message,
1202
+ type: type,
1203
+ library: this.getLibraryId(),
1204
+ library_version: this.getLibraryVersion(),
1205
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1206
+ uuid: options?.uuid ? options.uuid : uuidv7(),
1207
+ };
1208
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1209
+ if (addGeoipDisableProperty) {
1210
+ if (!message.properties) {
1211
+ message.properties = {};
1212
+ }
1213
+ message['properties']['$geoip_disable'] = true;
1214
+ }
1215
+ if (message.distinctId) {
1216
+ message.distinct_id = message.distinctId;
1217
+ delete message.distinctId;
1218
+ }
1219
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1220
+ queue.push({ message });
1221
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1222
+ this._events.emit(type, message);
1223
+ // Flush queued events if we meet the flushAt length
1224
+ if (queue.length >= this.flushAt) {
1225
+ this.flushBackground();
1226
+ }
1227
+ if (this.flushInterval && !this._flushTimer) {
1228
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
1395
1229
  }
1396
- message['properties']['$geoip_disable'] = true;
1397
- }
1398
- if (message.distinctId) {
1399
- message.distinct_id = message.distinctId;
1400
- delete message.distinctId;
1401
- }
1402
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1403
- queue.push({ message: message });
1404
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1405
- this._events.emit(type, message);
1406
- // Flush queued events if we meet the flushAt length
1407
- if (queue.length >= this.flushAt) {
1408
- this.flush();
1409
- }
1410
- if (this.flushInterval && !this._flushTimer) {
1411
- this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1412
- }
1413
- };
1414
- PostHogCoreStateless.prototype.flushAsync = function () {
1415
- var _this = this;
1416
- return new Promise(function (resolve, reject) {
1417
- _this.flush(function (err, data) {
1418
- return err ? reject(err) : resolve(data);
1419
- });
1420
1230
  });
1421
- };
1422
- PostHogCoreStateless.prototype.flush = function (callback) {
1423
- var _this = this;
1231
+ }
1232
+ clearFlushTimer() {
1424
1233
  if (this._flushTimer) {
1425
1234
  clearTimeout(this._flushTimer);
1426
- this._flushTimer = null;
1235
+ this._flushTimer = undefined;
1236
+ }
1237
+ }
1238
+ /**
1239
+ * Helper for flushing the queue in the background
1240
+ * Avoids unnecessary promise errors
1241
+ */
1242
+ flushBackground() {
1243
+ void this.flush().catch(() => { });
1244
+ }
1245
+ async flush() {
1246
+ if (!this.flushPromise) {
1247
+ this.flushPromise = this._flush().finally(() => {
1248
+ this.flushPromise = null;
1249
+ });
1250
+ this.addPendingPromise(this.flushPromise);
1427
1251
  }
1428
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1252
+ return this.flushPromise;
1253
+ }
1254
+ async _flush() {
1255
+ this.clearFlushTimer();
1256
+ await this._initPromise;
1257
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1429
1258
  if (!queue.length) {
1430
- return callback === null || callback === void 0 ? void 0 : callback();
1259
+ return [];
1431
1260
  }
1432
- var items = queue.splice(0, this.flushAt);
1433
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1434
- var messages = items.map(function (item) { return item.message; });
1435
- var data = {
1261
+ const items = queue.slice(0, this.maxBatchSize);
1262
+ const messages = items.map((item) => item.message);
1263
+ const persistQueueChange = () => {
1264
+ const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1265
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, refreshedQueue.slice(items.length));
1266
+ };
1267
+ const data = {
1436
1268
  api_key: this.apiKey,
1437
1269
  batch: messages,
1438
1270
  sent_at: currentISOTime(),
1439
1271
  };
1440
- var done = function (err) {
1441
- if (err) {
1442
- _this._events.emit('error', err);
1443
- }
1444
- callback === null || callback === void 0 ? void 0 : callback(err, messages);
1445
- _this._events.emit('flush', messages);
1446
- };
1447
1272
  // Don't set the user agent if we're not on a browser. The latest spec allows
1448
1273
  // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1449
1274
  // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1450
1275
  // but browsers such as Chrome and Safari have not caught up.
1451
1276
  this.getCustomUserAgent();
1452
- var payload = JSON.stringify(data);
1453
- var url = this.captureMode === 'form'
1454
- ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1455
- : "".concat(this.host, "/batch/");
1456
- var fetchOptions = this.captureMode === 'form'
1277
+ const payload = JSON.stringify(data);
1278
+ const url = this.captureMode === 'form'
1279
+ ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
1280
+ : `${this.host}/batch/`;
1281
+ const fetchOptions = this.captureMode === 'form'
1457
1282
  ? {
1458
1283
  method: 'POST',
1459
1284
  mode: 'no-cors',
1460
1285
  credentials: 'omit',
1461
1286
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1462
- body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1287
+ body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
1463
1288
  }
1464
1289
  : {
1465
1290
  method: 'POST',
1466
1291
  headers: { 'Content-Type': 'application/json' },
1467
1292
  body: payload,
1468
1293
  };
1469
- var requestPromise = this.fetchWithRetry(url, fetchOptions);
1470
- this.addPendingPromise(requestPromise
1471
- .then(function () { return done(); })
1472
- .catch(function (err) {
1473
- done(err);
1474
- }));
1475
- };
1476
- PostHogCoreStateless.prototype.fetchWithRetry = function (url, options, retryOptions) {
1294
+ try {
1295
+ await this.fetchWithRetry(url, fetchOptions);
1296
+ }
1297
+ catch (err) {
1298
+ // depending on the error type, eg a malformed JSON or broken queue, it'll always return an error
1299
+ // and this will be an endless loop, in this case, if the error isn't a network issue, we always remove the items from the queue
1300
+ if (!(err instanceof PostHogFetchNetworkError)) {
1301
+ persistQueueChange();
1302
+ }
1303
+ this._events.emit('error', err);
1304
+ throw err;
1305
+ }
1306
+ persistQueueChange();
1307
+ this._events.emit('flush', messages);
1308
+ return messages;
1309
+ }
1310
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1477
1311
  var _a;
1478
- var _b;
1479
- return __awaiter(this, void 0, void 0, function () {
1480
- var _this = this;
1481
- return __generator(this, function (_c) {
1482
- switch (_c.label) {
1483
- case 0:
1484
- (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1485
- var ctrl = new AbortController();
1486
- setTimeout(function () { return ctrl.abort(); }, ms);
1487
- return ctrl.signal;
1488
- });
1489
- return [4 /*yield*/, retriable(function () { return __awaiter(_this, void 0, void 0, function () {
1490
- var res, e_1, isNoCors;
1491
- return __generator(this, function (_a) {
1492
- switch (_a.label) {
1493
- case 0:
1494
- res = null;
1495
- _a.label = 1;
1496
- case 1:
1497
- _a.trys.push([1, 3, , 4]);
1498
- return [4 /*yield*/, this.fetch(url, __assign({ signal: AbortSignal.timeout(this.requestTimeout) }, options))];
1499
- case 2:
1500
- res = _a.sent();
1501
- return [3 /*break*/, 4];
1502
- case 3:
1503
- e_1 = _a.sent();
1504
- // fetch will only throw on network errors or on timeouts
1505
- throw new PostHogFetchNetworkError(e_1);
1506
- case 4:
1507
- isNoCors = options.mode === 'no-cors';
1508
- if (!isNoCors && (res.status < 200 || res.status >= 400)) {
1509
- throw new PostHogFetchHttpError(res);
1510
- }
1511
- return [2 /*return*/, res];
1512
- }
1513
- });
1514
- }); }, __assign(__assign({}, this._retryOptions), retryOptions))];
1515
- case 1: return [2 /*return*/, _c.sent()];
1516
- }
1517
- });
1312
+ (_a = AbortSignal).timeout ?? (_a.timeout = function timeout(ms) {
1313
+ const ctrl = new AbortController();
1314
+ setTimeout(() => ctrl.abort(), ms);
1315
+ return ctrl.signal;
1518
1316
  });
1519
- };
1520
- PostHogCoreStateless.prototype.shutdownAsync = function () {
1521
- return __awaiter(this, void 0, void 0, function () {
1522
- var e_2;
1523
- return __generator(this, function (_a) {
1524
- switch (_a.label) {
1525
- case 0:
1526
- clearTimeout(this._flushTimer);
1527
- _a.label = 1;
1528
- case 1:
1529
- _a.trys.push([1, 5, , 6]);
1530
- return [4 /*yield*/, this.flushAsync()];
1531
- case 2:
1532
- _a.sent();
1533
- return [4 /*yield*/, Promise.all(Object.values(this.pendingPromises).map(function (x) {
1534
- return x.catch(function () {
1535
- // ignore errors as we are shutting down and can't deal with them anyways.
1536
- });
1537
- }))
1538
- // flush again to make sure we send all events, some of which might've been added
1539
- // while we were waiting for the pending promises to resolve
1540
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1541
- ];
1542
- case 3:
1543
- _a.sent();
1544
- // flush again to make sure we send all events, some of which might've been added
1545
- // while we were waiting for the pending promises to resolve
1546
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1547
- return [4 /*yield*/, this.flushAsync()];
1548
- case 4:
1549
- // flush again to make sure we send all events, some of which might've been added
1550
- // while we were waiting for the pending promises to resolve
1551
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1552
- _a.sent();
1553
- return [3 /*break*/, 6];
1554
- case 5:
1555
- e_2 = _a.sent();
1556
- if (!isPostHogFetchError(e_2)) {
1557
- throw e_2;
1558
- }
1559
- console.error('Error while shutting down PostHog', e_2);
1560
- return [3 /*break*/, 6];
1561
- case 6: return [2 /*return*/];
1317
+ return await retriable(async () => {
1318
+ let res = null;
1319
+ try {
1320
+ res = await this.fetch(url, {
1321
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1322
+ ...options,
1323
+ });
1324
+ }
1325
+ catch (e) {
1326
+ // fetch will only throw on network errors or on timeouts
1327
+ throw new PostHogFetchNetworkError(e);
1328
+ }
1329
+ // If we're in no-cors mode, we can't access the response status
1330
+ // We only throw on HTTP errors if we're not in no-cors mode
1331
+ // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors
1332
+ const isNoCors = options.mode === 'no-cors';
1333
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) {
1334
+ throw new PostHogFetchHttpError(res);
1335
+ }
1336
+ return res;
1337
+ }, { ...this._retryOptions, ...retryOptions });
1338
+ }
1339
+ async shutdown(shutdownTimeoutMs = 30000) {
1340
+ await this._initPromise;
1341
+ this.clearFlushTimer();
1342
+ try {
1343
+ await Promise.all(Object.values(this.pendingPromises));
1344
+ const startTimeWithDelay = Date.now() + shutdownTimeoutMs;
1345
+ while (true) {
1346
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1347
+ if (queue.length === 0) {
1348
+ break;
1562
1349
  }
1563
- });
1564
- });
1565
- };
1566
- PostHogCoreStateless.prototype.shutdown = function () {
1567
- void this.shutdownAsync();
1568
- };
1569
- return PostHogCoreStateless;
1570
- }());
1571
- var PostHogCore = /** @class */ (function (_super) {
1572
- __extends(PostHogCore, _super);
1573
- function PostHogCore(apiKey, options) {
1574
- var _this = this;
1575
- var _a, _b, _c;
1350
+ // flush again to make sure we send all events, some of which might've been added
1351
+ // while we were waiting for the pending promises to resolve
1352
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1353
+ await this.flush();
1354
+ // If we've been waiting for more than the shutdownTimeoutMs, stop it
1355
+ const now = Date.now();
1356
+ if (startTimeWithDelay < now) {
1357
+ break;
1358
+ }
1359
+ }
1360
+ }
1361
+ catch (e) {
1362
+ if (!isPostHogFetchError(e)) {
1363
+ throw e;
1364
+ }
1365
+ console.error('Error while shutting down PostHog', e);
1366
+ }
1367
+ }
1368
+ }
1369
+ class PostHogCore extends PostHogCoreStateless {
1370
+ constructor(apiKey, options) {
1576
1371
  // Default for stateful mode is to not disable geoip. Only override if explicitly set
1577
- var disableGeoipOption = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : false;
1578
- _this = _super.call(this, apiKey, __assign(__assign({}, options), { disableGeoip: disableGeoipOption })) || this;
1579
- _this.flagCallReported = {};
1580
- _this.sessionProps = {};
1581
- _this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
1582
- _this._sessionExpirationTimeSeconds = (_c = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _c !== void 0 ? _c : 1800; // 30 minutes
1583
- return _this;
1584
- }
1585
- PostHogCore.prototype.setupBootstrap = function (options) {
1586
- var _a, _b, _c, _d;
1587
- if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
1588
- if ((_b = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _b === void 0 ? void 0 : _b.isIdentifiedId) {
1372
+ const disableGeoipOption = options?.disableGeoip ?? false;
1373
+ // Default for stateful mode is to timeout at 10s. Only override if explicitly set
1374
+ const featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 10000; // 10 seconds
1375
+ super(apiKey, { ...options, disableGeoip: disableGeoipOption, featureFlagsRequestTimeoutMs });
1376
+ this.flagCallReported = {};
1377
+ this.sessionProps = {};
1378
+ this.sendFeatureFlagEvent = options?.sendFeatureFlagEvent ?? true;
1379
+ this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800; // 30 minutes
1380
+ }
1381
+ setupBootstrap(options) {
1382
+ if (options?.bootstrap?.distinctId) {
1383
+ if (options?.bootstrap?.isIdentifiedId) {
1589
1384
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, options.bootstrap.distinctId);
1590
1385
  }
1591
1386
  else {
1592
1387
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, options.bootstrap.distinctId);
1593
1388
  }
1594
1389
  }
1595
- if ((_c = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _c === void 0 ? void 0 : _c.featureFlags) {
1596
- var activeFlags = Object.keys(((_d = options.bootstrap) === null || _d === void 0 ? void 0 : _d.featureFlags) || {})
1597
- .filter(function (flag) { var _a, _b; return !!((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[flag]); })
1598
- .reduce(function (res, key) {
1599
- var _a, _b;
1600
- return ((res[key] = ((_b = (_a = options.bootstrap) === null || _a === void 0 ? void 0 : _a.featureFlags) === null || _b === void 0 ? void 0 : _b[key]) || false), res);
1601
- }, {});
1390
+ if (options?.bootstrap?.featureFlags) {
1391
+ const activeFlags = Object.keys(options.bootstrap?.featureFlags || {})
1392
+ .filter((flag) => !!options.bootstrap?.featureFlags?.[flag])
1393
+ .reduce((res, key) => ((res[key] = options.bootstrap?.featureFlags?.[key] || false), res), {});
1602
1394
  this.setKnownFeatureFlags(activeFlags);
1603
- (options === null || options === void 0 ? void 0 : options.bootstrap.featureFlagPayloads) && this.setKnownFeatureFlagPayloads(options === null || options === void 0 ? void 0 : options.bootstrap.featureFlagPayloads);
1395
+ options?.bootstrap.featureFlagPayloads && this.setKnownFeatureFlagPayloads(options?.bootstrap.featureFlagPayloads);
1604
1396
  }
1605
- };
1606
- Object.defineProperty(PostHogCore.prototype, "props", {
1607
- // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
1608
- get: function () {
1609
- if (!this._props) {
1610
- this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
1611
- }
1612
- return this._props || {};
1613
- },
1614
- set: function (val) {
1615
- this._props = val;
1616
- },
1617
- enumerable: false,
1618
- configurable: true
1619
- });
1620
- PostHogCore.prototype.clearProps = function () {
1397
+ }
1398
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
1399
+ get props() {
1400
+ if (!this._props) {
1401
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
1402
+ }
1403
+ return this._props || {};
1404
+ }
1405
+ set props(val) {
1406
+ this._props = val;
1407
+ }
1408
+ clearProps() {
1621
1409
  this.props = undefined;
1622
1410
  this.sessionProps = {};
1623
- };
1624
- PostHogCore.prototype.on = function (event, cb) {
1411
+ }
1412
+ on(event, cb) {
1625
1413
  return this._events.on(event, cb);
1626
- };
1627
- PostHogCore.prototype.reset = function (propertiesToKeep) {
1628
- var allPropertiesToKeep = __spreadArray([PostHogPersistedProperty.Queue], (propertiesToKeep || []), true);
1629
- // clean up props
1630
- this.clearProps();
1631
- for (var _i = 0, _a = Object.keys(PostHogPersistedProperty); _i < _a.length; _i++) {
1632
- var key = _a[_i];
1633
- if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
1634
- this.setPersistedProperty(PostHogPersistedProperty[key], null);
1414
+ }
1415
+ reset(propertiesToKeep) {
1416
+ this.wrap(() => {
1417
+ const allPropertiesToKeep = [PostHogPersistedProperty.Queue, ...(propertiesToKeep || [])];
1418
+ // clean up props
1419
+ this.clearProps();
1420
+ for (const key of Object.keys(PostHogPersistedProperty)) {
1421
+ if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) {
1422
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
1423
+ }
1635
1424
  }
1636
- }
1637
- };
1638
- PostHogCore.prototype.getCommonEventProperties = function () {
1639
- var featureFlags = this.getFeatureFlags();
1640
- var featureVariantProperties = {};
1425
+ });
1426
+ }
1427
+ getCommonEventProperties() {
1428
+ const featureFlags = this.getFeatureFlags();
1429
+ const featureVariantProperties = {};
1641
1430
  if (featureFlags) {
1642
- for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
1643
- var _b = _a[_i], feature = _b[0], variant = _b[1];
1644
- featureVariantProperties["$feature/".concat(feature)] = variant;
1431
+ for (const [feature, variant] of Object.entries(featureFlags)) {
1432
+ featureVariantProperties[`$feature/${feature}`] = variant;
1645
1433
  }
1646
1434
  }
1647
- return __assign(__assign({ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties), _super.prototype.getCommonEventProperties.call(this));
1648
- };
1649
- PostHogCore.prototype.enrichProperties = function (properties) {
1650
- return __assign(__assign(__assign(__assign(__assign({}, this.props), this.sessionProps), (properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() });
1651
- };
1652
- PostHogCore.prototype.getSessionId = function () {
1653
- var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1654
- var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1435
+ return {
1436
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
1437
+ ...featureVariantProperties,
1438
+ ...super.getCommonEventProperties(),
1439
+ };
1440
+ }
1441
+ enrichProperties(properties) {
1442
+ return {
1443
+ ...this.props,
1444
+ ...this.sessionProps,
1445
+ ...(properties || {}),
1446
+ ...this.getCommonEventProperties(),
1447
+ $session_id: this.getSessionId(),
1448
+ };
1449
+ }
1450
+ /**
1451
+ * * @returns {string} The stored session ID for the current session. This may be an empty string if the client is not yet fully initialized.
1452
+ */
1453
+ getSessionId() {
1454
+ if (!this._isInitialized) {
1455
+ return '';
1456
+ }
1457
+ let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1458
+ const sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1655
1459
  if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
1656
1460
  sessionId = uuidv7();
1657
1461
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
1658
1462
  }
1659
1463
  this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
1660
1464
  return sessionId;
1661
- };
1662
- PostHogCore.prototype.resetSessionId = function () {
1663
- this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1664
- };
1665
- PostHogCore.prototype.getAnonymousId = function () {
1666
- var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1465
+ }
1466
+ resetSessionId() {
1467
+ this.wrap(() => {
1468
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
1469
+ });
1470
+ }
1471
+ /**
1472
+ * * @returns {string} The stored anonymous ID. This may be an empty string if the client is not yet fully initialized.
1473
+ */
1474
+ getAnonymousId() {
1475
+ if (!this._isInitialized) {
1476
+ return '';
1477
+ }
1478
+ let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1667
1479
  if (!anonId) {
1668
1480
  anonId = uuidv7();
1669
1481
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
1670
1482
  }
1671
1483
  return anonId;
1672
- };
1673
- PostHogCore.prototype.getDistinctId = function () {
1484
+ }
1485
+ /**
1486
+ * * @returns {string} The stored distinct ID. This may be an empty string if the client is not yet fully initialized.
1487
+ */
1488
+ getDistinctId() {
1489
+ if (!this._isInitialized) {
1490
+ return '';
1491
+ }
1674
1492
  return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
1675
- };
1676
- PostHogCore.prototype.unregister = function (property) {
1677
- delete this.props[property];
1678
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1679
- };
1680
- PostHogCore.prototype.register = function (properties) {
1681
- this.props = __assign(__assign({}, this.props), properties);
1682
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1683
- };
1684
- PostHogCore.prototype.registerForSession = function (properties) {
1685
- this.sessionProps = __assign(__assign({}, this.sessionProps), properties);
1686
- };
1687
- PostHogCore.prototype.unregisterForSession = function (property) {
1493
+ }
1494
+ async unregister(property) {
1495
+ this.wrap(() => {
1496
+ delete this.props[property];
1497
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1498
+ });
1499
+ }
1500
+ async register(properties) {
1501
+ this.wrap(() => {
1502
+ this.props = {
1503
+ ...this.props,
1504
+ ...properties,
1505
+ };
1506
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1507
+ });
1508
+ }
1509
+ registerForSession(properties) {
1510
+ this.sessionProps = {
1511
+ ...this.sessionProps,
1512
+ ...properties,
1513
+ };
1514
+ }
1515
+ unregisterForSession(property) {
1688
1516
  delete this.sessionProps[property];
1689
- };
1517
+ }
1690
1518
  /***
1691
1519
  *** TRACKING
1692
1520
  ***/
1693
- PostHogCore.prototype.identify = function (distinctId, properties, options) {
1694
- var previousDistinctId = this.getDistinctId();
1695
- distinctId = distinctId || previousDistinctId;
1696
- if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
1697
- this.groups(properties.$groups);
1698
- }
1699
- var allProperties = this.enrichProperties(__assign(__assign({}, properties), { $anon_distinct_id: this.getAnonymousId(), $set: properties }));
1700
- if (distinctId !== previousDistinctId) {
1701
- // We keep the AnonymousId to be used by decide calls and identify to link the previousId
1702
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
1703
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
1704
- this.reloadFeatureFlags();
1705
- }
1706
- _super.prototype.identifyStateless.call(this, distinctId, allProperties, options);
1707
- return this;
1708
- };
1709
- PostHogCore.prototype.capture = function (event, properties, options) {
1710
- var distinctId = this.getDistinctId();
1711
- if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
1712
- this.groups(properties.$groups);
1713
- }
1714
- var allProperties = this.enrichProperties(properties);
1715
- _super.prototype.captureStateless.call(this, distinctId, event, allProperties, options);
1716
- return this;
1717
- };
1718
- PostHogCore.prototype.alias = function (alias) {
1719
- var distinctId = this.getDistinctId();
1720
- var allProperties = this.enrichProperties({});
1721
- _super.prototype.aliasStateless.call(this, alias, distinctId, allProperties);
1722
- return this;
1723
- };
1724
- PostHogCore.prototype.autocapture = function (eventType, elements, properties, options) {
1725
- if (properties === void 0) { properties = {}; }
1726
- var distinctId = this.getDistinctId();
1727
- var payload = {
1728
- distinct_id: distinctId,
1729
- event: '$autocapture',
1730
- properties: __assign(__assign({}, this.enrichProperties(properties)), { $event_type: eventType, $elements: elements }),
1731
- };
1732
- this.enqueue('autocapture', payload, options);
1733
- return this;
1734
- };
1521
+ identify(distinctId, properties, options) {
1522
+ this.wrap(() => {
1523
+ const previousDistinctId = this.getDistinctId();
1524
+ distinctId = distinctId || previousDistinctId;
1525
+ if (properties?.$groups) {
1526
+ this.groups(properties.$groups);
1527
+ }
1528
+ const allProperties = this.enrichProperties({
1529
+ ...properties,
1530
+ $anon_distinct_id: this.getAnonymousId(),
1531
+ $set: properties,
1532
+ });
1533
+ if (distinctId !== previousDistinctId) {
1534
+ // We keep the AnonymousId to be used by decide calls and identify to link the previousId
1535
+ this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
1536
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
1537
+ this.reloadFeatureFlags();
1538
+ }
1539
+ super.identifyStateless(distinctId, allProperties, options);
1540
+ });
1541
+ }
1542
+ capture(event, properties, options) {
1543
+ this.wrap(() => {
1544
+ const distinctId = this.getDistinctId();
1545
+ if (properties?.$groups) {
1546
+ this.groups(properties.$groups);
1547
+ }
1548
+ const allProperties = this.enrichProperties(properties);
1549
+ super.captureStateless(distinctId, event, allProperties, options);
1550
+ });
1551
+ }
1552
+ alias(alias) {
1553
+ this.wrap(() => {
1554
+ const distinctId = this.getDistinctId();
1555
+ const allProperties = this.enrichProperties({});
1556
+ super.aliasStateless(alias, distinctId, allProperties);
1557
+ });
1558
+ }
1559
+ autocapture(eventType, elements, properties = {}, options) {
1560
+ this.wrap(() => {
1561
+ const distinctId = this.getDistinctId();
1562
+ const payload = {
1563
+ distinct_id: distinctId,
1564
+ event: '$autocapture',
1565
+ properties: {
1566
+ ...this.enrichProperties(properties),
1567
+ $event_type: eventType,
1568
+ $elements: elements,
1569
+ },
1570
+ };
1571
+ this.enqueue('autocapture', payload, options);
1572
+ });
1573
+ }
1735
1574
  /***
1736
1575
  *** GROUPS
1737
1576
  ***/
1738
- PostHogCore.prototype.groups = function (groups) {
1739
- // Get persisted groups
1740
- var existingGroups = this.props.$groups || {};
1741
- this.register({
1742
- $groups: __assign(__assign({}, existingGroups), groups),
1577
+ groups(groups) {
1578
+ this.wrap(() => {
1579
+ // Get persisted groups
1580
+ const existingGroups = this.props.$groups || {};
1581
+ this.register({
1582
+ $groups: {
1583
+ ...existingGroups,
1584
+ ...groups,
1585
+ },
1586
+ });
1587
+ if (Object.keys(groups).find((type) => existingGroups[type] !== groups[type])) {
1588
+ this.reloadFeatureFlags();
1589
+ }
1743
1590
  });
1744
- if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; })) {
1745
- this.reloadFeatureFlags();
1746
- }
1747
- return this;
1748
- };
1749
- PostHogCore.prototype.group = function (groupType, groupKey, groupProperties, options) {
1750
- var _a;
1751
- this.groups((_a = {},
1752
- _a[groupType] = groupKey,
1753
- _a));
1754
- if (groupProperties) {
1755
- this.groupIdentify(groupType, groupKey, groupProperties, options);
1756
- }
1757
- return this;
1758
- };
1759
- PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties, options) {
1760
- var distinctId = this.getDistinctId();
1761
- var eventProperties = this.enrichProperties({});
1762
- _super.prototype.groupIdentifyStateless.call(this, groupType, groupKey, groupProperties, options, distinctId, eventProperties);
1763
- return this;
1764
- };
1591
+ }
1592
+ group(groupType, groupKey, groupProperties, options) {
1593
+ this.wrap(() => {
1594
+ this.groups({
1595
+ [groupType]: groupKey,
1596
+ });
1597
+ if (groupProperties) {
1598
+ this.groupIdentify(groupType, groupKey, groupProperties, options);
1599
+ }
1600
+ });
1601
+ }
1602
+ groupIdentify(groupType, groupKey, groupProperties, options) {
1603
+ this.wrap(() => {
1604
+ const distinctId = this.getDistinctId();
1605
+ const eventProperties = this.enrichProperties({});
1606
+ super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);
1607
+ });
1608
+ }
1765
1609
  /***
1766
1610
  * PROPERTIES
1767
1611
  ***/
1768
- PostHogCore.prototype.setPersonPropertiesForFlags = function (properties) {
1769
- // Get persisted person properties
1770
- var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1771
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, __assign(__assign({}, existingProperties), properties));
1772
- return this;
1773
- };
1774
- PostHogCore.prototype.resetPersonPropertiesForFlags = function () {
1775
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {});
1776
- };
1612
+ setPersonPropertiesForFlags(properties) {
1613
+ this.wrap(() => {
1614
+ // Get persisted person properties
1615
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1616
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {
1617
+ ...existingProperties,
1618
+ ...properties,
1619
+ });
1620
+ });
1621
+ }
1622
+ resetPersonPropertiesForFlags() {
1623
+ this.wrap(() => {
1624
+ this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {});
1625
+ });
1626
+ }
1777
1627
  /** @deprecated - Renamed to setPersonPropertiesForFlags */
1778
- PostHogCore.prototype.personProperties = function (properties) {
1628
+ personProperties(properties) {
1779
1629
  return this.setPersonPropertiesForFlags(properties);
1780
- };
1781
- PostHogCore.prototype.setGroupPropertiesForFlags = function (properties) {
1782
- // Get persisted group properties
1783
- var existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
1784
- if (Object.keys(existingProperties).length !== 0) {
1785
- Object.keys(existingProperties).forEach(function (groupType) {
1786
- existingProperties[groupType] = __assign(__assign({}, existingProperties[groupType]), properties[groupType]);
1787
- delete properties[groupType];
1630
+ }
1631
+ setGroupPropertiesForFlags(properties) {
1632
+ this.wrap(() => {
1633
+ // Get persisted group properties
1634
+ const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) ||
1635
+ {};
1636
+ if (Object.keys(existingProperties).length !== 0) {
1637
+ Object.keys(existingProperties).forEach((groupType) => {
1638
+ existingProperties[groupType] = {
1639
+ ...existingProperties[groupType],
1640
+ ...properties[groupType],
1641
+ };
1642
+ delete properties[groupType];
1643
+ });
1644
+ }
1645
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {
1646
+ ...existingProperties,
1647
+ ...properties,
1788
1648
  });
1789
- }
1790
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, __assign(__assign({}, existingProperties), properties));
1791
- return this;
1792
- };
1793
- PostHogCore.prototype.resetGroupPropertiesForFlags = function () {
1794
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {});
1795
- };
1649
+ });
1650
+ }
1651
+ resetGroupPropertiesForFlags() {
1652
+ this.wrap(() => {
1653
+ this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {});
1654
+ });
1655
+ }
1796
1656
  /** @deprecated - Renamed to setGroupPropertiesForFlags */
1797
- PostHogCore.prototype.groupProperties = function (properties) {
1798
- return this.setGroupPropertiesForFlags(properties);
1799
- };
1657
+ groupProperties(properties) {
1658
+ this.wrap(() => {
1659
+ this.setGroupPropertiesForFlags(properties);
1660
+ });
1661
+ }
1800
1662
  /***
1801
1663
  *** FEATURE FLAGS
1802
1664
  ***/
1803
- PostHogCore.prototype.decideAsync = function (sendAnonDistinctId) {
1804
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1665
+ async decideAsync(sendAnonDistinctId = true) {
1666
+ await this._initPromise;
1805
1667
  if (this._decideResponsePromise) {
1806
1668
  return this._decideResponsePromise;
1807
1669
  }
1808
1670
  return this._decideAsync(sendAnonDistinctId);
1809
- };
1810
- PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
1811
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1812
- return __awaiter(this, void 0, void 0, function () {
1813
- var distinctId, groups, personProperties, groupProperties, extraProperties;
1814
- var _this = this;
1815
- return __generator(this, function (_a) {
1816
- distinctId = this.getDistinctId();
1817
- groups = this.props.$groups || {};
1818
- personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1819
- groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
1820
- extraProperties = {
1821
- $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
1822
- };
1823
- this._decideResponsePromise = _super.prototype.getDecide.call(this, distinctId, groups, personProperties, groupProperties, extraProperties)
1824
- .then(function (res) {
1825
- if (res === null || res === void 0 ? void 0 : res.featureFlags) {
1826
- var newFeatureFlags = res.featureFlags;
1827
- var newFeatureFlagPayloads = res.featureFlagPayloads;
1828
- if (res.errorsWhileComputingFlags) {
1829
- // if not all flags were computed, we upsert flags instead of replacing them
1830
- var currentFlags = _this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1831
- var currentFlagPayloads = _this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1832
- newFeatureFlags = __assign(__assign({}, currentFlags), res.featureFlags);
1833
- newFeatureFlagPayloads = __assign(__assign({}, currentFlagPayloads), res.featureFlagPayloads);
1834
- }
1835
- _this.setKnownFeatureFlags(newFeatureFlags);
1836
- _this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1671
+ }
1672
+ async _decideAsync(sendAnonDistinctId = true) {
1673
+ this._decideResponsePromise = this._initPromise
1674
+ .then(() => {
1675
+ const distinctId = this.getDistinctId();
1676
+ const groups = this.props.$groups || {};
1677
+ const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
1678
+ const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) ||
1679
+ {};
1680
+ const extraProperties = {
1681
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
1682
+ };
1683
+ return super.getDecide(distinctId, groups, personProperties, groupProperties, extraProperties).then((res) => {
1684
+ if (res?.featureFlags) {
1685
+ let newFeatureFlags = res.featureFlags;
1686
+ let newFeatureFlagPayloads = res.featureFlagPayloads;
1687
+ if (res.errorsWhileComputingFlags) {
1688
+ // if not all flags were computed, we upsert flags instead of replacing them
1689
+ const currentFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1690
+ const currentFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1691
+ newFeatureFlags = { ...currentFlags, ...res.featureFlags };
1692
+ newFeatureFlagPayloads = { ...currentFlagPayloads, ...res.featureFlagPayloads };
1837
1693
  }
1838
- return res;
1839
- })
1840
- .finally(function () {
1841
- _this._decideResponsePromise = undefined;
1842
- });
1843
- return [2 /*return*/, this._decideResponsePromise];
1694
+ this.setKnownFeatureFlags(newFeatureFlags);
1695
+ this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1696
+ }
1697
+ return res;
1844
1698
  });
1699
+ })
1700
+ .finally(() => {
1701
+ this._decideResponsePromise = undefined;
1845
1702
  });
1846
- };
1847
- PostHogCore.prototype.setKnownFeatureFlags = function (featureFlags) {
1848
- this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1849
- this._events.emit('featureflags', featureFlags);
1850
- };
1851
- PostHogCore.prototype.setKnownFeatureFlagPayloads = function (featureFlagPayloads) {
1852
- this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads, featureFlagPayloads);
1853
- };
1854
- PostHogCore.prototype.getFeatureFlag = function (key) {
1855
- var featureFlags = this.getFeatureFlags();
1703
+ return this._decideResponsePromise;
1704
+ }
1705
+ setKnownFeatureFlags(featureFlags) {
1706
+ this.wrap(() => {
1707
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, featureFlags);
1708
+ this._events.emit('featureflags', featureFlags);
1709
+ });
1710
+ }
1711
+ setKnownFeatureFlagPayloads(featureFlagPayloads) {
1712
+ this.wrap(() => {
1713
+ this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads, featureFlagPayloads);
1714
+ });
1715
+ }
1716
+ getFeatureFlag(key) {
1717
+ const featureFlags = this.getFeatureFlags();
1856
1718
  if (!featureFlags) {
1857
1719
  // If we haven't loaded flags yet, or errored out, we respond with undefined
1858
1720
  return undefined;
1859
1721
  }
1860
- var response = featureFlags[key];
1722
+ let response = featureFlags[key];
1861
1723
  // `/decide` v3 returns all flags
1862
1724
  if (response === undefined) {
1863
1725
  // For cases where the flag is unknown, return false
@@ -1872,38 +1734,36 @@ var PostHogCore = /** @class */ (function (_super) {
1872
1734
  }
1873
1735
  // If we have flags we either return the value (true or string) or false
1874
1736
  return response;
1875
- };
1876
- PostHogCore.prototype.getFeatureFlagPayload = function (key) {
1877
- var payloads = this.getFeatureFlagPayloads();
1737
+ }
1738
+ getFeatureFlagPayload(key) {
1739
+ const payloads = this.getFeatureFlagPayloads();
1878
1740
  if (!payloads) {
1879
1741
  return undefined;
1880
1742
  }
1881
- var response = payloads[key];
1743
+ const response = payloads[key];
1882
1744
  // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1883
1745
  if (response === undefined) {
1884
1746
  return null;
1885
1747
  }
1886
1748
  return this._parsePayload(response);
1887
- };
1888
- PostHogCore.prototype.getFeatureFlagPayloads = function () {
1889
- var _this = this;
1890
- var payloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1749
+ }
1750
+ getFeatureFlagPayloads() {
1751
+ const payloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1891
1752
  if (payloads) {
1892
- return Object.fromEntries(Object.entries(payloads).map(function (_a) {
1893
- var k = _a[0], v = _a[1];
1894
- return [k, _this._parsePayload(v)];
1895
- }));
1753
+ return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1896
1754
  }
1897
1755
  return payloads;
1898
- };
1899
- PostHogCore.prototype.getFeatureFlags = function () {
1900
- var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1901
- var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1756
+ }
1757
+ getFeatureFlags() {
1758
+ // NOTE: We don't check for _initPromise here as the function is designed to be
1759
+ // callable before the state being loaded anyways
1760
+ let flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1761
+ const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1902
1762
  if (!overriddenFlags) {
1903
1763
  return flags;
1904
1764
  }
1905
1765
  flags = flags || {};
1906
- for (var key in overriddenFlags) {
1766
+ for (const key in overriddenFlags) {
1907
1767
  if (!overriddenFlags[key]) {
1908
1768
  delete flags[key];
1909
1769
  }
@@ -1912,90 +1772,72 @@ var PostHogCore = /** @class */ (function (_super) {
1912
1772
  }
1913
1773
  }
1914
1774
  return flags;
1915
- };
1916
- PostHogCore.prototype.getFeatureFlagsAndPayloads = function () {
1917
- var flags = this.getFeatureFlags();
1918
- var payloads = this.getFeatureFlagPayloads();
1775
+ }
1776
+ getFeatureFlagsAndPayloads() {
1777
+ const flags = this.getFeatureFlags();
1778
+ const payloads = this.getFeatureFlagPayloads();
1919
1779
  return {
1920
- flags: flags,
1921
- payloads: payloads,
1780
+ flags,
1781
+ payloads,
1922
1782
  };
1923
- };
1924
- PostHogCore.prototype.isFeatureEnabled = function (key) {
1925
- var response = this.getFeatureFlag(key);
1783
+ }
1784
+ isFeatureEnabled(key) {
1785
+ const response = this.getFeatureFlag(key);
1926
1786
  if (response === undefined) {
1927
1787
  return undefined;
1928
1788
  }
1929
1789
  return !!response;
1930
- };
1790
+ }
1931
1791
  // Used when we want to trigger the reload but we don't care about the result
1932
- PostHogCore.prototype.reloadFeatureFlags = function (cb) {
1792
+ reloadFeatureFlags(cb) {
1933
1793
  this.decideAsync()
1934
- .then(function (res) {
1935
- cb === null || cb === void 0 ? void 0 : cb(undefined, res === null || res === void 0 ? void 0 : res.featureFlags);
1794
+ .then((res) => {
1795
+ cb?.(undefined, res?.featureFlags);
1936
1796
  })
1937
- .catch(function (e) {
1938
- cb === null || cb === void 0 ? void 0 : cb(e, undefined);
1797
+ .catch((e) => {
1798
+ cb?.(e, undefined);
1939
1799
  if (!cb) {
1940
1800
  console.log('[PostHog] Error reloading feature flags', e);
1941
1801
  }
1942
1802
  });
1943
- };
1944
- PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1945
- var _a;
1946
- if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1947
- return __awaiter(this, void 0, void 0, function () {
1948
- return __generator(this, function (_b) {
1949
- switch (_b.label) {
1950
- case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
1951
- case 1: return [2 /*return*/, (_a = (_b.sent())) === null || _a === void 0 ? void 0 : _a.featureFlags];
1952
- }
1953
- });
1803
+ }
1804
+ async reloadFeatureFlagsAsync(sendAnonDistinctId = true) {
1805
+ return (await this.decideAsync(sendAnonDistinctId))?.featureFlags;
1806
+ }
1807
+ onFeatureFlags(cb) {
1808
+ return this.on('featureflags', async () => {
1809
+ const flags = this.getFeatureFlags();
1810
+ if (flags) {
1811
+ cb(flags);
1812
+ }
1954
1813
  });
1955
- };
1956
- PostHogCore.prototype.onFeatureFlags = function (cb) {
1957
- var _this = this;
1958
- return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1959
- var flags;
1960
- return __generator(this, function (_a) {
1961
- flags = this.getFeatureFlags();
1962
- if (flags) {
1963
- cb(flags);
1964
- }
1965
- return [2 /*return*/];
1966
- });
1967
- }); });
1968
- };
1969
- PostHogCore.prototype.onFeatureFlag = function (key, cb) {
1970
- var _this = this;
1971
- return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
1972
- var flagResponse;
1973
- return __generator(this, function (_a) {
1974
- flagResponse = this.getFeatureFlag(key);
1975
- if (flagResponse !== undefined) {
1976
- cb(flagResponse);
1977
- }
1978
- return [2 /*return*/];
1979
- });
1980
- }); });
1981
- };
1982
- PostHogCore.prototype.overrideFeatureFlag = function (flags) {
1983
- if (flags === null) {
1984
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1985
- }
1986
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1987
- };
1988
- return PostHogCore;
1989
- }(PostHogCoreStateless));
1814
+ }
1815
+ onFeatureFlag(key, cb) {
1816
+ return this.on('featureflags', async () => {
1817
+ const flagResponse = this.getFeatureFlag(key);
1818
+ if (flagResponse !== undefined) {
1819
+ cb(flagResponse);
1820
+ }
1821
+ });
1822
+ }
1823
+ async overrideFeatureFlag(flags) {
1824
+ this.wrap(() => {
1825
+ if (flags === null) {
1826
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1827
+ }
1828
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1829
+ });
1830
+ }
1831
+ }
1990
1832
 
1991
- var version = "2.6.2";
1833
+ var version = "3.0.0-beta.2";
1992
1834
 
1993
1835
  function getContext(window) {
1994
- var context = {};
1836
+ let context = {};
1995
1837
 
1996
1838
  if (window.navigator) {
1997
- var userAgent = window.navigator.userAgent;
1998
- context = __assign(__assign({}, context), {
1839
+ const userAgent = window.navigator.userAgent;
1840
+ context = { ...context,
1999
1841
  $os: os(window),
2000
1842
  $browser: browser(userAgent, window.navigator.vendor, !!window.opera),
2001
1843
  $referrer: window.document.referrer,
@@ -2008,15 +1850,16 @@ function getContext(window) {
2008
1850
  $screen_height: window.screen.height,
2009
1851
  $screen_width: window.screen.width,
2010
1852
  $screen_dpr: window.devicePixelRatio
2011
- });
1853
+ };
2012
1854
  }
2013
1855
 
2014
- context = __assign(__assign({}, context), {
1856
+ context = { ...context,
2015
1857
  $lib: 'js',
2016
1858
  $lib_version: version,
2017
1859
  $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
2018
- $time: currentTimestamp() / 1000
2019
- });
1860
+ $time: currentTimestamp() / 1000 // epoch time in seconds
1861
+
1862
+ };
2020
1863
  return context; // TODO: strip empty props?
2021
1864
  }
2022
1865
 
@@ -2074,7 +1917,7 @@ function browser(userAgent, vendor, opera) {
2074
1917
  }
2075
1918
 
2076
1919
  function browserVersion(userAgent, vendor, opera) {
2077
- var regexList = {
1920
+ const regexList = {
2078
1921
  'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
2079
1922
  'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
2080
1923
  Chrome: /Chrome\/(\d+(\.\d+)?)/,
@@ -2092,14 +1935,14 @@ function browserVersion(userAgent, vendor, opera) {
2092
1935
  'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
2093
1936
  Mozilla: /rv:(\d+(\.\d+)?)/
2094
1937
  };
2095
- var browserString = browser(userAgent, vendor, opera);
2096
- var regex = regexList[browserString] || undefined;
1938
+ const browserString = browser(userAgent, vendor, opera);
1939
+ const regex = regexList[browserString] || undefined;
2097
1940
 
2098
1941
  if (regex === undefined) {
2099
1942
  return null;
2100
1943
  }
2101
1944
 
2102
- var matches = userAgent.match(regex);
1945
+ const matches = userAgent.match(regex);
2103
1946
 
2104
1947
  if (!matches) {
2105
1948
  return null;
@@ -2109,7 +1952,7 @@ function browserVersion(userAgent, vendor, opera) {
2109
1952
  }
2110
1953
 
2111
1954
  function os(window) {
2112
- var a = window.navigator.userAgent;
1955
+ const a = window.navigator.userAgent;
2113
1956
 
2114
1957
  if (/Windows/i.test(a)) {
2115
1958
  if (/Phone/.test(a) || /WPDesktop/.test(a)) {
@@ -2153,7 +1996,7 @@ function device(userAgent) {
2153
1996
  }
2154
1997
 
2155
1998
  function referringDomain(referrer) {
2156
- var split = referrer.split('/');
1999
+ const split = referrer.split('/');
2157
2000
 
2158
2001
  if (split.length >= 3) {
2159
2002
  return split[2];
@@ -2163,14 +2006,14 @@ function referringDomain(referrer) {
2163
2006
  }
2164
2007
 
2165
2008
  // Methods partially borrowed from quirksmode.org/js/cookies.html
2166
- var cookieStore = {
2167
- getItem: function (key) {
2009
+ const cookieStore = {
2010
+ getItem(key) {
2168
2011
  try {
2169
- var nameEQ = key + '=';
2170
- var ca = document.cookie.split(';');
2012
+ const nameEQ = key + '=';
2013
+ const ca = document.cookie.split(';');
2171
2014
 
2172
- for (var i = 0; i < ca.length; i++) {
2173
- var c = ca[i];
2015
+ for (let i = 0; i < ca.length; i++) {
2016
+ let c = ca[i];
2174
2017
 
2175
2018
  while (c.charAt(0) == ' ') {
2176
2019
  c = c.substring(1, c.length);
@@ -2184,33 +2027,37 @@ var cookieStore = {
2184
2027
 
2185
2028
  return null;
2186
2029
  },
2187
- setItem: function (key, value) {
2030
+
2031
+ setItem(key, value) {
2188
2032
  try {
2189
- var cdomain = '',
2190
- expires = '',
2191
- secure = '';
2192
- var new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2033
+ const cdomain = '',
2034
+ expires = '',
2035
+ secure = '';
2036
+ const new_cookie_val = key + '=' + encodeURIComponent(value) + expires + '; path=/' + cdomain + secure;
2193
2037
  document.cookie = new_cookie_val;
2194
2038
  } catch (err) {
2195
2039
  return;
2196
2040
  }
2197
2041
  },
2198
- removeItem: function (name) {
2042
+
2043
+ removeItem(name) {
2199
2044
  try {
2200
2045
  cookieStore.setItem(name, '');
2201
2046
  } catch (err) {
2202
2047
  return;
2203
2048
  }
2204
2049
  },
2205
- clear: function () {
2050
+
2051
+ clear() {
2206
2052
  document.cookie = '';
2207
2053
  },
2208
- getAllKeys: function () {
2209
- var ca = document.cookie.split(';');
2210
- var keys = [];
2211
2054
 
2212
- for (var i = 0; i < ca.length; i++) {
2213
- var c = ca[i];
2055
+ getAllKeys() {
2056
+ const ca = document.cookie.split(';');
2057
+ const keys = [];
2058
+
2059
+ for (let i = 0; i < ca.length; i++) {
2060
+ let c = ca[i];
2214
2061
 
2215
2062
  while (c.charAt(0) == ' ') {
2216
2063
  c = c.substring(1, c.length);
@@ -2221,45 +2068,47 @@ var cookieStore = {
2221
2068
 
2222
2069
  return keys;
2223
2070
  }
2071
+
2224
2072
  };
2225
2073
 
2226
- var createStorageLike = function (store) {
2074
+ const createStorageLike = store => {
2227
2075
  return {
2228
- getItem: function (key) {
2076
+ getItem(key) {
2229
2077
  return store.getItem(key);
2230
2078
  },
2231
- setItem: function (key, value) {
2079
+
2080
+ setItem(key, value) {
2232
2081
  store.setItem(key, value);
2233
2082
  },
2234
- removeItem: function (key) {
2083
+
2084
+ removeItem(key) {
2235
2085
  store.removeItem(key);
2236
2086
  },
2237
- clear: function () {
2087
+
2088
+ clear() {
2238
2089
  store.clear();
2239
2090
  },
2240
- getAllKeys: function () {
2241
- var keys = [];
2242
2091
 
2243
- for (var key in localStorage) {
2092
+ getAllKeys() {
2093
+ const keys = [];
2094
+
2095
+ for (const key in localStorage) {
2244
2096
  keys.push(key);
2245
2097
  }
2246
2098
 
2247
2099
  return keys;
2248
2100
  }
2101
+
2249
2102
  };
2250
2103
  };
2251
2104
 
2252
- var checkStoreIsSupported = function (storage, key) {
2253
- if (key === void 0) {
2254
- key = '__mplssupport__';
2255
- }
2256
-
2105
+ const checkStoreIsSupported = (storage, key = '__mplssupport__') => {
2257
2106
  if (!window) {
2258
2107
  return false;
2259
2108
  }
2260
2109
 
2261
2110
  try {
2262
- var val = 'xyz';
2111
+ const val = 'xyz';
2263
2112
  storage.setItem(key, val);
2264
2113
 
2265
2114
  if (storage.getItem(key) !== val) {
@@ -2273,49 +2122,54 @@ var checkStoreIsSupported = function (storage, key) {
2273
2122
  }
2274
2123
  };
2275
2124
 
2276
- var localStore = undefined;
2277
- var sessionStore = undefined;
2125
+ let localStore = undefined;
2126
+ let sessionStore = undefined;
2278
2127
 
2279
- var createMemoryStorage = function () {
2280
- var _cache = {};
2281
- var store = {
2282
- getItem: function (key) {
2128
+ const createMemoryStorage = () => {
2129
+ const _cache = {};
2130
+ const store = {
2131
+ getItem(key) {
2283
2132
  return _cache[key];
2284
2133
  },
2285
- setItem: function (key, value) {
2134
+
2135
+ setItem(key, value) {
2286
2136
  _cache[key] = value !== null ? value : undefined;
2287
2137
  },
2288
- removeItem: function (key) {
2138
+
2139
+ removeItem(key) {
2289
2140
  delete _cache[key];
2290
2141
  },
2291
- clear: function () {
2292
- for (var key in _cache) {
2142
+
2143
+ clear() {
2144
+ for (const key in _cache) {
2293
2145
  delete _cache[key];
2294
2146
  }
2295
2147
  },
2296
- getAllKeys: function () {
2297
- var keys = [];
2298
2148
 
2299
- for (var key in _cache) {
2149
+ getAllKeys() {
2150
+ const keys = [];
2151
+
2152
+ for (const key in _cache) {
2300
2153
  keys.push(key);
2301
2154
  }
2302
2155
 
2303
2156
  return keys;
2304
2157
  }
2158
+
2305
2159
  };
2306
2160
  return store;
2307
2161
  };
2308
2162
 
2309
- var getStorage = function (type, window) {
2163
+ const getStorage = (type, window) => {
2310
2164
  if (window) {
2311
2165
  if (!localStorage) {
2312
- var _localStore = createStorageLike(window.localStorage);
2166
+ const _localStore = createStorageLike(window.localStorage);
2313
2167
 
2314
2168
  localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
2315
2169
  }
2316
2170
 
2317
2171
  if (!sessionStore) {
2318
- var _sessionStore = createStorageLike(window.sessionStorage);
2172
+ const _sessionStore = createStorageLike(window.sessionStorage);
2319
2173
 
2320
2174
  sessionStore = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
2321
2175
  }
@@ -2339,36 +2193,28 @@ var getStorage = function (type, window) {
2339
2193
  }
2340
2194
  };
2341
2195
 
2342
- var PostHog =
2343
- /** @class */
2344
- function (_super) {
2345
- __extends(PostHog, _super);
2346
-
2347
- function PostHog(apiKey, options) {
2348
- var _this = _super.call(this, apiKey, options) || this; // posthog-js stores options in one object on
2349
-
2350
-
2351
- _this._storageKey = (options === null || options === void 0 ? void 0 : options.persistence_name) ? "ph_".concat(options.persistence_name) : "ph_".concat(apiKey, "_posthog");
2352
- _this._storage = getStorage((options === null || options === void 0 ? void 0 : options.persistence) || 'localStorage', window);
2196
+ class PostHog extends PostHogCore {
2197
+ constructor(apiKey, options) {
2198
+ super(apiKey, options); // posthog-js stores options in one object on
2353
2199
 
2354
- _this.setupBootstrap(options);
2200
+ this._storageKey = options?.persistence_name ? `ph_${options.persistence_name}` : `ph_${apiKey}_posthog`;
2201
+ this._storage = getStorage(options?.persistence || 'localStorage', window);
2202
+ this.setupBootstrap(options);
2355
2203
 
2356
- if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
2357
- _this.reloadFeatureFlags();
2204
+ if (options?.preloadFeatureFlags !== false) {
2205
+ this.reloadFeatureFlags();
2358
2206
  }
2359
-
2360
- return _this;
2361
2207
  }
2362
2208
 
2363
- PostHog.prototype.getPersistedProperty = function (key) {
2209
+ getPersistedProperty(key) {
2364
2210
  if (!this._storageCache) {
2365
2211
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2366
2212
  }
2367
2213
 
2368
2214
  return this._storageCache[key];
2369
- };
2215
+ }
2370
2216
 
2371
- PostHog.prototype.setPersistedProperty = function (key, value) {
2217
+ setPersistedProperty(key, value) {
2372
2218
  if (!this._storageCache) {
2373
2219
  this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
2374
2220
  }
@@ -2380,30 +2226,31 @@ function (_super) {
2380
2226
  }
2381
2227
 
2382
2228
  this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
2383
- };
2229
+ }
2384
2230
 
2385
- PostHog.prototype.fetch = function (url, options) {
2231
+ fetch(url, options) {
2386
2232
  return window.fetch(url, options);
2387
- };
2233
+ }
2388
2234
 
2389
- PostHog.prototype.getLibraryId = function () {
2235
+ getLibraryId() {
2390
2236
  return 'posthog-js-lite';
2391
- };
2237
+ }
2392
2238
 
2393
- PostHog.prototype.getLibraryVersion = function () {
2239
+ getLibraryVersion() {
2394
2240
  return version;
2395
- };
2241
+ }
2396
2242
 
2397
- PostHog.prototype.getCustomUserAgent = function () {
2243
+ getCustomUserAgent() {
2398
2244
  return;
2399
- };
2245
+ }
2400
2246
 
2401
- PostHog.prototype.getCommonEventProperties = function () {
2402
- return __assign(__assign({}, _super.prototype.getCommonEventProperties.call(this)), getContext(window));
2403
- };
2247
+ getCommonEventProperties() {
2248
+ return { ...super.getCommonEventProperties(),
2249
+ ...getContext(window)
2250
+ };
2251
+ }
2404
2252
 
2405
- return PostHog;
2406
- }(PostHogCore);
2253
+ }
2407
2254
 
2408
2255
  exports.PostHog = PostHog;
2409
2256
  exports["default"] = PostHog;