posthog-js-lite 2.2.0 → 2.3.0

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
@@ -176,29 +176,31 @@ function retriable(fn, props) {
176
176
  i = 0;
177
177
  _d.label = 1;
178
178
  case 1:
179
- if (!(i < retryCount + 1)) return [3 /*break*/, 8];
180
- _d.label = 2;
179
+ if (!(i < retryCount + 1)) return [3 /*break*/, 7];
180
+ if (!(i > 0)) return [3 /*break*/, 3];
181
+ // don't wait when it's the last try
182
+ return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
181
183
  case 2:
182
- _d.trys.push([2, 4, , 5]);
183
- return [4 /*yield*/, fn()];
184
+ // don't wait when it's the last try
185
+ _d.sent();
186
+ _d.label = 3;
184
187
  case 3:
188
+ _d.trys.push([3, 5, , 6]);
189
+ return [4 /*yield*/, fn()];
190
+ case 4:
185
191
  res = _d.sent();
186
192
  return [2 /*return*/, res];
187
- case 4:
193
+ case 5:
188
194
  e_1 = _d.sent();
189
195
  lastError = e_1;
190
196
  if (!retryCheck(e_1)) {
191
197
  throw e_1;
192
198
  }
193
- return [3 /*break*/, 5];
194
- case 5: return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
199
+ return [3 /*break*/, 6];
195
200
  case 6:
196
- _d.sent();
197
- _d.label = 7;
198
- case 7:
199
201
  i++;
200
202
  return [3 /*break*/, 1];
201
- case 8: throw lastError;
203
+ case 7: throw lastError;
202
204
  }
203
205
  });
204
206
  });
@@ -697,11 +699,35 @@ var SimpleEventEmitter = /** @class */ (function () {
697
699
  return SimpleEventEmitter;
698
700
  }());
