posthog-js-lite 2.2.0 → 2.2.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
@@ -697,11 +697,9 @@ var SimpleEventEmitter = /** @class */ (function () {
697
697
  return SimpleEventEmitter;
698
698
  }());
699
699
 
700
- var PostHogCore = /** @class */ (function () {
701
- function PostHogCore(apiKey, options) {
702
- var _this = this;
703
- var _a, _b, _c, _d, _e, _f;
704
- this.flagCallReported = {};
700
+ var PostHogCoreStateless = /** @class */ (function () {
701
+ function PostHogCoreStateless(apiKey, options) {
702
+ var _a, _b, _c, _d;
705
703
  // internal
706
704
  this._events = new SimpleEventEmitter();
707
705
  assert(apiKey, "You must pass your PostHog project's api key.");
@@ -710,33 +708,375 @@ var PostHogCore = /** @class */ (function () {
710
708
  this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
711
709
  this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
712
710
  this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
713
- this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
714
711
  // If enable is explicitly set to false we override the optout
715
712
  this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
716
713
  this._retryOptions = {
717
- retryCount: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _c !== void 0 ? _c : 3,
718
- retryDelay: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _d !== void 0 ? _d : 3000,
714
+ retryCount: (_b = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _b !== void 0 ? _b : 3,
715
+ retryDelay: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _c !== void 0 ? _c : 3000,
716
+ };
717
+ this.requestTimeout = (_d = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _d !== void 0 ? _d : 10000; // 10 seconds
718
+ }
719
+ PostHogCoreStateless.prototype.getCommonEventProperties = function () {
720
+ return {
721
+ $lib: this.getLibraryId(),
722
+ $lib_version: this.getLibraryVersion(),
723
+ };
724
+ };
725
+ Object.defineProperty(PostHogCoreStateless.prototype, "optedOut", {
726
+ get: function () {
727
+ var _a, _b;
728
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
729
+ },
730
+ enumerable: false,
731
+ configurable: true
732
+ });
733
+ PostHogCoreStateless.prototype.optIn = function () {
734
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
735
+ };
736
+ PostHogCoreStateless.prototype.optOut = function () {
737
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
738
+ };
739
+ PostHogCoreStateless.prototype.on = function (event, cb) {
740
+ return this._events.on(event, cb);
741
+ };
742
+ PostHogCoreStateless.prototype.debug = function (enabled) {
743
+ var _a;
744
+ if (enabled === void 0) { enabled = true; }
745
+ (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
746
+ if (enabled) {
747
+ this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
748
+ }
749
+ };
750
+ PostHogCoreStateless.prototype.buildPayload = function (payload) {
751
+ return {
752
+ distinct_id: payload.distinct_id,
753
+ event: payload.event,
754
+ properties: __assign(__assign({}, (payload.properties || {})), this.getCommonEventProperties()),
755
+ };
756
+ };
757
+ /***
758
+ *** TRACKING
759
+ ***/
760
+ PostHogCoreStateless.prototype.identifyStateless = function (distinctId, properties, options) {
761
+ // The properties passed to identifyStateless are event properties.
762
+ // To add person properties, pass in all person properties to the `$set` key.
763
+ var payload = __assign({}, this.buildPayload({
764
+ distinct_id: distinctId,
765
+ event: '$identify',
766
+ properties: properties,
767
+ }));
768
+ this.enqueue('identify', payload, options);
769
+ return this;
770
+ };
771
+ PostHogCoreStateless.prototype.captureStateless = function (distinctId, event, properties, options) {
772
+ var payload = this.buildPayload({ distinct_id: distinctId, event: event, properties: properties });
773
+ this.enqueue('capture', payload, options);
774
+ return this;
775
+ };
776
+ PostHogCoreStateless.prototype.aliasStateless = function (alias, distinctId, properties) {
777
+ var payload = this.buildPayload({
778
+ event: '$create_alias',
779
+ distinct_id: distinctId,
780
+ properties: __assign(__assign({}, (properties || {})), { distinct_id: distinctId, alias: alias }),
781
+ });
782
+ this.enqueue('alias', payload);
783
+ return this;
784
+ };
785
+ /***
786
+ *** GROUPS
787
+ ***/
788
+ PostHogCoreStateless.prototype.groupIdentifyStateless = function (groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
789
+ var payload = this.buildPayload({
790
+ distinct_id: distinctId || "$".concat(groupType, "_").concat(groupKey),
791
+ event: '$groupidentify',
792
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, (eventProperties || {})),
793
+ });
794
+ this.enqueue('capture', payload, options);
795
+ return this;
796
+ };
797
+ /***
798
+ *** FEATURE FLAGS
799
+ ***/
800
+ PostHogCoreStateless.prototype.getDecide = function (distinctId, groups, personProperties, groupProperties, extraPayload) {
801
+ if (groups === void 0) { groups = {}; }
802
+ if (personProperties === void 0) { personProperties = {}; }
803
+ if (groupProperties === void 0) { groupProperties = {}; }
804
+ if (extraPayload === void 0) { extraPayload = {}; }
805
+ return __awaiter(this, void 0, void 0, function () {
806
+ var url, fetchOptions;
807
+ return __generator(this, function (_a) {
808
+ url = "".concat(this.host, "/decide/?v=3");
809
+ fetchOptions = {
810
+ method: 'POST',
811
+ headers: { 'Content-Type': 'application/json' },
812
+ body: JSON.stringify(__assign({ token: this.apiKey, distinct_id: distinctId, groups: groups, person_properties: personProperties, group_properties: groupProperties }, extraPayload)),
813
+ };
814
+ return [2 /*return*/, this.fetchWithRetry(url, fetchOptions)
815
+ .then(function (response) { return response.json(); })
816
+ .catch(function (error) {
817
+ console.error('Error fetching feature flags', error);
818
+ return undefined;
819
+ })];
820
+ });
821
+ });
822
+ };
823
+ PostHogCoreStateless.prototype.getFeatureFlagStateless = function (key, distinctId, groups, personProperties, groupProperties) {
824
+ if (groups === void 0) { groups = {}; }
825
+ if (personProperties === void 0) { personProperties = {}; }
826
+ if (groupProperties === void 0) { groupProperties = {}; }
827
+ return __awaiter(this, void 0, void 0, function () {
828
+ var featureFlags, response;
829
+ return __generator(this, function (_a) {
830
+ switch (_a.label) {
831
+ case 0: return [4 /*yield*/, this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties)];
832
+ case 1:
833
+ featureFlags = _a.sent();
834
+ if (!featureFlags) {
835
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
836
+ return [2 /*return*/, undefined];
837
+ }
838
+ response = featureFlags[key];
839
+ // `/decide` v3 returns all flags
840
+ if (response === undefined) {
841
+ // For cases where the flag is unknown, return false
842
+ response = false;
843
+ }
844
+ // If we have flags we either return the value (true or string) or false
845
+ return [2 /*return*/, response];
846
+ }
847
+ });
848
+ });
849
+ };
850
+ PostHogCoreStateless.prototype.getFeatureFlagPayloadStateless = function (key, distinctId, groups, personProperties, groupProperties) {
851
+ if (groups === void 0) { groups = {}; }
852
+ if (personProperties === void 0) { personProperties = {}; }
853
+ if (groupProperties === void 0) { groupProperties = {}; }
854
+ return __awaiter(this, void 0, void 0, function () {
855
+ var payloads, response;
856
+ return __generator(this, function (_a) {
857
+ switch (_a.label) {
858
+ case 0: return [4 /*yield*/, this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties)];
859
+ case 1:
860
+ payloads = _a.sent();
861
+ if (!payloads) {
862
+ return [2 /*return*/, undefined];
863
+ }
864
+ response = payloads[key];
865
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
866
+ if (response === undefined) {
867
+ return [2 /*return*/, null];
868
+ }
869
+ return [2 /*return*/, this._parsePayload(response)];
870
+ }
871
+ });
872
+ });
873
+ };
874
+ PostHogCoreStateless.prototype.getFeatureFlagPayloadsStateless = function (distinctId, groups, personProperties, groupProperties) {
875
+ if (groups === void 0) { groups = {}; }
876
+ if (personProperties === void 0) { personProperties = {}; }
877
+ if (groupProperties === void 0) { groupProperties = {}; }
878
+ return __awaiter(this, void 0, void 0, function () {
879
+ var payloads;
880
+ var _this = this;
881
+ return __generator(this, function (_a) {
882
+ switch (_a.label) {
883
+ case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties)];
884
+ case 1:
885
+ payloads = (_a.sent()).payloads;
886
+ if (payloads) {
887
+ return [2 /*return*/, Object.fromEntries(Object.entries(payloads).map(function (_a) {
888
+ var k = _a[0], v = _a[1];
889
+ return [k, _this._parsePayload(v)];
890
+ }))];
891
+ }
892
+ return [2 /*return*/, payloads];
893
+ }
894
+ });
895
+ });
896
+ };
897
+ PostHogCoreStateless.prototype._parsePayload = function (response) {
898
+ try {
899
+ return JSON.parse(response);
900
+ }
901
+ catch (_a) {
902
+ return response;
903
+ }
904
+ };
905
+ PostHogCoreStateless.prototype.getFeatureFlagsStateless = function (distinctId, groups, personProperties, groupProperties) {
906
+ if (groups === void 0) { groups = {}; }
907
+ if (personProperties === void 0) { personProperties = {}; }
908
+ if (groupProperties === void 0) { groupProperties = {}; }
909
+ return __awaiter(this, void 0, void 0, function () {
910
+ return __generator(this, function (_a) {
911
+ switch (_a.label) {
912
+ case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties)];
913
+ case 1: return [2 /*return*/, (_a.sent()).flags];
914
+ }
915
+ });
916
+ });
917
+ };
918
+ PostHogCoreStateless.prototype.getFeatureFlagsAndPayloadsStateless = function (distinctId, groups, personProperties, groupProperties) {
919
+ if (groups === void 0) { groups = {}; }
920
+ if (personProperties === void 0) { personProperties = {}; }
921
+ if (groupProperties === void 0) { groupProperties = {}; }
922
+ return __awaiter(this, void 0, void 0, function () {
923
+ var decideResponse, flags, payloads;
924
+ return __generator(this, function (_a) {
925
+ switch (_a.label) {
926
+ case 0: return [4 /*yield*/, this.getDecide(distinctId, groups, personProperties, groupProperties)];
927
+ case 1:
928
+ decideResponse = _a.sent();
929
+ flags = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlags;
930
+ payloads = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlagPayloads;
931
+ return [2 /*return*/, {
932
+ flags: flags,
933
+ payloads: payloads,
934
+ }];
935
+ }
936
+ });
937
+ });
938
+ };
939
+ /***
940
+ *** QUEUEING AND FLUSHING
941
+ ***/
942
+ PostHogCoreStateless.prototype.enqueue = function (type, _message, options) {
943
+ var _this = this;
944
+ if (this.optedOut) {
945
+ this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.enable()");
946
+ return;
947
+ }
948
+ 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() });
949
+ if (message.distinctId) {
950
+ message.distinct_id = message.distinctId;
951
+ delete message.distinctId;
952
+ }
953
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
954
+ queue.push({ message: message });
955
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
956
+ this._events.emit(type, message);
957
+ // Flush queued events if we meet the flushAt length
958
+ if (queue.length >= this.flushAt) {
959
+ this.flush();
960
+ }
961
+ if (this.flushInterval && !this._flushTimer) {
962
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
963
+ }
964
+ };
965
+ PostHogCoreStateless.prototype.flushAsync = function () {
966
+ var _this = this;
967
+ return new Promise(function (resolve, reject) {
968
+ _this.flush(function (err, data) {
969
+ return err ? reject(err) : resolve(data);
970
+ });
971
+ });
972
+ };
973
+ PostHogCoreStateless.prototype.flush = function (callback) {
974
+ var _this = this;
975
+ if (this._flushTimer) {
976
+ clearTimeout(this._flushTimer);
977
+ this._flushTimer = null;
978
+ }
979
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
980
+ if (!queue.length) {
981
+ return callback === null || callback === void 0 ? void 0 : callback();
982
+ }
983
+ var items = queue.splice(0, this.flushAt);
984
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
985
+ var messages = items.map(function (item) { return item.message; });
986
+ var data = {
987
+ api_key: this.apiKey,
988
+ batch: messages,
989
+ sent_at: currentISOTime(),
719
990
  };
720
- this.requestTimeout = (_e = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _e !== void 0 ? _e : 10000; // 10 seconds
721
- this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
991
+ var done = function (err) {
992
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
993
+ _this._events.emit('flush', messages);
994
+ };
995
+ // Don't set the user agent if we're not on a browser. The latest spec allows
996
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
997
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
998
+ // but browsers such as Chrome and Safari have not caught up.
999
+ this.getCustomUserAgent();
1000
+ var payload = JSON.stringify(data);
1001
+ var url = this.captureMode === 'form'
1002
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1003
+ : "".concat(this.host, "/batch/");
1004
+ var fetchOptions = this.captureMode === 'form'
1005
+ ? {
1006
+ method: 'POST',
1007
+ mode: 'no-cors',
1008
+ credentials: 'omit',
1009
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1010
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1011
+ }
1012
+ : {
1013
+ method: 'POST',
1014
+ headers: { 'Content-Type': 'application/json' },
1015
+ body: payload,
1016
+ };
1017
+ this.fetchWithRetry(url, fetchOptions)
1018
+ .then(function () { return done(); })
1019
+ .catch(function (err) {
1020
+ if (err.response) {
1021
+ var error = new Error(err.response.statusText);
1022
+ return done(error);
1023
+ }
1024
+ done(err);
1025
+ });
1026
+ };
1027
+ PostHogCoreStateless.prototype.fetchWithRetry = function (url, options, retryOptions) {
1028
+ var _a;
1029
+ var _b;
1030
+ return __awaiter(this, void 0, void 0, function () {
1031
+ var _this = this;
1032
+ return __generator(this, function (_c) {
1033
+ (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1034
+ var ctrl = new AbortController();
1035
+ setTimeout(function () { return ctrl.abort(); }, ms);
1036
+ return ctrl.signal;
1037
+ });
1038
+ return [2 /*return*/, retriable(function () {
1039
+ return _this.fetch(url, __assign({ signal: AbortSignal.timeout(_this.requestTimeout) }, options));
1040
+ }, retryOptions || this._retryOptions)];
1041
+ });
1042
+ });
1043
+ };
1044
+ PostHogCoreStateless.prototype.shutdownAsync = function () {
1045
+ return __awaiter(this, void 0, void 0, function () {
1046
+ return __generator(this, function (_a) {
1047
+ switch (_a.label) {
1048
+ case 0:
1049
+ clearTimeout(this._flushTimer);
1050
+ return [4 /*yield*/, this.flushAsync()];
1051
+ case 1:
1052
+ _a.sent();
1053
+ return [2 /*return*/];
1054
+ }
1055
+ });
1056
+ });
1057
+ };
1058
+ PostHogCoreStateless.prototype.shutdown = function () {
1059
+ void this.shutdownAsync();
1060
+ };
1061
+ return PostHogCoreStateless;
1062
+ }());
1063
+ var PostHogCore = /** @class */ (function (_super) {
1064
+ __extends(PostHogCore, _super);
1065
+ function PostHogCore(apiKey, options) {
1066
+ var _this = this;
1067
+ var _a, _b;
1068
+ _this = _super.call(this, apiKey, options) || this;
1069
+ _this.flagCallReported = {};
1070
+ _this.sendFeatureFlagEvent = (_a = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _a !== void 0 ? _a : true;
1071
+ _this._sessionExpirationTimeSeconds = (_b = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _b !== void 0 ? _b : 1800; // 30 minutes
722
1072
  // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
723
1073
  if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
724
1074
  safeSetTimeout(function () {
725
- void _this.reloadFeatureFlagsAsync();
1075
+ _this.reloadFeatureFlags();
726
1076
  }, 1);
727
1077
  }
1078
+ return _this;
728
1079
  }
729
- PostHogCore.prototype.getCommonEventProperties = function () {
730
- var featureFlags = this.getFeatureFlags();
731
- var featureVariantProperties = {};
732
- if (featureFlags) {
733
- for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
734
- var _b = _a[_i], feature = _b[0], variant = _b[1];
735
- featureVariantProperties["$feature/".concat(feature)] = variant;
736
- }
737
- }
738
- return __assign({ $lib: this.getLibraryId(), $lib_version: this.getLibraryVersion(), $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties);
739
- };
740
1080
  PostHogCore.prototype.setupBootstrap = function (options) {
741
1081
  var _a, _b, _c, _d;
742
1082
  if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
@@ -775,20 +1115,6 @@ var PostHogCore = /** @class */ (function () {
775
1115
  PostHogCore.prototype.clearProps = function () {
776
1116
  this.props = undefined;
777
1117
  };
778
- Object.defineProperty(PostHogCore.prototype, "optedOut", {
779
- get: function () {
780
- var _a, _b;
781
- return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
782
- },
783
- enumerable: false,
784
- configurable: true
785
- });
786
- PostHogCore.prototype.optIn = function () {
787
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
788
- };
789
- PostHogCore.prototype.optOut = function () {
790
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
791
- };
792
1118
  PostHogCore.prototype.on = function (event, cb) {
793
1119
  return this._events.on(event, cb);
794
1120
  };
@@ -803,20 +1129,19 @@ var PostHogCore = /** @class */ (function () {
803
1129
  }
804
1130
  }
805
1131
  };
806
- PostHogCore.prototype.debug = function (enabled) {
807
- var _a;
808
- if (enabled === void 0) { enabled = true; }
809
- (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
810
- if (enabled) {
811
- this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
1132
+ PostHogCore.prototype.getCommonEventProperties = function () {
1133
+ var featureFlags = this.getFeatureFlags();
1134
+ var featureVariantProperties = {};
1135
+ if (featureFlags) {
1136
+ for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
1137
+ var _b = _a[_i], feature = _b[0], variant = _b[1];
1138
+ featureVariantProperties["$feature/".concat(feature)] = variant;
1139
+ }
812
1140
  }
1141
+ return __assign(__assign({ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties), _super.prototype.getCommonEventProperties.call(this));
813
1142
  };
814
- PostHogCore.prototype.buildPayload = function (payload) {
815
- return {
816
- distinct_id: payload.distinct_id || this.getDistinctId(),
817
- event: payload.event,
818
- properties: __assign(__assign(__assign(__assign({}, this.props), (payload.properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() }),
819
- };
1143
+ PostHogCore.prototype.enrichProperties = function (properties) {
1144
+ return __assign(__assign(__assign(__assign({}, this.props), (properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() });
820
1145
  };
821
1146
  PostHogCore.prototype.getSessionId = function () {
822
1147
  var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
@@ -859,48 +1184,41 @@ var PostHogCore = /** @class */ (function () {
859
1184
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
860
1185
  this.groups(properties.$groups);
861
1186
  }
862
- var payload = __assign(__assign({}, this.buildPayload({
863
- distinct_id: distinctId,
864
- event: '$identify',
865
- properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getAnonymousId() }),
866
- })), { $set: properties });
1187
+ var allProperties = this.enrichProperties(__assign(__assign({}, properties), { $anon_distinct_id: this.getAnonymousId(), $set: properties }));
867
1188
  if (distinctId !== previousDistinctId) {
868
1189
  // We keep the AnonymousId to be used by decide calls and identify to link the previousId
869
1190
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
870
1191
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
871
1192
  if (this.getFeatureFlags()) {
872
- void this.reloadFeatureFlagsAsync();
1193
+ this.reloadFeatureFlags();
873
1194
  }
874
1195
  }
875
- this.enqueue('identify', payload, options);
1196
+ _super.prototype.identifyStateless.call(this, distinctId, allProperties, options);
876
1197
  return this;
877
1198
  };
878
1199
  PostHogCore.prototype.capture = function (event, properties, options) {
1200
+ var distinctId = this.getDistinctId();
879
1201
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
880
1202
  this.groups(properties.$groups);
881
1203
  }
882
- var payload = this.buildPayload({ event: event, properties: properties });
883
- this.enqueue('capture', payload, options);
1204
+ var allProperties = this.enrichProperties(properties);
1205
+ _super.prototype.captureStateless.call(this, distinctId, event, allProperties, options);
884
1206
  return this;
885
1207
  };
886
1208
  PostHogCore.prototype.alias = function (alias) {
887
1209
  var distinctId = this.getDistinctId();
888
- var payload = this.buildPayload({
889
- event: '$create_alias',
890
- properties: {
891
- distinct_id: distinctId,
892
- alias: alias,
893
- },
894
- });
895
- this.enqueue('alias', payload);
1210
+ var allProperties = this.enrichProperties({});
1211
+ _super.prototype.aliasStateless.call(this, alias, distinctId, allProperties);
896
1212
  return this;
897
1213
  };
898
1214
  PostHogCore.prototype.autocapture = function (eventType, elements, properties, options) {
899
1215
  if (properties === void 0) { properties = {}; }
900
- var payload = this.buildPayload({
1216
+ var distinctId = this.getDistinctId();
1217
+ var payload = {
1218
+ distinct_id: distinctId,
901
1219
  event: '$autocapture',
902
- properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
903
- });
1220
+ properties: __assign(__assign({}, this.enrichProperties(properties)), { $event_type: eventType, $elements: elements }),
1221
+ };
904
1222
  this.enqueue('autocapture', payload, options);
905
1223
  return this;
906
1224
  };
@@ -914,7 +1232,7 @@ var PostHogCore = /** @class */ (function () {
914
1232
  $groups: __assign(__assign({}, existingGroups), groups),
915
1233
  });
916
1234
  if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
917
- void this.reloadFeatureFlagsAsync();
1235
+ this.reloadFeatureFlags();
918
1236
  }
919
1237
  return this;
920
1238
  };
@@ -929,11 +1247,9 @@ var PostHogCore = /** @class */ (function () {
929
1247
  return this;
930
1248
  };
931
1249
  PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties, options) {
932
- var payload = this.buildPayload({
933
- event: '$groupidentify',
934
- properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
935
- });
936
- this.enqueue('capture', payload, options);
1250
+ var distinctId = this.getDistinctId();
1251
+ var eventProperties = this.enrichProperties({});
1252
+ _super.prototype.groupIdentifyStateless.call(this, groupType, groupKey, groupProperties, options, distinctId, eventProperties);
937
1253
  return this;
938
1254
  };
939
1255
  /***
@@ -970,30 +1286,19 @@ var PostHogCore = /** @class */ (function () {
970
1286
  PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
971
1287
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
972
1288
  return __awaiter(this, void 0, void 0, function () {
973
- var url, distinctId, groups, personProperties, groupProperties, fetchOptions;
1289
+ var distinctId, groups, personProperties, groupProperties, extraProperties;
974
1290
  var _this = this;
975
1291
  return __generator(this, function (_a) {
976
- url = "".concat(this.host, "/decide/?v=3");
977
1292
  distinctId = this.getDistinctId();
978
1293
  groups = this.props.$groups || {};
979
1294
  personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
980
1295
  groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
981
- fetchOptions = {
982
- method: 'POST',
983
- headers: { 'Content-Type': 'application/json' },
984
- body: JSON.stringify({
985
- token: this.apiKey,
986
- distinct_id: distinctId,
987
- $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
988
- groups: groups,
989
- person_properties: personProperties,
990
- group_properties: groupProperties,
991
- }),
1296
+ extraProperties = {
1297
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
992
1298
  };
993
- this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
994
- .then(function (r) { return r.json(); })
1299
+ this._decideResponsePromise = _super.prototype.getDecide.call(this, distinctId, groups, personProperties, groupProperties, extraProperties)
995
1300
  .then(function (res) {
996
- if (res.featureFlags) {
1301
+ if (res === null || res === void 0 ? void 0 : res.featureFlags) {
997
1302
  var newFeatureFlags = res.featureFlags;
998
1303
  var newFeatureFlagPayloads = res.featureFlagPayloads;
999
1304
  if (res.errorsWhileComputingFlags) {
@@ -1067,14 +1372,6 @@ var PostHogCore = /** @class */ (function () {
1067
1372
  }
1068
1373
  return payloads;
1069
1374
  };
1070
- PostHogCore.prototype._parsePayload = function (response) {
1071
- try {
1072
- return JSON.parse(response);
1073
- }
1074
- catch (_a) {
1075
- return response;
1076
- }
1077
- };
1078
1375
  PostHogCore.prototype.getFeatureFlags = function () {
1079
1376
  var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1080
1377
  var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
@@ -1107,13 +1404,27 @@ var PostHogCore = /** @class */ (function () {
1107
1404
  }
1108
1405
  return !!response;
1109
1406
  };
1407
+ // Used when we want to trigger the reload but we don't care about the result
1408
+ PostHogCore.prototype.reloadFeatureFlags = function (cb) {
1409
+ this.decideAsync()
1410
+ .then(function (res) {
1411
+ cb === null || cb === void 0 ? void 0 : cb(undefined, res === null || res === void 0 ? void 0 : res.featureFlags);
1412
+ })
1413
+ .catch(function (e) {
1414
+ cb === null || cb === void 0 ? void 0 : cb(e, undefined);
1415
+ if (!cb) {
1416
+ console.log('[PostHog] Error reloading feature flags', e);
1417
+ }
1418
+ });
1419
+ };
1110
1420
  PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1421
+ var _a;
1111
1422
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1112
1423
  return __awaiter(this, void 0, void 0, function () {
1113
- return __generator(this, function (_a) {
1114
- switch (_a.label) {
1424
+ return __generator(this, function (_b) {
1425
+ switch (_b.label) {
1115
1426
  case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
1116
- case 1: return [2 /*return*/, (_a.sent()).featureFlags];
1427
+ case 1: return [2 /*return*/, (_a = (_b.sent())) === null || _a === void 0 ? void 0 : _a.featureFlags];
1117
1428
  }
1118
1429
  });
1119
1430
  });
@@ -1150,134 +1461,10 @@ var PostHogCore = /** @class */ (function () {
1150
1461
  }
1151
1462
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1152
1463
  };
1153
- /***
1154
- *** QUEUEING AND FLUSHING
1155
- ***/
1156
- PostHogCore.prototype.enqueue = function (type, _message, options) {
1157
- var _this = this;
1158
- if (this.optedOut) {
1159
- return;
1160
- }
1161
- 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() });
1162
- if (message.distinctId) {
1163
- message.distinct_id = message.distinctId;
1164
- delete message.distinctId;
1165
- }
1166
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1167
- queue.push({ message: message });
1168
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1169
- this._events.emit(type, message);
1170
- // Flush queued events if we meet the flushAt length
1171
- if (queue.length >= this.flushAt) {
1172
- this.flush();
1173
- }
1174
- if (this.flushInterval && !this._flushTimer) {
1175
- this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1176
- }
1177
- };
1178
- PostHogCore.prototype.flushAsync = function () {
1179
- var _this = this;
1180
- return new Promise(function (resolve, reject) {
1181
- _this.flush(function (err, data) {
1182
- return err ? reject(err) : resolve(data);
1183
- });
1184
- });
1185
- };
1186
- PostHogCore.prototype.flush = function (callback) {
1187
- var _this = this;
1188
- if (this.optedOut) {
1189
- return callback === null || callback === void 0 ? void 0 : callback();
1190
- }
1191
- if (this._flushTimer) {
1192
- clearTimeout(this._flushTimer);
1193
- this._flushTimer = null;
1194
- }
1195
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1196
- if (!queue.length) {
1197
- return callback === null || callback === void 0 ? void 0 : callback();
1198
- }
1199
- var items = queue.splice(0, this.flushAt);
1200
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1201
- var messages = items.map(function (item) { return item.message; });
1202
- var data = {
1203
- api_key: this.apiKey,
1204
- batch: messages,
1205
- sent_at: currentISOTime(),
1206
- };
1207
- var done = function (err) {
1208
- callback === null || callback === void 0 ? void 0 : callback(err, messages);
1209
- _this._events.emit('flush', messages);
1210
- };
1211
- // Don't set the user agent if we're not on a browser. The latest spec allows
1212
- // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1213
- // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1214
- // but browsers such as Chrome and Safari have not caught up.
1215
- this.getCustomUserAgent();
1216
- var payload = JSON.stringify(data);
1217
- var url = this.captureMode === 'form'
1218
- ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1219
- : "".concat(this.host, "/batch/");
1220
- var fetchOptions = this.captureMode === 'form'
1221
- ? {
1222
- method: 'POST',
1223
- mode: 'no-cors',
1224
- credentials: 'omit',
1225
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1226
- body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1227
- }
1228
- : {
1229
- method: 'POST',
1230
- headers: { 'Content-Type': 'application/json' },
1231
- body: payload,
1232
- };
1233
- this.fetchWithRetry(url, fetchOptions)
1234
- .then(function () { return done(); })
1235
- .catch(function (err) {
1236
- if (err.response) {
1237
- var error = new Error(err.response.statusText);
1238
- return done(error);
1239
- }
1240
- done(err);
1241
- });
1242
- };
1243
- PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1244
- var _a;
1245
- var _b;
1246
- return __awaiter(this, void 0, void 0, function () {
1247
- var _this = this;
1248
- return __generator(this, function (_c) {
1249
- (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1250
- var ctrl = new AbortController();
1251
- setTimeout(function () { return ctrl.abort(); }, ms);
1252
- return ctrl.signal;
1253
- });
1254
- return [2 /*return*/, retriable(function () {
1255
- return _this.fetch(url, __assign({ signal: AbortSignal.timeout(_this.requestTimeout) }, options));
1256
- }, retryOptions || this._retryOptions)];
1257
- });
1258
- });
1259
- };
1260
- PostHogCore.prototype.shutdownAsync = function () {
1261
- return __awaiter(this, void 0, void 0, function () {
1262
- return __generator(this, function (_a) {
1263
- switch (_a.label) {
1264
- case 0:
1265
- clearTimeout(this._flushTimer);
1266
- return [4 /*yield*/, this.flushAsync()];
1267
- case 1:
1268
- _a.sent();
1269
- return [2 /*return*/];
1270
- }
1271
- });
1272
- });
1273
- };
1274
- PostHogCore.prototype.shutdown = function () {
1275
- void this.shutdownAsync();
1276
- };
1277
1464
  return PostHogCore;
1278
- }());
1465
+ }(PostHogCoreStateless));
1279
1466
 
1280
- var version = "2.2.0";
1467
+ var version = "2.2.1";
1281
1468
 
1282
1469
  function getContext(window) {
1283
1470
  var context = {};