posthog-js-lite 2.5.0 → 2.6.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.d.ts CHANGED
@@ -44,7 +44,10 @@ declare type PostHogFetchOptions = {
44
44
  body?: string;
45
45
  signal?: AbortSignal;
46
46
  };
47
- declare type PosthogCaptureOptions = {
47
+ declare type PostHogCaptureOptions = {
48
+ /** If provided overrides the auto-generated event ID */
49
+ uuid?: string;
50
+ /** If provided overrides the auto-generated timestamp */
48
51
  timestamp?: Date;
49
52
  disableGeoip?: boolean;
50
53
  };
@@ -113,9 +116,9 @@ declare abstract class PostHogCoreStateless {
113
116
  private captureMode;
114
117
  private removeDebugCallback?;
115
118
  private debugMode;
116
- private pendingPromises;
117
119
  private disableGeoip;
118
120
  private _optoutOverride;
121
+ private pendingPromises;
119
122
  protected _events: SimpleEventEmitter;
120
123
  protected _flushTimer?: any;
121
124
  protected _retryOptions: RetriableOptions;
@@ -133,20 +136,21 @@ declare abstract class PostHogCoreStateless {
133
136
  on(event: string, cb: (...args: any[]) => void): () => void;
134
137
  debug(enabled?: boolean): void;
135
138
  private buildPayload;
139
+ protected addPendingPromise(promise: Promise<any>): void;
136
140
  /***
137
141
  *** TRACKING
138
142
  ***/
139
- protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PosthogCaptureOptions): this;
143
+ protected identifyStateless(distinctId: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): this;
140
144
  protected captureStateless(distinctId: string, event: string, properties?: {
141
145
  [key: string]: any;
142
- }, options?: PosthogCaptureOptions): this;
146
+ }, options?: PostHogCaptureOptions): this;
143
147
  protected aliasStateless(alias: string, distinctId: string, properties?: {
144
148
  [key: string]: any;
145
- }, options?: PosthogCaptureOptions): this;
149
+ }, options?: PostHogCaptureOptions): this;
146
150
  /***
147
151
  *** GROUPS
148
152
  ***/
149
- protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PosthogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): this;
153
+ protected groupIdentifyStateless(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions, distinctId?: string, eventProperties?: PostHogEventProperties): this;
150
154
  /***
151
155
  *** FEATURE FLAGS
152
156
  ***/
@@ -163,7 +167,7 @@ declare abstract class PostHogCoreStateless {
163
167
  /***
164
168
  *** QUEUEING AND FLUSHING
165
169
  ***/
166
- protected enqueue(type: string, _message: any, options?: PosthogCaptureOptions): void;
170
+ protected enqueue(type: string, _message: any, options?: PostHogCaptureOptions): void;
167
171
  flushAsync(): Promise<any>;
168
172
  flush(callback?: (err?: any, data?: any) => void): void;
169
173
  private fetchWithRetry;
@@ -201,20 +205,20 @@ declare abstract class PostHogCore extends PostHogCoreStateless {
201
205
  /***
202
206
  *** TRACKING
203
207
  ***/
204
- identify(distinctId?: string, properties?: PostHogEventProperties, options?: PosthogCaptureOptions): this;
208
+ identify(distinctId?: string, properties?: PostHogEventProperties, options?: PostHogCaptureOptions): this;
205
209
  capture(event: string, properties?: {
206
210
  [key: string]: any;
207
- }, options?: PosthogCaptureOptions): this;
211
+ }, options?: PostHogCaptureOptions): this;
208
212
  alias(alias: string): this;
209
- autocapture(eventType: string, elements: PostHogAutocaptureElement[], properties?: PostHogEventProperties, options?: PosthogCaptureOptions): this;
213
+ autocapture(eventType: string, elements: PostHogAutocaptureElement[], properties?: PostHogEventProperties, options?: PostHogCaptureOptions): this;
210
214
  /***
211
215
  *** GROUPS
212
216
  ***/
213
217
  groups(groups: {
214
218
  [type: string]: string | number;
215
219
  }): this;
