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.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()),
719
755
  };
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
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(),
990
+ };
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);
@@ -853,61 +1178,48 @@ var PostHogCore = /** @class */ (function () {
853
1178
  /***
854
1179
  *** TRACKING
855
1180
  ***/
856
- PostHogCore.prototype.identify = function (distinctId, properties) {
1181
+ PostHogCore.prototype.identify = function (distinctId, properties, options) {
857
1182
  var previousDistinctId = this.getDistinctId();
858
1183
  distinctId = distinctId || previousDistinctId;
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);
1196
+ _super.prototype.identifyStateless.call(this, distinctId, allProperties, options);
876
1197
  return this;
877
1198
  };
878
- PostHogCore.prototype.capture = function (event, properties, forceSendFeatureFlags) {
879
- if (forceSendFeatureFlags === void 0) { forceSendFeatureFlags = false; }
1199
+ PostHogCore.prototype.capture = function (event, properties, options) {
1200
+ var distinctId = this.getDistinctId();
880
1201
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
881
1202
  this.groups(properties.$groups);
882
1203
  }
883
- if (forceSendFeatureFlags) {
884
- this._sendFeatureFlags(event, properties);
885
- }
886
- else {
887
- var payload = this.buildPayload({ event: event, properties: properties });
888
- this.enqueue('capture', payload);
889
- }
1204
+ var allProperties = this.enrichProperties(properties);
1205
+ _super.prototype.captureStateless.call(this, distinctId, event, allProperties, options);
890
1206
  return this;
891
1207
  };
892
1208
  PostHogCore.prototype.alias = function (alias) {
893
1209
  var distinctId = this.getDistinctId();
894
- var payload = this.buildPayload({
895
- event: '$create_alias',
896
- properties: {
897
- distinct_id: distinctId,
898
- alias: alias,
899
- },
900
- });
901
- this.enqueue('alias', payload);
1210
+ var allProperties = this.enrichProperties({});
1211
+ _super.prototype.aliasStateless.call(this, alias, distinctId, allProperties);
902
1212
  return this;
903
1213
  };
904
- PostHogCore.prototype.autocapture = function (eventType, elements, properties) {
1214
+ PostHogCore.prototype.autocapture = function (eventType, elements, properties, options) {
905
1215
  if (properties === void 0) { properties = {}; }
906
- var payload = this.buildPayload({
1216
+ var distinctId = this.getDistinctId();
1217
+ var payload = {
1218
+ distinct_id: distinctId,
907
1219
  event: '$autocapture',
908
- properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
909
- });
910
- this.enqueue('autocapture', payload);
1220
+ properties: __assign(__assign({}, this.enrichProperties(properties)), { $event_type: eventType, $elements: elements }),
1221
+ };
1222
+ this.enqueue('autocapture', payload, options);
911
1223
  return this;
912
1224
  };
913
1225
  /***
@@ -920,26 +1232,24 @@ var PostHogCore = /** @class */ (function () {
920
1232
  $groups: __assign(__assign({}, existingGroups), groups),
921
1233
  });
922
1234
  if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
923
- void this.reloadFeatureFlagsAsync();
1235
+ this.reloadFeatureFlags();
924
1236
  }
925
1237
  return this;
926
1238
  };
927
- PostHogCore.prototype.group = function (groupType, groupKey, groupProperties) {
1239
+ PostHogCore.prototype.group = function (groupType, groupKey, groupProperties, options) {
928
1240
  var _a;
929
1241
  this.groups((_a = {},
930
1242
  _a[groupType] = groupKey,
931
1243
  _a));
932
1244
  if (groupProperties) {
933
- this.groupIdentify(groupType, groupKey, groupProperties);
1245
+ this.groupIdentify(groupType, groupKey, groupProperties, options);
934
1246
  }
935
1247
  return this;
936
1248
  };
937
- PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties) {
938
- var payload = this.buildPayload({
939
- event: '$groupidentify',
940
- properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
941
- });
942
- this.enqueue('capture', payload);
1249
+ PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties, options) {
1250
+ var distinctId = this.getDistinctId();
1251
+ var eventProperties = this.enrichProperties({});
1252
+ _super.prototype.groupIdentifyStateless.call(this, groupType, groupKey, groupProperties, options, distinctId, eventProperties);
943
1253
  return this;
944
1254
  };
945
1255
  /***
@@ -976,30 +1286,19 @@ var PostHogCore = /** @class */ (function () {
976
1286
  PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
977
1287
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
978
1288
  return __awaiter(this, void 0, void 0, function () {
979
- var url, distinctId, groups, personProperties, groupProperties, fetchOptions;
1289
+ var distinctId, groups, personProperties, groupProperties, extraProperties;
980
1290
  var _this = this;
981
1291
  return __generator(this, function (_a) {
982
- url = "".concat(this.host, "/decide/?v=3");
983
1292
  distinctId = this.getDistinctId();
984
1293
  groups = this.props.$groups || {};
985
1294
  personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
986
1295
  groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
987
- fetchOptions = {
988
- method: 'POST',
989
- headers: { 'Content-Type': 'application/json' },
990
- body: JSON.stringify({
991
- token: this.apiKey,
992
- distinct_id: distinctId,
993
- $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
994
- groups: groups,
995
- person_properties: personProperties,
996
- group_properties: groupProperties,
997
- }),
1296
+ extraProperties = {
1297
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
998
1298
  };
999
- this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
1000
- .then(function (r) { return r.json(); })
1299
+ this._decideResponsePromise = _super.prototype.getDecide.call(this, distinctId, groups, personProperties, groupProperties, extraProperties)
1001
1300
  .then(function (res) {
1002
- if (res.featureFlags) {
1301
+ if (res === null || res === void 0 ? void 0 : res.featureFlags) {
1003
1302
  var newFeatureFlags = res.featureFlags;
1004
1303
  var newFeatureFlagPayloads = res.featureFlagPayloads;
1005
1304
  if (res.errorsWhileComputingFlags) {
@@ -1073,14 +1372,6 @@ var PostHogCore = /** @class */ (function () {
1073
1372
  }
1074
1373
  return payloads;
1075
1374
  };
1076
- PostHogCore.prototype._parsePayload = function (response) {
1077
- try {
1078
- return JSON.parse(response);
1079
- }
1080
- catch (_a) {
1081
- return response;
1082
- }
1083
- };
1084
1375
  PostHogCore.prototype.getFeatureFlags = function () {
1085
1376
  var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1086
1377
  var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
@@ -1113,13 +1404,27 @@ var PostHogCore = /** @class */ (function () {
1113
1404
  }
1114
1405
  return !!response;
1115
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
+ };
1116
1420
  PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1421
+ var _a;
1117
1422
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1118
1423
  return __awaiter(this, void 0, void 0, function () {
1119
- return __generator(this, function (_a) {
1120
- switch (_a.label) {
1424
+ return __generator(this, function (_b) {
1425
+ switch (_b.label) {
1121
1426
  case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
1122
- 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];
1123
1428
  }
1124
1429
  });
1125
1430
  });
@@ -1156,142 +1461,10 @@ var PostHogCore = /** @class */ (function () {
1156
1461
  }
1157
1462
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1158
1463
  };
1159
- PostHogCore.prototype._sendFeatureFlags = function (event, properties) {
1160
- var _this = this;
1161
- this.reloadFeatureFlagsAsync(false).finally(function () {
1162
- // Try to enqueue message irrespective of errors during feature flag fetching
1163
- var payload = _this.buildPayload({ event: event, properties: properties });
1164
- _this.enqueue('capture', payload);
1165
- });
1166
- };
1167
- /***
1168
- *** QUEUEING AND FLUSHING
1169
- ***/
1170
- PostHogCore.prototype.enqueue = function (type, _message) {
1171
- var _this = this;
1172
- if (this.optedOut) {
1173
- return;
1174
- }
1175
- var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: _message.timestamp ? _message.timestamp : currentISOTime() });
1176
- if (message.distinctId) {
1177
- message.distinct_id = message.distinctId;
1178
- delete message.distinctId;
1179
- }
1180
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1181
- queue.push({ message: message });
1182
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1183
- this._events.emit(type, message);
1184
- // Flush queued events if we meet the flushAt length
1185
- if (queue.length >= this.flushAt) {
1186
- this.flush();
1187
- }
1188
- if (this.flushInterval && !this._flushTimer) {
1189
- this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1190
- }
1191
- };
1192
- PostHogCore.prototype.flushAsync = function () {
1193
- var _this = this;
1194
- return new Promise(function (resolve, reject) {
1195
- _this.flush(function (err, data) {
1196
- return err ? reject(err) : resolve(data);
1197
- });
1198
- });
1199
- };
1200
- PostHogCore.prototype.flush = function (callback) {
1201
- var _this = this;
1202
- if (this.optedOut) {
1203
- return callback === null || callback === void 0 ? void 0 : callback();
1204
- }
1205
- if (this._flushTimer) {
1206
- clearTimeout(this._flushTimer);
1207
- this._flushTimer = null;
1208
- }
1209
- var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1210
- if (!queue.length) {
1211
- return callback === null || callback === void 0 ? void 0 : callback();
1212
- }
1213
- var items = queue.splice(0, this.flushAt);
1214
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1215
- var messages = items.map(function (item) { return item.message; });
1216
- var data = {
1217
- api_key: this.apiKey,
1218
- batch: messages,
1219
- sent_at: currentISOTime(),
1220
- };
1221
- var done = function (err) {
1222
- callback === null || callback === void 0 ? void 0 : callback(err, messages);
1223
- _this._events.emit('flush', messages);
1224
- };
1225
- // Don't set the user agent if we're not on a browser. The latest spec allows
1226
- // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1227
- // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1228
- // but browsers such as Chrome and Safari have not caught up.
1229
- this.getCustomUserAgent();
1230
- var payload = JSON.stringify(data);
1231
- var url = this.captureMode === 'form'
1232
- ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1233
- : "".concat(this.host, "/batch/");
1234
- var fetchOptions = this.captureMode === 'form'
1235
- ? {
1236
- method: 'POST',
1237
- mode: 'no-cors',
1238
- credentials: 'omit',
1239
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1240
- body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1241
- }
1242
- : {
1243
- method: 'POST',
1244
- headers: { 'Content-Type': 'application/json' },
1245
- body: payload,
1246
- };
1247
- this.fetchWithRetry(url, fetchOptions)
1248
- .then(function () { return done(); })
1249
- .catch(function (err) {
1250
- if (err.response) {
1251
- var error = new Error(err.response.statusText);
1252
- return done(error);
1253
- }
1254
- done(err);
1255
- });
1256
- };
1257
- PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1258
- var _a;
1259
- var _b;
1260
- return __awaiter(this, void 0, void 0, function () {
1261
- var _this = this;
1262
- return __generator(this, function (_c) {
1263
- (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1264
- var ctrl = new AbortController();
1265
- setTimeout(function () { return ctrl.abort(); }, ms);
1266
- return ctrl.signal;
1267
- });
1268
- return [2 /*return*/, retriable(function () {
1269
- return _this.fetch(url, __assign({ signal: AbortSignal.timeout(_this.requestTimeout) }, options));
1270
- }, retryOptions || this._retryOptions)];
1271
- });
1272
- });
1273
- };
1274
- PostHogCore.prototype.shutdownAsync = function () {
1275
- return __awaiter(this, void 0, void 0, function () {
1276
- return __generator(this, function (_a) {
1277
- switch (_a.label) {
1278
- case 0:
1279
- clearTimeout(this._flushTimer);
1280
- return [4 /*yield*/, this.flushAsync()];
1281
- case 1:
1282
- _a.sent();
1283
- return [2 /*return*/];
1284
- }
1285
- });
1286
- });
1287
- };
1288
- PostHogCore.prototype.shutdown = function () {
1289
- void this.shutdownAsync();
1290
- };
1291
1464
  return PostHogCore;
1292
- }());
1465
+ }(PostHogCoreStateless));
1293
1466
 
1294
- var version = "2.1.0";
1467
+ var version = "2.2.1";
1295
1468
 
1296
1469
  function getContext(window) {
1297
1470
  var context = {};