posthog-js-lite 2.6.1 → 3.0.0-beta.1

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