216
- group(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PosthogCaptureOptions): this;
217
- groupIdentify(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PosthogCaptureOptions): this;
220
+ group(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions): this;
221
+ groupIdentify(groupType: string, groupKey: string | number, groupProperties?: PostHogEventProperties, options?: PostHogCaptureOptions): this;
218
222
  /***
219
223
  * PROPERTIES
220
224
  ***/
package/lib/index.esm.js CHANGED
@@ -207,26 +207,6 @@ function retriable(fn, props) {
207
207
  });
208
208
  });
209
209
  }
210
- // https://stackoverflow.com/a/8809472
211
- function generateUUID(globalThis) {
212
- // Public Domain/MIT
213
- var d = new Date().getTime(); //Timestamp
214
- var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
215
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
216
- var r = Math.random() * 16; //random number between 0 and 16
217
- if (d > 0) {
218
- //Use timestamp until depleted
219
- r = (d + r) % 16 | 0;
220
- d = Math.floor(d / 16);
221
- }
222
- else {
223
- //Use microseconds since page-load if supported
224
- r = (d2 + r) % 16 | 0;
225
- d2 = Math.floor(d2 / 16);
226
- }
227
- return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
228
- });
229
- }
230
210
  function currentTimestamp() {
231
211
  return new Date().getTime();
232
212
  }
@@ -701,6 +681,401 @@ var SimpleEventEmitter = /** @class */ (function () {
701
681
  return SimpleEventEmitter;
702
682
  }());
703
683
 
