posthog-js-lite 2.6.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.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) {
@@ -792,7 +1167,7 @@ var PostHogCoreStateless = /** @class */ (function () {
792
1167
  };
793
1168
  PostHogCoreStateless.prototype.addPendingPromise = function (promise) {
794
1169
  var _this = this;
795
- var promiseUUID = generateUUID();
1170
+ var promiseUUID = uuidv7();
796
1171
  this.pendingPromises[promiseUUID] = promise;
797
1172
  promise.finally(function () {
798
1173
  delete _this.pendingPromises[promiseUUID];
@@ -996,7 +1371,7 @@ var PostHogCoreStateless = /** @class */ (function () {
996
1371
  this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
997
1372
  return;
998
1373
  }
999
- 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 : generateUUID(globalThis) });
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() });
1000
1375
  var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
1001
1376
  if (addGeoipDisableProperty) {
1002
1377
  if (!message.properties) {
@@ -1261,7 +1636,7 @@ var PostHogCore = /** @class */ (function (_super) {
1261
1636
  var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
1262
1637
  var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
1263
1638
  if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
1264
- sessionId = generateUUID(globalThis);
1639
+ sessionId = uuidv7();
1265
1640
  this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
1266
1641
  }
1267
1642
  this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
@@ -1273,7 +1648,7 @@ var PostHogCore = /** @class */ (function (_super) {
1273
1648
  PostHogCore.prototype.getAnonymousId = function () {
1274
1649
  var anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
1275
1650
  if (!anonId) {
1276
- anonId = generateUUID(globalThis);
1651
+ anonId = uuidv7();
1277
1652
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
1278
1653
  }
1279
1654
  return anonId;
@@ -1596,7 +1971,7 @@ var PostHogCore = /** @class */ (function (_super) {
1596
1971
  return PostHogCore;
1597
1972
  }(PostHogCoreStateless));
1598
1973
 
1599
- var version = "2.6.0";
1974
+ var version = "2.6.1";
1600
1975
 
1601
1976
  function getContext(window) {
1602
1977
  var context = {};