699
701
 
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 = {};
702
+ var PostHogFetchHttpError = /** @class */ (function (_super) {
703
+ __extends(PostHogFetchHttpError, _super);
704
+ function PostHogFetchHttpError(response) {
705
+ var _this = _super.call(this, 'HTTP error while fetching PostHog: ' + response.status) || this;
706
+ _this.response = response;
707
+ _this.name = 'PostHogFetchHttpError';
708
+ return _this;
709
+ }
710
+ return PostHogFetchHttpError;
711
+ }(Error));
712
+ var PostHogFetchNetworkError = /** @class */ (function (_super) {
713
+ __extends(PostHogFetchNetworkError, _super);
714
+ function PostHogFetchNetworkError(error) {
715
+ var _this = _super.call(this, 'Network error while fetching PostHog', error instanceof Error ? { cause: error } : {}) || this;
716
+ _this.error = error;
717
+ _this.name = 'PostHogFetchNetworkError';
718
+ return _this;
719
+ }
720
+ return PostHogFetchNetworkError;
721
+ }(Error));
722
+ function isPostHogFetchError(err) {
723
+ return typeof err === 'object' && (err.name === 'PostHogFetchHttpError' || err.name === 'PostHogFetchNetworkError');
724
+ }
725
+ var PostHogCoreStateless = /** @class */ (function () {
726
+ function PostHogCoreStateless(apiKey, options) {
727
+ var _a, _b, _c, _d, _e;
728
+ this.debugMode = false;
729
+ this.pendingPromises = {};
730
+ this.disableGeoip = true;
705
731
  // internal
706
732
  this._events = new SimpleEventEmitter();
707
733
  assert(apiKey, "You must pass your PostHog project's api key.");
@@ -710,33 +736,438 @@ var PostHogCore = /** @class */ (function () {
710
736
  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
737
  this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
712
738
  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
739
  // If enable is explicitly set to false we override the optout
715
740
  this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
716
741
  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,
742
+ retryCount: (_b = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _b !== void 0 ? _b : 3,
743
+ retryDelay: (_c = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _c !== void 0 ? _c : 3000,
744
+ retryCheck: isPostHogFetchError,
745
+ };
746
+ this.requestTimeout = (_d = options === null || options === void 0 ? void 0 : options.requestTimeout) !== null && _d !== void 0 ? _d : 10000; // 10 seconds
747
+ this.disableGeoip = (_e = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _e !== void 0 ? _e : true;
748
+ }
749
+ PostHogCoreStateless.prototype.getCommonEventProperties = function () {
750
+ return {
751
+ $lib: this.getLibraryId(),
752
+ $lib_version: this.getLibraryVersion(),
753
+ };
754
+ };
755
+ Object.defineProperty(PostHogCoreStateless.prototype, "optedOut", {
756
+ get: function () {
757
+ var _a, _b;
758
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
759
+ },
760
+ enumerable: false,
761
+ configurable: true
762
+ });
763
+ PostHogCoreStateless.prototype.optIn = function () {
764
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
765
+ };
766
+ PostHogCoreStateless.prototype.optOut = function () {
767
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
768
+ };
769
+ PostHogCoreStateless.prototype.on = function (event, cb) {
770
+ return this._events.on(event, cb);
771
+ };
772
+ PostHogCoreStateless.prototype.debug = function (enabled) {
773
+ var _a;
774
+ if (enabled === void 0) { enabled = true; }
775
+ (_a = this.removeDebugCallback) === null || _a === void 0 ? void 0 : _a.call(this);
776
+ this.debugMode = enabled;
777
+ if (enabled) {
778
+ this.removeDebugCallback = this.on('*', function (event, payload) { return console.log('PostHog Debug', event, payload); });
779
+ }
780
+ };
781
+ PostHogCoreStateless.prototype.buildPayload = function (payload) {
782
+ return {
783
+ distinct_id: payload.distinct_id,
784
+ event: payload.event,
785
+ properties: __assign(__assign({}, (payload.properties || {})), this.getCommonEventProperties()),
786
+ };
787
+ };
788
+ /***
789
+ *** TRACKING
790
+ ***/
791
+ PostHogCoreStateless.prototype.identifyStateless = function (distinctId, properties, options) {
792
+ // The properties passed to identifyStateless are event properties.
793
+ // To add person properties, pass in all person properties to the `$set` key.
794
+ var payload = __assign({}, this.buildPayload({
795
+ distinct_id: distinctId,
796
+ event: '$identify',
797
+ properties: properties,
798
+ }));
799
+ this.enqueue('identify', payload, options);
800
+ return this;
801
+ };
802
+ PostHogCoreStateless.prototype.captureStateless = function (distinctId, event, properties, options) {
803
+ var payload = this.buildPayload({ distinct_id: distinctId, event: event, properties: properties });
804
+ this.enqueue('capture', payload, options);
805
+ return this;
806
+ };
807
+ PostHogCoreStateless.prototype.aliasStateless = function (alias, distinctId, properties, options) {
808
+ var payload = this.buildPayload({
809
+ event: '$create_alias',
810
+ distinct_id: distinctId,
811
+ properties: __assign(__assign({}, (properties || {})), { distinct_id: distinctId, alias: alias }),
812
+ });
813
+ this.enqueue('alias', payload, options);
814
+ return this;
815
+ };
816
+ /***
817
+ *** GROUPS
818
+ ***/
819
+ PostHogCoreStateless.prototype.groupIdentifyStateless = function (groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
820
+ var payload = this.buildPayload({
821
+ distinct_id: distinctId || "$".concat(groupType, "_").concat(groupKey),
822
+ event: '$groupidentify',
823
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, (eventProperties || {})),
824
+ });
825
+ this.enqueue('capture', payload, options);
826
+ return this;
827
+ };
828
+ /***
829
+ *** FEATURE FLAGS
830
+ ***/
831
+ PostHogCoreStateless.prototype.getDecide = function (distinctId, groups, personProperties, groupProperties, extraPayload) {
832
+ if (groups === void 0) { groups = {}; }
833
+ if (personProperties === void 0) { personProperties = {}; }
834
+ if (groupProperties === void 0) { groupProperties = {}; }
835
+ if (extraPayload === void 0) { extraPayload = {}; }
836
+ return __awaiter(this, void 0, void 0, function () {
837
+ var url, fetchOptions;
838
+ return __generator(this, function (_a) {
839
+ url = "".concat(this.host, "/decide/?v=3");
840
+ fetchOptions = {
841
+ method: 'POST',
842
+ headers: { 'Content-Type': 'application/json' },
843
+ body: JSON.stringify(__assign({ token: this.apiKey, distinct_id: distinctId, groups: groups, person_properties: personProperties, group_properties: groupProperties }, extraPayload)),
844
+ };
845
+ return [2 /*return*/, this.fetchWithRetry(url, fetchOptions)
846
+ .then(function (response) { return response.json(); })
847
+ .catch(function (error) {
848
+ console.error('Error fetching feature flags', error);
849
+ return undefined;
850
+ })];
851
+ });
852
+ });
853
+ };
854
+ PostHogCoreStateless.prototype.getFeatureFlagStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
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 featureFlags, response;
860
+ return __generator(this, function (_a) {
861
+ switch (_a.label) {
862
+ case 0: return [4 /*yield*/, this.getFeatureFlagsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
863
+ case 1:
864
+ featureFlags = _a.sent();
865
+ if (!featureFlags) {
866
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
867
+ return [2 /*return*/, undefined];
868
+ }
869
+ response = featureFlags[key];
870
+ // `/decide` v3 returns all flags
871
+ if (response === undefined) {
872
+ // For cases where the flag is unknown, return false
873
+ response = false;
874
+ }
875
+ // If we have flags we either return the value (true or string) or false
876
+ return [2 /*return*/, response];
877
+ }
878
+ });
879
+ });
880
+ };
881
+ PostHogCoreStateless.prototype.getFeatureFlagPayloadStateless = function (key, distinctId, groups, personProperties, groupProperties, disableGeoip) {
882
+ if (groups === void 0) { groups = {}; }
883
+ if (personProperties === void 0) { personProperties = {}; }
884
+ if (groupProperties === void 0) { groupProperties = {}; }
885
+ return __awaiter(this, void 0, void 0, function () {
886
+ var payloads, response;
887
+ return __generator(this, function (_a) {
888
+ switch (_a.label) {
889
+ case 0: return [4 /*yield*/, this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
890
+ case 1:
891
+ payloads = _a.sent();
892
+ if (!payloads) {
893
+ return [2 /*return*/, undefined];
894
+ }
895
+ response = payloads[key];
896
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
897
+ if (response === undefined) {
898
+ return [2 /*return*/, null];
899
+ }
900
+ return [2 /*return*/, this._parsePayload(response)];
901
+ }
902
+ });
903
+ });
904
+ };
905
+ PostHogCoreStateless.prototype.getFeatureFlagPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
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
+ var payloads;
911
+ var _this = this;
912
+ return __generator(this, function (_a) {
913
+ switch (_a.label) {
914
+ case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
915
+ case 1:
916
+ payloads = (_a.sent()).payloads;
917
+ if (payloads) {
918
+ return [2 /*return*/, Object.fromEntries(Object.entries(payloads).map(function (_a) {
919
+ var k = _a[0], v = _a[1];
920
+ return [k, _this._parsePayload(v)];
921
+ }))];
922
+ }
923
+ return [2 /*return*/, payloads];
924
+ }
925
+ });
926
+ });
927
+ };
928
+ PostHogCoreStateless.prototype._parsePayload = function (response) {
929
+ try {
930
+ return JSON.parse(response);
931
+ }
932
+ catch (_a) {
933
+ return response;
934
+ }
935
+ };
936
+ PostHogCoreStateless.prototype.getFeatureFlagsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
937
+ if (groups === void 0) { groups = {}; }
938
+ if (personProperties === void 0) { personProperties = {}; }
939
+ if (groupProperties === void 0) { groupProperties = {}; }
940
+ return __awaiter(this, void 0, void 0, function () {
941
+ return __generator(this, function (_a) {
942
+ switch (_a.label) {
943
+ case 0: return [4 /*yield*/, this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)];
944
+ case 1: return [2 /*return*/, (_a.sent()).flags];
945
+ }
946
+ });
947
+ });
948
+ };
949
+ PostHogCoreStateless.prototype.getFeatureFlagsAndPayloadsStateless = function (distinctId, groups, personProperties, groupProperties, disableGeoip) {
950
+ if (groups === void 0) { groups = {}; }
951
+ if (personProperties === void 0) { personProperties = {}; }
952
+ if (groupProperties === void 0) { groupProperties = {}; }
953
+ return __awaiter(this, void 0, void 0, function () {
954
+ var extraPayload, decideResponse, flags, payloads;
955
+ return __generator(this, function (_a) {
956
+ switch (_a.label) {
957
+ case 0:
958
+ extraPayload = {};
959
+ if (disableGeoip !== null && disableGeoip !== void 0 ? disableGeoip : this.disableGeoip) {
960
+ extraPayload['geoip_disable'] = true;
961
+ }
962
+ return [4 /*yield*/, this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload)];
963
+ case 1:
964
+ decideResponse = _a.sent();
965
+ flags = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlags;
966
+ payloads = decideResponse === null || decideResponse === void 0 ? void 0 : decideResponse.featureFlagPayloads;
967
+ return [2 /*return*/, {
968
+ flags: flags,
969
+ payloads: payloads,
970
+ }];
971
+ }
972
+ });
973
+ });
974
+ };
975
+ /***
976
+ *** QUEUEING AND FLUSHING
977
+ ***/
978
+ PostHogCoreStateless.prototype.enqueue = function (type, _message, options) {
979
+ var _this = this;
980
+ var _a;
981
+ if (this.optedOut) {
982
+ this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.enable()");
983
+ return;
984
+ }
985
+ 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() });
986
+ var addGeoipDisableProperty = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : this.disableGeoip;
987
+ if (addGeoipDisableProperty) {
988
+ if (!message.properties) {
989
+ message.properties = {};
990
+ }
991
+ message['properties']['$geoip_disable'] = true;
992
+ }
993
+ if (message.distinctId) {
994
+ message.distinct_id = message.distinctId;
995
+ delete message.distinctId;
996
+ }
997
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
998
+ queue.push({ message: message });
999
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1000
+ this._events.emit(type, message);
1001
+ // Flush queued events if we meet the flushAt length
1002
+ if (queue.length >= this.flushAt) {
1003
+ this.flush();
1004
+ }
1005
+ if (this.flushInterval && !this._flushTimer) {
1006
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1007
+ }
1008
+ };
1009
+ PostHogCoreStateless.prototype.flushAsync = function () {
1010
+ var _this = this;
1011
+ return new Promise(function (resolve, reject) {
1012
+ _this.flush(function (err, data) {
1013
+ return err ? reject(err) : resolve(data);
1014
+ });
1015
+ });
1016
+ };
1017
+ PostHogCoreStateless.prototype.flush = function (callback) {
1018
+ var _this = this;
1019
+ if (this._flushTimer) {
1020
+ clearTimeout(this._flushTimer);
1021
+ this._flushTimer = null;
1022
+ }
1023
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1024
+ if (!queue.length) {
1025
+ return callback === null || callback === void 0 ? void 0 : callback();
1026
+ }
1027
+ var items = queue.splice(0, this.flushAt);
1028
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1029
+ var messages = items.map(function (item) { return item.message; });
1030
+ var data = {
1031
+ api_key: this.apiKey,
1032
+ batch: messages,
1033
+ sent_at: currentISOTime(),
719
1034
  };
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
1035
+ var promiseUUID = generateUUID();
1036
+ var done = function (err) {
1037
+ if (err) {
1038
+ _this._events.emit('error', err);
1039
+ }
1040
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
1041
+ // remove promise from pendingPromises
1042
+ delete _this.pendingPromises[promiseUUID];
1043
+ _this._events.emit('flush', messages);
1044
+ };
1045
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1046
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1047
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1048
+ // but browsers such as Chrome and Safari have not caught up.
1049
+ this.getCustomUserAgent();
1050
+ var payload = JSON.stringify(data);
1051
+ var url = this.captureMode === 'form'
1052
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1053
+ : "".concat(this.host, "/batch/");
1054
+ var fetchOptions = this.captureMode === 'form'
1055
+ ? {
1056
+ method: 'POST',
1057
+ mode: 'no-cors',
1058
+ credentials: 'omit',
1059
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1060
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1061
+ }
1062
+ : {
1063
+ method: 'POST',
1064
+ headers: { 'Content-Type': 'application/json' },
1065
+ body: payload,
1066
+ };
1067
+ var requestPromise = this.fetchWithRetry(url, fetchOptions);
1068
+ this.pendingPromises[promiseUUID] = requestPromise;
1069
+ requestPromise
1070
+ .then(function () { return done(); })
1071
+ .catch(function (err) {
1072
+ done(err);
1073
+ });
1074
+ };
1075
+ PostHogCoreStateless.prototype.fetchWithRetry = function (url, options, retryOptions) {
1076
+ var _a;
1077
+ var _b;
1078
+ return __awaiter(this, void 0, void 0, function () {
1079
+ var _this = this;
1080
+ return __generator(this, function (_c) {
1081
+ switch (_c.label) {
1082
+ case 0:
1083
+ (_a = (_b = AbortSignal).timeout) !== null && _a !== void 0 ? _a : (_b.timeout = function timeout(ms) {
1084
+ var ctrl = new AbortController();
1085
+ setTimeout(function () { return ctrl.abort(); }, ms);
1086
+ return ctrl.signal;
1087
+ });
1088
+ return [4 /*yield*/, retriable(function () { return __awaiter(_this, void 0, void 0, function () {
1089
+ var res, e_1;
1090
+ return __generator(this, function (_a) {
1091
+ switch (_a.label) {
1092
+ case 0:
1093
+ res = null;
1094
+ _a.label = 1;
1095
+ case 1:
1096
+ _a.trys.push([1, 3, , 4]);
1097
+ return [4 /*yield*/, this.fetch(url, __assign({ signal: AbortSignal.timeout(this.requestTimeout) }, options))];
1098
+ case 2:
1099
+ res = _a.sent();
1100
+ return [3 /*break*/, 4];
1101
+ case 3:
1102
+ e_1 = _a.sent();
1103
+ // fetch will only throw on network errors or on timeouts
1104
+ throw new PostHogFetchNetworkError(e_1);
1105
+ case 4:
1106
+ if (res.status < 200 || res.status >= 400) {
1107
+ throw new PostHogFetchHttpError(res);
1108
+ }
1109
+ return [2 /*return*/, res];
1110
+ }
1111
+ });
1112
+ }); }, __assign(__assign({}, this._retryOptions), retryOptions))];
1113
+ case 1: return [2 /*return*/, _c.sent()];
1114
+ }
1115
+ });
1116
+ });
1117
+ };
1118
+ PostHogCoreStateless.prototype.shutdownAsync = function () {
1119
+ return __awaiter(this, void 0, void 0, function () {
1120
+ var e_2;
1121
+ return __generator(this, function (_a) {
1122
+ switch (_a.label) {
1123
+ case 0:
1124
+ clearTimeout(this._flushTimer);
1125
+ _a.label = 1;
1126
+ case 1:
1127
+ _a.trys.push([1, 4, , 5]);
1128
+ return [4 /*yield*/, this.flushAsync()];
1129
+ case 2:
1130
+ _a.sent();
1131
+ return [4 /*yield*/, Promise.allSettled(Object.values(this.pendingPromises))];
1132
+ case 3:
1133
+ _a.sent();
1134
+ return [3 /*break*/, 5];
1135
+ case 4:
1136
+ e_2 = _a.sent();
1137
+ if (!isPostHogFetchError(e_2)) {
1138
+ throw e_2;
1139
+ }
1140
+ console.error('Error while shutting down PostHog', e_2);
1141
+ return [3 /*break*/, 5];
1142
+ case 5: return [2 /*return*/];
1143
+ }
1144
+ });
1145
+ });
1146
+ };
1147
+ PostHogCoreStateless.prototype.shutdown = function () {
1148
+ void this.shutdownAsync();
1149
+ };
1150
+ return PostHogCoreStateless;
1151
+ }());
1152
+ var PostHogCore = /** @class */ (function (_super) {
1153
+ __extends(PostHogCore, _super);
1154
+ function PostHogCore(apiKey, options) {
1155
+ var _this = this;
1156
+ var _a, _b, _c;
1157
+ // Default for stateful mode is to not disable geoip. Only override if explicitly set
1158
+ var disableGeoipOption = (_a = options === null || options === void 0 ? void 0 : options.disableGeoip) !== null && _a !== void 0 ? _a : false;
1159
+ _this = _super.call(this, apiKey, __assign(__assign({}, options), { disableGeoip: disableGeoipOption })) || this;
1160
+ _this.flagCallReported = {};
1161
+ _this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
1162
+ _this._sessionExpirationTimeSeconds = (_c = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _c !== void 0 ? _c : 1800; // 30 minutes
722
1163
  // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
723
1164
  if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
724
1165
  safeSetTimeout(function () {
725
- void _this.reloadFeatureFlagsAsync();
1166
+ _this.reloadFeatureFlags();
726
1167
  }, 1);
727
1168
  }
1169
+ return _this;
728
1170
  }
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
1171
  PostHogCore.prototype.setupBootstrap = function (options) {
741
1172
  var _a, _b, _c, _d;
742
1173
  if ((_a = options === null || options === void 0 ? void 0 : options.bootstrap) === null || _a === void 0 ? void 0 : _a.distinctId) {
@@ -775,20 +1206,6 @@ var PostHogCore = /** @class */ (function () {
775
1206
  PostHogCore.prototype.clearProps = function () {
776
1207
  this.props = undefined;
777
1208
  };
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
1209
  PostHogCore.prototype.on = function (event, cb) {
793
1210
  return this._events.on(event, cb);
794
1211
  };
@@ -803,20 +1220,19 @@ var PostHogCore = /** @class */ (function () {
803
1220
  }
804
1221
  }
805
1222
  };
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); });
1223
+ PostHogCore.prototype.getCommonEventProperties = function () {
1224
+ var featureFlags = this.getFeatureFlags();
1225
+ var featureVariantProperties = {};
1226
+ if (featureFlags) {
1227
+ for (var _i = 0, _a = Object.entries(featureFlags); _i < _a.length; _i++) {
1228
+ var _b = _a[_i], feature = _b[0], variant = _b[1];
1229
+ featureVariantProperties["$feature/".concat(feature)] = variant;
1230
+ }
812
1231
  }
1232
+ return __assign(__assign({ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined }, featureVariantProperties), _super.prototype.getCommonEventProperties.call(this));
813
1233
  };
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
- };
1234
+ PostHogCore.prototype.enrichProperties = function (properties) {
1235
+ return __assign(__assign(__assign(__assign({}, this.props), (properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() });
820
1236
  };
821
1237
  PostHogCore.prototype.getSessionId = function () {
822
1238
  var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
@@ -859,48 +1275,41 @@ var PostHogCore = /** @class */ (function () {
859
1275
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
860
1276
  this.groups(properties.$groups);
861
1277
  }
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 });
1278
+ var allProperties = this.enrichProperties(__assign(__assign({}, properties), { $anon_distinct_id: this.getAnonymousId(), $set: properties }));
867
1279
  if (distinctId !== previousDistinctId) {
868
1280
  // We keep the AnonymousId to be used by decide calls and identify to link the previousId
869
1281
  this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
870
1282
  this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
871
1283
  if (this.getFeatureFlags()) {
872
- void this.reloadFeatureFlagsAsync();
1284
+ this.reloadFeatureFlags();
873
1285
  }
874
1286
  }
875
- this.enqueue('identify', payload, options);
1287
+ _super.prototype.identifyStateless.call(this, distinctId, allProperties, options);
876
1288
  return this;
877
1289
  };
878
1290
  PostHogCore.prototype.capture = function (event, properties, options) {
1291
+ var distinctId = this.getDistinctId();
879
1292
  if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
880
1293
  this.groups(properties.$groups);
881
1294
  }
882
- var payload = this.buildPayload({ event: event, properties: properties });
883
- this.enqueue('capture', payload, options);
1295
+ var allProperties = this.enrichProperties(properties);
1296
+ _super.prototype.captureStateless.call(this, distinctId, event, allProperties, options);
884
1297
  return this;
885
1298
  };
886
1299
  PostHogCore.prototype.alias = function (alias) {
887
1300
  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);
1301
+ var allProperties = this.enrichProperties({});
1302
+ _super.prototype.aliasStateless.call(this, alias, distinctId, allProperties);
896
1303
  return this;
897
1304
  };