684
+ /**
685
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
686
+ *
687
+ * @license Apache-2.0
688
+ * @copyright 2021-2023 LiosK
689
+ * @packageDocumentation
690
+ */
691
+ var DIGITS = "0123456789abcdef";
692
+ /** Represents a UUID as a 16-byte byte array. */
693
+ var UUID = /** @class */ (function () {
694
+ /** @param bytes - The 16-byte byte array representation. */
695
+ function UUID(bytes) {
696
+ this.bytes = bytes;
697
+ }
698
+ /**
699
+ * Creates an object from the internal representation, a 16-byte byte array
700
+ * containing the binary UUID representation in the big-endian byte order.
701
+ *
702
+ * This method does NOT shallow-copy the argument, and thus the created object
703
+ * holds the reference to the underlying buffer.
704
+ *
705
+ * @throws TypeError if the length of the argument is not 16.
706
+ */
707
+ UUID.ofInner = function (bytes) {
708
+ if (bytes.length !== 16) {
709
+ throw new TypeError("not 128-bit length");
710
+ }
711
+ else {
712
+ return new UUID(bytes);
713
+ }
714
+ };
715
+ /**
716
+ * Builds a byte array from UUIDv7 field values.
717
+ *
718
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
719
+ * @param randA - A 12-bit `rand_a` field value.
720
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
721
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
722
+ * @throws RangeError if any field value is out of the specified range.
723
+ */
724
+ UUID.fromFieldsV7 = function (unixTsMs, randA, randBHi, randBLo) {
725
+ if (!Number.isInteger(unixTsMs) ||
726
+ !Number.isInteger(randA) ||
727
+ !Number.isInteger(randBHi) ||
728
+ !Number.isInteger(randBLo) ||
729
+ unixTsMs < 0 ||
730
+ randA < 0 ||
731
+ randBHi < 0 ||
732
+ randBLo < 0 ||
733
+ unixTsMs > 281474976710655 ||
734
+ randA > 0xfff ||
735
+ randBHi > 1073741823 ||
736
+ randBLo > 4294967295) {
737
+ throw new RangeError("invalid field value");
738
+ }
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);
745
+ bytes[5] = unixTsMs;
746
+ bytes[6] = 0x70 | (randA >>> 8);
747
+ bytes[7] = randA;
748
+ bytes[8] = 0x80 | (randBHi >>> 24);
749
+ bytes[9] = randBHi >>> 16;
750
+ bytes[10] = randBHi >>> 8;
751
+ bytes[11] = randBHi;
752
+ bytes[12] = randBLo >>> 24;
753
+ bytes[13] = randBLo >>> 16;
754
+ bytes[14] = randBLo >>> 8;
755
+ bytes[15] = randBLo;
756
+ return new UUID(bytes);
757
+ };
758
+ /**
759
+ * Builds a byte array from a string representation.
760
+ *
761
+ * This method accepts the following formats:
762
+ *
763
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
764
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
765
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
766
+ * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
767
+ *
768
+ * Leading and trailing whitespaces represents an error.
769
+ *
770
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
771
+ */
772
+ UUID.parse = function (uuid) {
773
+ var _a, _b, _c, _d;
774
+ var hex = undefined;
775
+ switch (uuid.length) {
776
+ case 32:
777
+ hex = (_a = /^[0-9a-f]{32}$/i.exec(uuid)) === null || _a === void 0 ? void 0 : _a[0];
778
+ break;
779
+ case 36:
780
+ 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("");
783
+ break;
784
+ case 38:
785
+ 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("");
788
+ break;
789
+ case 45:
790
+ 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("");
793
+ break;
794
+ }
795
+ 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);
799
+ inner[i + 0] = n >>> 24;
800
+ inner[i + 1] = n >>> 16;
801
+ inner[i + 2] = n >>> 8;
802
+ inner[i + 3] = n;
803
+ }
804
+ return new UUID(inner);
805
+ }
806
+ else {
807
+ throw new SyntaxError("could not parse UUID string");
808
+ }
809
+ };
810
+ /**
811
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
812
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
813
+ */
814
+ UUID.prototype.toString = function () {
815
+ var text = "";
816
+ for (var i = 0; i < this.bytes.length; i++) {
817
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
818
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
819
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
820
+ text += "-";
821
+ }
822
+ }
823
+ return text;
824
+ };
825
+ /**
826
+ * @returns The 32-digit hexadecimal representation without hyphens
827
+ * (`0189dcd553117d408db09496a2eef37b`).
828
+ */
829
+ UUID.prototype.toHex = function () {
830
+ var text = "";
831
+ for (var i = 0; i < this.bytes.length; i++) {
832
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
833
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
834
+ }
835
+ return text;
836
+ };
837
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
838
+ UUID.prototype.toJSON = function () {
839
+ return this.toString();
840
+ };
841
+ /**
842
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
843
+ * "MAX".
844
+ *
845
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
846
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
847
+ * subsumed under the variants `0b0` and `0b111`, respectively.
848
+ */
849
+ UUID.prototype.getVariant = function () {
850
+ var n = this.bytes[8] >>> 4;
851
+ if (n < 0) {
852
+ throw new Error("unreachable");
853
+ }
854
+ else if (n <= 7) {
855
+ return this.bytes.every(function (e) { return e === 0; }) ? "NIL" : "VAR_0";
856
+ }
857
+ else if (n <= 11) {
858
+ return "VAR_10";
859
+ }
860
+ else if (n <= 13) {
861
+ return "VAR_110";
862
+ }
863
+ else if (n <= 15) {
864
+ return this.bytes.every(function (e) { return e === 0xff; }) ? "MAX" : "VAR_RESERVED";
865
+ }
866
+ else {
867
+ throw new Error("unreachable");
868
+ }
869
+ };
870
+ /**
871
+ * Returns the version field value of the UUID or `undefined` if the UUID does
872
+ * not have the variant field value of `0b10`.
873
+ */
874
+ UUID.prototype.getVersion = function () {
875
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
876
+ };
877
+ /** Creates an object from `this`. */
878
+ UUID.prototype.clone = function () {
879
+ return new UUID(this.bytes.slice(0));
880
+ };
881
+ /** Returns true if `this` is equivalent to `other`. */
882
+ UUID.prototype.equals = function (other) {
883
+ return this.compareTo(other) === 0;
884
+ };
885
+ /**
886
+ * Returns a negative integer, zero, or positive integer if `this` is less
887
+ * than, equal to, or greater than `other`, respectively.
888
+ */
889
+ UUID.prototype.compareTo = function (other) {
890
+ for (var i = 0; i < 16; i++) {
891
+ var diff = this.bytes[i] - other.bytes[i];
892
+ if (diff !== 0) {
893
+ return Math.sign(diff);
894
+ }
895
+ }
896
+ return 0;
897
+ };
898
+ return UUID;
899
+ }());
900
+ /**
901
+ * Encapsulates the monotonic counter state.
902
+ *
903
+ * This class provides APIs to utilize a separate counter state from that of the
904
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
905
+ * the default {@link generate} method, this class has {@link generateOrAbort}
906
+ * that is useful to absolutely guarantee the monotonically increasing order of
907
+ * generated UUIDs. See their respective documentation for details.
908
+ */
909
+ var V7Generator = /** @class */ (function () {
910
+ /**
911
+ * Creates a generator object with the default random number generator, or
912
+ * with the specified one if passed as an argument. The specified random
913
+ * number generator should be cryptographically strong and securely seeded.
914
+ */
915
+ function V7Generator(randomNumberGenerator) {
916
+ this.timestamp = 0;
917
+ this.counter = 0;
918
+ this.random = randomNumberGenerator !== null && randomNumberGenerator !== void 0 ? randomNumberGenerator : getDefaultRandom();
919
+ }
920
+ /**
921
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
922
+ * generator upon significant timestamp rollback.
923
+ *
924
+ * This method returns a monotonically increasing UUID by reusing the previous
925
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
926
+ * preceding UUID's. However, when such a clock rollback is considered
927
+ * significant (i.e., by more than ten seconds), this method resets the
928
+ * generator and returns a new UUID based on the given timestamp, breaking the
929
+ * increasing order of UUIDs.
930
+ *
931
+ * See {@link generateOrAbort} for the other mode of generation and
932
+ * {@link generateOrResetCore} for the low-level primitive.
933
+ */
934
+ V7Generator.prototype.generate = function () {
935
+ return this.generateOrResetCore(Date.now(), 10000);
936
+ };
937
+ /**
938
+ * Generates a new UUIDv7 object from the current timestamp, or returns
939
+ * `undefined` upon significant timestamp rollback.
940
+ *
941
+ * This method returns a monotonically increasing UUID by reusing the previous
942
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
943
+ * preceding UUID's. However, when such a clock rollback is considered
944
+ * significant (i.e., by more than ten seconds), this method aborts and
945
+ * returns `undefined` immediately.
946
+ *
947
+ * See {@link generate} for the other mode of generation and
948
+ * {@link generateOrAbortCore} for the low-level primitive.
949
+ */
950
+ V7Generator.prototype.generateOrAbort = function () {
951
+ return this.generateOrAbortCore(Date.now(), 10000);
952
+ };
953
+ /**
954
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
955
+ * generator upon significant timestamp rollback.
956
+ *
957
+ * This method is equivalent to {@link generate} except that it takes a custom
958
+ * timestamp and clock rollback allowance.
959
+ *
960
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
961
+ * considered significant. A suggested value is `10_000` (milliseconds).
962
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
963
+ */
964
+ V7Generator.prototype.generateOrResetCore = function (unixTsMs, rollbackAllowance) {
965
+ var value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
966
+ if (value === undefined) {
967
+ // reset state and resume
968
+ this.timestamp = 0;
969
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
970
+ }
971
+ return value;
972
+ };
973
+ /**
974
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
975
+ * `undefined` upon significant timestamp rollback.
976
+ *
977
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
978
+ * custom timestamp and clock rollback allowance.
979
+ *
980
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
981
+ * considered significant. A suggested value is `10_000` (milliseconds).
982
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
983
+ */
984
+ V7Generator.prototype.generateOrAbortCore = function (unixTsMs, rollbackAllowance) {
985
+ var MAX_COUNTER = 4398046511103;
986
+ if (!Number.isInteger(unixTsMs) ||
987
+ unixTsMs < 1 ||
988
+ unixTsMs > 281474976710655) {
989
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
990
+ }
991
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
992
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
993
+ }
994
+ if (unixTsMs > this.timestamp) {
995
+ this.timestamp = unixTsMs;
996
+ this.resetCounter();
997
+ }
998
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
999
+ // go on with previous timestamp if new one is not much smaller
1000
+ this.counter++;
1001
+ if (this.counter > MAX_COUNTER) {
1002
+ // increment timestamp at counter overflow
1003
+ this.timestamp++;
1004
+ this.resetCounter();
1005
+ }
1006
+ }
1007
+ else {
1008
+ // abort if clock went backwards to unbearable extent
1009
+ return undefined;
1010
+ }
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
+ };
1013
+ /** Initializes the counter at a 42-bit random integer. */
1014
+ V7Generator.prototype.resetCounter = function () {
1015
+ this.counter =
1016
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
1017
+ };
1018
+ /**
1019
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
1020
+ *
1021
+ * @internal
1022
+ */
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);
1025
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
1026
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
1027
+ 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
+ }
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++];
1065
+ };
1066
+ return BufferedCryptoRandom;
1067
+ }());
1068
+ var defaultGenerator;
1069
+ /**
1070
+ * Generates a UUIDv7 string.
1071
+ *
1072
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
1073
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
1074
+ */
1075
+ var uuidv7 = function () { return uuidv7obj().toString(); };
1076
+ /** Generates a UUIDv7 object. */
1077
+ var uuidv7obj = function () { return (defaultGenerator || (defaultGenerator = new V7Generator())).generate(); };
1078
+
704
1079
  var PostHogFetchHttpError = /** @class */ (function (_super) {
705
1080
  __extends(PostHogFetchHttpError, _super);
706
1081
  function PostHogFetchHttpError(response) {
@@ -731,8 +1106,8 @@ var PostHogCoreStateless = /** @class */ (function () {
731
1106
  function PostHogCoreStateless(apiKey, options) {
732
1107
  var _a, _b, _c, _d, _e;
733
1108
  this.debugMode = false;
734
- this.pendingPromises = {};
735
1109
  this.disableGeoip = true;
1110
+ this.pendingPromises = {};
736
1111
  // internal
737
1112
  this._events = new SimpleEventEmitter();
738
1113
  assert(apiKey, "You must pass your PostHog project's api key.");
@@ -790,6 +1165,14 @@ var PostHogCoreStateless = /** @class */ (function () {
790
1165
  properties: __assign(__assign({}, (payload.properties || {})), this.getCommonEventProperties()),
791
1166
  };
792
1167
  };
1168
+ PostHogCoreStateless.prototype.addPendingPromise = function (promise) {
1169
+ var _this = this;
1170
+ var promiseUUID = uuidv7();
1171
+ this.pendingPromises[promiseUUID] = promise;
1172
+ promise.finally(function () {
1173
+ delete _this.pendingPromises[promiseUUID];
1174
+ });
1175
+ };
793
1176
  /***
794
1177
  *** TRACKING
795
1178
  ***/
@@ -840,6 +1223,7 @@ var PostHogCoreStateless = /** @class */ (function () {
840
1223
  if (extraPayload === void 0) { extraPayload = {}; }
841
1224
  return __awaiter(this, void 0, void 0, function () {
842
1225
  var url, fetchOptions;
1226
+ var _this = this;
843
1227
  return __generator(this, function (_a) {
844
1228
  url = "".concat(this.host, "/decide/?v=3");
845
1229
  fetchOptions = {
@@ -850,7 +1234,7 @@ var PostHogCoreStateless = /** @class */ (function () {
850
1234
  return [2 /*return*/, this.fetchWithRetry(url, fetchOptions)
851
1235
  .then(function (response) { return response.json(); })
852
1236
  .catch(function (error) {
853
- console.error('Error fetching feature flags', error);
1237
+ _this._events.emit('error', error);
854
1238
  return undefined;
855
1239
  })];
856
1240
  });
@@ -984,10 +1368,10 @@ var PostHogCoreStateless = /** @class */ (function () {
984
1368
  var _this = this;
985
1369
  var _a;
986
1370
  if (this.optedOut) {
987
- this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.enable()");
1371
+ this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
988
1372
  return;
989
1373
  }
990
- 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() });
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() });
991
1375
  var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
992
1376
  if (addGeoipDisableProperty) {
993
1377
  if (!message.properties) {
@@ -1037,14 +1421,11 @@ var PostHogCoreStateless = /** @class */ (function () {
1037
1421
  batch: messages,
1038
1422
  sent_at: currentISOTime(),
1039
1423
  };
1040
- var promiseUUID = generateUUID();
1041
1424
  var done = function (err) {
1042
1425
  if (err) {
1043
1426
  _this._events.emit('error', err);
1044
1427
  }
1045
1428
  callback === null || callback === void 0 ? void 0 : callback(err, messages);
1046
- // remove promise from pendingPromises
1047
- delete _this.pendingPromises[promiseUUID];
1048
1429
  _this._events.emit('flush', messages);
1049
1430
  };
1050
1431
  // Don't set the user agent if we're not on a browser. The latest spec allows
@@ -1070,12 +1451,11 @@ var PostHogCoreStateless = /** @class */ (function () {
1070
1451
  body: payload,
1071
1452
  };
1072
1453
  var requestPromise = this.fetchWithRetry(url, fetchOptions);
1073
- this.pendingPromises[promiseUUID] = requestPromise;
1074
- requestPromise
1454
+ this.addPendingPromise(requestPromise
1075
1455
  .then(function () { return done(); })
1076
1456
  .catch(function (err) {
1077
1457
  done(err);
1078
- });
1458
+ }));
1079
1459
  };
1080
1460
  PostHogCoreStateless.prototype.fetchWithRetry = function (url, options, retryOptions) {
1081
1461
  var _a;
@@ -1129,7 +1509,7 @@ var PostHogCoreStateless = /** @class */ (function () {
1129
1509
  clearTimeout(this._flushTimer);
1130
1510
  _a.label = 1;
1131
1511
  case 1:
1132
- _a.trys.push([1, 4, , 5]);
1512
+ _a.trys.push([1, 5, , 6]);
1133
1513
  return [4 /*yield*/, this.flushAsync()];
1134
1514
  case 2:
1135
1515
  _a.sent();
@@ -1137,18 +1517,31 @@ var PostHogCoreStateless = /** @class */ (function () {
1137
1517
  return x.catch(function () {
1138
1518
  // ignore errors as we are shutting down and can't deal with them anyways.
1139
1519
  });
1140
- }))];
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
+ ];
1141
1525
  case 3:
1142
1526
  _a.sent();
1143
- return [3 /*break*/, 5];
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()];
1144
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:
1145
1538
  e_2 = _a.sent();
1146
1539
  if (!isPostHogFetchError(e_2)) {
1147
1540
  throw e_2;
1148
1541
  }
1149
1542
  console.error('Error while shutting down PostHog', e_2);
1150
- return [3 /*break*/, 5];
1151
- case 5: return [2 /*return*/];
1543
+ return [3 /*break*/, 6];
1544
+ case 6: return [2 /*return*/];
1152
1545
  }
1153
1546
  });
1154
1547
  });
@@ -1243,7 +1636,7 @@ var PostHogCore = /** @class */ (function (_super) {
1243
1636
  var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1244
1637
  var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1245
1638
  if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
1246
- sessionId = generateUUID(globalThis);
1639
+ sessionId = uuidv7();
1247
1640
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
1248
1641
  }
1249
1642
  this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
@@ -1255,7 +1648,7 @@ var PostHogCore = /** @class */ (function (_super) {
1255
1648
  PostHogCore.prototype.getAnonymousId = function () {
1256
1649
  var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1257
1650
  if (!anonId) {
1258
- anonId = generateUUID(globalThis);
1651
+ anonId = uuidv7();
1259
1652
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
1260
1653
  }
1261
1654
  return anonId;
@@ -1578,7 +1971,7 @@ var PostHogCore = /** @class */ (function (_super) {
1578
1971
  return PostHogCore;
1579
1972
  }(PostHogCoreStateless));
1580
1973
 
1581
- var version = "2.5.0";
1974
+ var version = "2.6.1";
1582
1975
 
1583
1976
  function getContext(window) {
1584
1977
  var context = {};