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