898
1305
  PostHogCore.prototype.autocapture = function (eventType, elements, properties, options) {
899
1306
  if (properties === void 0) { properties = {}; }
900
- var payload = this.buildPayload({
1307
+ var distinctId = this.getDistinctId();
1308
+ var payload = {
1309
+ distinct_id: distinctId,
901
1310
  event: '$autocapture',
902
- properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
903
- });
1311
+ properties: __assign(__assign({}, this.enrichProperties(properties)), { $event_type: eventType, $elements: elements }),
1312
+ };
904
1313
  this.enqueue('autocapture', payload, options);
905
1314
  return this;
906
1315
  };
@@ -914,7 +1323,7 @@ var PostHogCore = /** @class */ (function () {
914
1323
  $groups: __assign(__assign({}, existingGroups), groups),
915
1324
  });
916
1325
  if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this.getFeatureFlags()) {
917
- void this.reloadFeatureFlagsAsync();
1326
+ this.reloadFeatureFlags();
918
1327
  }
919
1328
  return this;
920
1329
  };
@@ -929,11 +1338,9 @@ var PostHogCore = /** @class */ (function () {
929
1338
  return this;
930
1339
  };
931
1340
  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);
1341
+ var distinctId = this.getDistinctId();
1342
+ var eventProperties = this.enrichProperties({});
1343
+ _super.prototype.groupIdentifyStateless.call(this, groupType, groupKey, groupProperties, options, distinctId, eventProperties);
937
1344
  return this;
