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