938
1345
  };
939
1346
  /***
@@ -970,30 +1377,19 @@ var PostHogCore = /** @class */ (function () {
970
1377
  PostHogCore.prototype._decideAsync = function (sendAnonDistinctId) {
971
1378
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
972
1379
  return __awaiter(this, void 0, void 0, function () {
973
- var url, distinctId, groups, personProperties, groupProperties, fetchOptions;
1380
+ var distinctId, groups, personProperties, groupProperties, extraProperties;
974
1381
  var _this = this;
975
1382
  return __generator(this, function (_a) {
976
- url = "".concat(this.host, "/decide/?v=3");
977
1383
  distinctId = this.getDistinctId();
978
1384
  groups = this.props.$groups || {};
979
1385
  personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
980
1386
  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
- }),
1387
+ extraProperties = {
1388
+ $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : undefined,
992
1389
  };
993
- this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
994
- .then(function (r) { return r.json(); })
1390
+ this._decideResponsePromise = _super.prototype.getDecide.call(this, distinctId, groups, personProperties, groupProperties, extraProperties)
995
1391
  .then(function (res) {
996
- if (res.featureFlags) {
1392
+ if (res === null || res === void 0 ? void 0 : res.featureFlags) {
997
1393
  var newFeatureFlags = res.featureFlags;
998
1394
  var newFeatureFlagPayloads = res.featureFlagPayloads;
999
1395
  if (res.errorsWhileComputingFlags) {
@@ -1067,14 +1463,6 @@ var PostHogCore = /** @class */ (function () {
1067
1463
  }
1068
1464
  return payloads;
1069
1465
  };
1070
- PostHogCore.prototype._parsePayload = function (response) {
1071
- try {
1072
- return JSON.parse(response);
1073
- }
1074
- catch (_a) {
1075
- return response;
1076
- }
1077
- };
1078
1466
  PostHogCore.prototype.getFeatureFlags = function () {
1079
1467
  var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1080
1468
  var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
@@ -1107,13 +1495,27 @@ var PostHogCore = /** @class */ (function () {
1107
1495
  }
1108
1496
  return !!response;
1109
1497
  };
1498
+ // Used when we want to trigger the reload but we don't care about the result
1499
+ PostHogCore.prototype.reloadFeatureFlags = function (cb) {
1500
+ this.decideAsync()
1501
+ .then(function (res) {
1502
+ cb === null || cb === void 0 ? void 0 : cb(undefined, res === null || res === void 0 ? void 0 : res.featureFlags);
1503
+ })
1504
+ .catch(function (e) {
1505
+ cb === null || cb === void 0 ? void 0 : cb(e, undefined);
1506
+ if (!cb) {
1507
+ console.log('[PostHog] Error reloading feature flags', e);
1508
+ }
1509
+ });
1510
+ };
1110
1511
  PostHogCore.prototype.reloadFeatureFlagsAsync = function (sendAnonDistinctId) {
1512
+ var _a;
1111
1513
  if (sendAnonDistinctId === void 0) { sendAnonDistinctId = true; }
1112
1514
  return __awaiter(this, void 0, void 0, function () {
1113
- return __generator(this, function (_a) {
1114
- switch (_a.label) {
1515
+ return __generator(this, function (_b) {
1516
+ switch (_b.label) {
1115
1517
  case 0: return [4 /*yield*/, this.decideAsync(sendAnonDistinctId)];
1116
- case 1: return [2 /*return*/, (_a.sent()).featureFlags];
1518
+ case 1: return [2 /*return*/, (_a = (_b.sent())) === null || _a === void 0 ? void 0 : _a.featureFlags];
1117
1519
  }
1118
1520
  });
1119
1521
  });
@@ -1150,134 +1552,10 @@ var PostHogCore = /** @class */ (function () {
1150
1552
  }
1151
1553
  return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1152
1554
  };
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
1555
  return PostHogCore;
1278
- }());
1556
+ }(PostHogCoreStateless));
1279
1557
 
1280
- var version = "2.2.0";
1558
+ var version = "2.3.0";
1281
1559
 
1282
1560
  function getContext(window) {
1283
1561
  var context = {};