@posthog/core 1.1.0 → 1.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.
Files changed (128) hide show
  1. package/dist/error-tracking/chunk-ids.js +1 -1
  2. package/dist/error-tracking/chunk-ids.mjs +1 -1
  3. package/dist/error-tracking/coercers/error-event-coercer.js +4 -5
  4. package/dist/error-tracking/coercers/error-event-coercer.mjs +4 -5
  5. package/dist/error-tracking/coercers/event-coercer.js +1 -2
  6. package/dist/error-tracking/coercers/event-coercer.mjs +1 -2
  7. package/dist/error-tracking/coercers/object-coercer.js +1 -2
  8. package/dist/error-tracking/coercers/object-coercer.mjs +1 -2
  9. package/dist/error-tracking/coercers/primitive-coercer.js +1 -2
  10. package/dist/error-tracking/coercers/primitive-coercer.mjs +1 -2
  11. package/dist/error-tracking/coercers/promise-rejection-event.js +4 -5
  12. package/dist/error-tracking/coercers/promise-rejection-event.mjs +4 -5
  13. package/dist/error-tracking/coercers/string-coercer.js +3 -4
  14. package/dist/error-tracking/coercers/string-coercer.mjs +3 -4
  15. package/dist/error-tracking/coercers/utils.js +2 -4
  16. package/dist/error-tracking/coercers/utils.mjs +2 -4
  17. package/dist/error-tracking/error-properties-builder.d.ts +6 -6
  18. package/dist/error-tracking/error-properties-builder.d.ts.map +1 -1
  19. package/dist/error-tracking/error-properties-builder.js +17 -27
  20. package/dist/error-tracking/error-properties-builder.mjs +16 -26
  21. package/dist/error-tracking/parsers/index.js +2 -4
  22. package/dist/error-tracking/parsers/index.mjs +2 -4
  23. package/dist/error-tracking/parsers/node.js +3 -5
  24. package/dist/error-tracking/parsers/node.mjs +3 -5
  25. package/dist/error-tracking/utils.js +4 -4
  26. package/dist/error-tracking/utils.mjs +4 -4
  27. package/dist/eventemitter.js +4 -4
  28. package/dist/eventemitter.mjs +4 -4
  29. package/dist/featureFlagUtils.js +20 -45
  30. package/dist/featureFlagUtils.mjs +20 -45
  31. package/dist/gzip.js +1 -2
  32. package/dist/gzip.mjs +1 -2
  33. package/dist/index.d.ts +4 -366
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +54 -1225
  36. package/dist/index.mjs +5 -1190
  37. package/dist/posthog-core-stateless.d.ts +204 -0
  38. package/dist/posthog-core-stateless.d.ts.map +1 -0
  39. package/dist/posthog-core-stateless.js +675 -0
  40. package/dist/posthog-core-stateless.mjs +632 -0
  41. package/dist/posthog-core.d.ts +171 -0
  42. package/dist/posthog-core.d.ts.map +1 -0
  43. package/dist/posthog-core.js +554 -0
  44. package/dist/posthog-core.mjs +520 -0
  45. package/dist/testing/PostHogCoreTestClient.d.ts +2 -1
  46. package/dist/testing/PostHogCoreTestClient.d.ts.map +1 -1
  47. package/dist/testing/PostHogCoreTestClient.js +9 -11
  48. package/dist/testing/PostHogCoreTestClient.mjs +8 -10
  49. package/dist/testing/test-utils.js +1 -1
  50. package/dist/testing/test-utils.mjs +1 -1
  51. package/dist/utils/bucketed-rate-limiter.js +8 -12
  52. package/dist/utils/bucketed-rate-limiter.mjs +8 -12
  53. package/dist/utils/index.js +3 -3
  54. package/dist/utils/index.mjs +3 -3
  55. package/dist/utils/type-utils.js +1 -1
  56. package/dist/utils/type-utils.mjs +1 -1
  57. package/dist/vendor/uuidv7.js +12 -16
  58. package/dist/vendor/uuidv7.mjs +12 -16
  59. package/package.json +3 -2
  60. package/src/__tests__/featureFlagUtils.spec.ts +427 -0
  61. package/src/__tests__/gzip.spec.ts +69 -0
  62. package/src/__tests__/posthog.ai.spec.ts +110 -0
  63. package/src/__tests__/posthog.capture.spec.ts +91 -0
  64. package/src/__tests__/posthog.core.spec.ts +135 -0
  65. package/src/__tests__/posthog.debug.spec.ts +36 -0
  66. package/src/__tests__/posthog.enqueue.spec.ts +93 -0
  67. package/src/__tests__/posthog.featureflags.spec.ts +1106 -0
  68. package/src/__tests__/posthog.featureflags.v1.spec.ts +922 -0
  69. package/src/__tests__/posthog.flush.spec.ts +237 -0
  70. package/src/__tests__/posthog.gdpr.spec.ts +50 -0
  71. package/src/__tests__/posthog.groups.spec.ts +96 -0
  72. package/src/__tests__/posthog.identify.spec.ts +194 -0
  73. package/src/__tests__/posthog.init.spec.ts +110 -0
  74. package/src/__tests__/posthog.listeners.spec.ts +51 -0
  75. package/src/__tests__/posthog.register.spec.ts +47 -0
  76. package/src/__tests__/posthog.reset.spec.ts +76 -0
  77. package/src/__tests__/posthog.sessions.spec.ts +63 -0
  78. package/src/__tests__/posthog.setProperties.spec.ts +102 -0
  79. package/src/__tests__/posthog.shutdown.spec.ts +88 -0
  80. package/src/__tests__/utils.spec.ts +36 -0
  81. package/src/error-tracking/chunk-ids.ts +58 -0
  82. package/src/error-tracking/coercers/dom-exception-coercer.ts +38 -0
  83. package/src/error-tracking/coercers/error-coercer.ts +36 -0
  84. package/src/error-tracking/coercers/error-event-coercer.ts +24 -0
  85. package/src/error-tracking/coercers/event-coercer.ts +19 -0
  86. package/src/error-tracking/coercers/index.ts +8 -0
  87. package/src/error-tracking/coercers/object-coercer.ts +76 -0
  88. package/src/error-tracking/coercers/primitive-coercer.ts +19 -0
  89. package/src/error-tracking/coercers/promise-rejection-event.spec.ts +77 -0
  90. package/src/error-tracking/coercers/promise-rejection-event.ts +53 -0
  91. package/src/error-tracking/coercers/string-coercer.spec.ts +26 -0
  92. package/src/error-tracking/coercers/string-coercer.ts +31 -0
  93. package/src/error-tracking/coercers/utils.ts +33 -0
  94. package/src/error-tracking/error-properties-builder.coerce.spec.ts +202 -0
  95. package/src/error-tracking/error-properties-builder.parse.spec.ts +30 -0
  96. package/src/error-tracking/error-properties-builder.ts +167 -0
  97. package/src/error-tracking/index.ts +5 -0
  98. package/src/error-tracking/parsers/base.ts +29 -0
  99. package/src/error-tracking/parsers/chrome.ts +53 -0
  100. package/src/error-tracking/parsers/gecko.ts +38 -0
  101. package/src/error-tracking/parsers/index.ts +104 -0
  102. package/src/error-tracking/parsers/node.ts +111 -0
  103. package/src/error-tracking/parsers/opera.ts +18 -0
  104. package/src/error-tracking/parsers/react-native.ts +0 -0
  105. package/src/error-tracking/parsers/safari.ts +33 -0
  106. package/src/error-tracking/parsers/winjs.ts +12 -0
  107. package/src/error-tracking/types.ts +107 -0
  108. package/src/error-tracking/utils.ts +39 -0
  109. package/src/eventemitter.ts +27 -0
  110. package/src/featureFlagUtils.ts +192 -0
  111. package/src/gzip.ts +29 -0
  112. package/src/index.ts +8 -0
  113. package/src/posthog-core-stateless.ts +1226 -0
  114. package/src/posthog-core.ts +958 -0
  115. package/src/testing/PostHogCoreTestClient.ts +91 -0
  116. package/src/testing/index.ts +2 -0
  117. package/src/testing/test-utils.ts +47 -0
  118. package/src/types.ts +544 -0
  119. package/src/utils/bucketed-rate-limiter.spec.ts +33 -0
  120. package/src/utils/bucketed-rate-limiter.ts +85 -0
  121. package/src/utils/index.ts +98 -0
  122. package/src/utils/number-utils.spec.ts +89 -0
  123. package/src/utils/number-utils.ts +30 -0
  124. package/src/utils/promise-queue.spec.ts +55 -0
  125. package/src/utils/promise-queue.ts +30 -0
  126. package/src/utils/string-utils.ts +23 -0
  127. package/src/utils/type-utils.ts +134 -0
  128. package/src/vendor/uuidv7.ts +479 -0
package/dist/index.mjs CHANGED
@@ -1,1194 +1,9 @@
1
- import { Compression, PostHogPersistedProperty } from "./types.mjs";
2
- import { createFlagsResponseFromFlagsAndPayloads, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, normalizeFlagsResponse, updateFlagValue } from "./featureFlagUtils.mjs";
3
- import { STRING_FORMAT, allSettled, assert, currentISOTime, isPlainError, removeTrailingSlash, retriable, safeSetTimeout } from "./utils/index.mjs";
4
- import { gzipCompress, isGzipSupported } from "./gzip.mjs";
5
- import { SimpleEventEmitter } from "./eventemitter.mjs";
1
+ import { getFeatureFlagValue } from "./featureFlagUtils.mjs";
6
2
  import { uuidv7 } from "./vendor/uuidv7.mjs";
7
- import { PromiseQueue } from "./utils/promise-queue.mjs";
8
3
  export * from "./utils/index.mjs";
4
+ export * from "./posthog-core.mjs";
5
+ export * from "./posthog-core-stateless.mjs";
9
6
  export * from "./types.mjs";
10
7
  import * as __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ from "./error-tracking/index.mjs";
11
- class PostHogFetchHttpError extends Error {
12
- get status() {
13
- return this.response.status;
14
- }
15
- get text() {
16
- return this.response.text();
17
- }
18
- get json() {
19
- return this.response.json();
20
- }
21
- constructor(response, reqByteLength){
22
- super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = 'PostHogFetchHttpError';
23
- }
24
- }
25
- class PostHogFetchNetworkError extends Error {
26
- constructor(error){
27
- super('Network error while fetching PostHog', error instanceof Error ? {
28
- cause: error
29
- } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';
30
- }
31
- }
32
- const maybeAdd = (key, value)=>void 0 !== value ? {
33
- [key]: value
34
- } : {};
35
- async function logFlushError(err) {
36
- if (err instanceof PostHogFetchHttpError) {
37
- let text = '';
38
- try {
39
- text = await err.text;
40
- } catch (e) {}
41
- console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
42
- } else console.error('Error while flushing PostHog', err);
43
- return Promise.resolve();
44
- }
45
- function isPostHogFetchError(err) {
46
- return 'object' == typeof err && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
47
- }
48
- function isPostHogFetchContentTooLargeError(err) {
49
- return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
50
- }
51
- class PostHogCoreStateless {
52
- logMsgIfDebug(fn) {
53
- if (this.isDebug) fn();
54
- }
55
- wrap(fn) {
56
- if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
57
- if (this._isInitialized) return fn();
58
- this._initPromise.then(()=>fn());
59
- }
60
- getCommonEventProperties() {
61
- return {
62
- $lib: this.getLibraryId(),
63
- $lib_version: this.getLibraryVersion()
64
- };
65
- }
66
- get optedOut() {
67
- var _this_getPersistedProperty;
68
- return null != (_this_getPersistedProperty = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) ? _this_getPersistedProperty : !this.defaultOptIn;
69
- }
70
- async optIn() {
71
- this.wrap(()=>{
72
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
73
- });
74
- }
75
- async optOut() {
76
- this.wrap(()=>{
77
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
78
- });
79
- }
80
- on(event, cb) {
81
- return this._events.on(event, cb);
82
- }
83
- debug() {
84
- let enabled = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
85
- var _this_removeDebugCallback, _this;
86
- null == (_this_removeDebugCallback = (_this = this).removeDebugCallback) || _this_removeDebugCallback.call(_this);
87
- if (enabled) {
88
- const removeDebugCallback = this.on('*', (event, payload)=>console.log('PostHog Debug', event, payload));
89
- this.removeDebugCallback = ()=>{
90
- removeDebugCallback();
91
- this.removeDebugCallback = void 0;
92
- };
93
- }
94
- }
95
- get isDebug() {
96
- return !!this.removeDebugCallback;
97
- }
98
- get isDisabled() {
99
- return this.disabled;
100
- }
101
- buildPayload(payload) {
102
- return {
103
- distinct_id: payload.distinct_id,
104
- event: payload.event,
105
- properties: {
106
- ...payload.properties || {},
107
- ...this.getCommonEventProperties()
108
- }
109
- };
110
- }
111
- addPendingPromise(promise) {
112
- return this.promiseQueue.add(promise);
113
- }
114
- identifyStateless(distinctId, properties, options) {
115
- this.wrap(()=>{
116
- const payload = {
117
- ...this.buildPayload({
118
- distinct_id: distinctId,
119
- event: '$identify',
120
- properties
121
- })
122
- };
123
- this.enqueue('identify', payload, options);
124
- });
125
- }
126
- async identifyStatelessImmediate(distinctId, properties, options) {
127
- const payload = {
128
- ...this.buildPayload({
129
- distinct_id: distinctId,
130
- event: '$identify',
131
- properties
132
- })
133
- };
134
- await this.sendImmediate('identify', payload, options);
135
- }
136
- captureStateless(distinctId, event, properties, options) {
137
- this.wrap(()=>{
138
- const payload = this.buildPayload({
139
- distinct_id: distinctId,
140
- event,
141
- properties
142
- });
143
- this.enqueue('capture', payload, options);
144
- });
145
- }
146
- async captureStatelessImmediate(distinctId, event, properties, options) {
147
- const payload = this.buildPayload({
148
- distinct_id: distinctId,
149
- event,
150
- properties
151
- });
152
- await this.sendImmediate('capture', payload, options);
153
- }
154
- aliasStateless(alias, distinctId, properties, options) {
155
- this.wrap(()=>{
156
- const payload = this.buildPayload({
157
- event: '$create_alias',
158
- distinct_id: distinctId,
159
- properties: {
160
- ...properties || {},
161
- distinct_id: distinctId,
162
- alias
163
- }
164
- });
165
- this.enqueue('alias', payload, options);
166
- });
167
- }
168
- async aliasStatelessImmediate(alias, distinctId, properties, options) {
169
- const payload = this.buildPayload({
170
- event: '$create_alias',
171
- distinct_id: distinctId,
172
- properties: {
173
- ...properties || {},
174
- distinct_id: distinctId,
175
- alias
176
- }
177
- });
178
- await this.sendImmediate('alias', payload, options);
179
- }
180
- groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
181
- this.wrap(()=>{
182
- const payload = this.buildPayload({
183
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
184
- event: '$groupidentify',
185
- properties: {
186
- $group_type: groupType,
187
- $group_key: groupKey,
188
- $group_set: groupProperties || {},
189
- ...eventProperties || {}
190
- }
191
- });
192
- this.enqueue('capture', payload, options);
193
- });
194
- }
195
- async getRemoteConfig() {
196
- await this._initPromise;
197
- let host = this.host;
198
- if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';
199
- else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';
200
- const url = `${host}/array/${this.apiKey}/config`;
201
- const fetchOptions = {
202
- method: 'GET',
203
- headers: {
204
- ...this.getCustomHeaders(),
205
- 'Content-Type': 'application/json'
206
- }
207
- };
208
- return this.fetchWithRetry(url, fetchOptions, {
209
- retryCount: 0
210
- }, this.remoteConfigRequestTimeoutMs).then((response)=>response.json()).catch((error)=>{
211
- this.logMsgIfDebug(()=>console.error('Remote config could not be loaded', error));
212
- this._events.emit('error', error);
213
- });
214
- }
215
- async getFlags(distinctId) {
216
- let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, extraPayload = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {};
217
- await this._initPromise;
218
- const url = `${this.host}/flags/?v=2&config=true`;
219
- const fetchOptions = {
220
- method: 'POST',
221
- headers: {
222
- ...this.getCustomHeaders(),
223
- 'Content-Type': 'application/json'
224
- },
225
- body: JSON.stringify({
226
- token: this.apiKey,
227
- distinct_id: distinctId,
228
- groups,
229
- person_properties: personProperties,
230
- group_properties: groupProperties,
231
- ...extraPayload
232
- })
233
- };
234
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Flags URL', url));
235
- return this.fetchWithRetry(url, fetchOptions, {
236
- retryCount: 0
237
- }, this.featureFlagsRequestTimeoutMs).then((response)=>response.json()).then((response)=>normalizeFlagsResponse(response)).catch((error)=>{
238
- this._events.emit('error', error);
239
- });
240
- }
241
- async getFeatureFlagStateless(key, distinctId) {
242
- let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
243
- await this._initPromise;
244
- const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
245
- if (void 0 === flagDetailResponse) return {
246
- response: void 0,
247
- requestId: void 0
248
- };
249
- let response = getFeatureFlagValue(flagDetailResponse.response);
250
- if (void 0 === response) response = false;
251
- return {
252
- response,
253
- requestId: flagDetailResponse.requestId
254
- };
255
- }
256
- async getFeatureFlagDetailStateless(key, distinctId) {
257
- let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
258
- await this._initPromise;
259
- const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
260
- key
261
- ]);
262
- if (void 0 === flagsResponse) return;
263
- const featureFlags = flagsResponse.flags;
264
- const flagDetail = featureFlags[key];
265
- return {
266
- response: flagDetail,
267
- requestId: flagsResponse.requestId
268
- };
269
- }
270
- async getFeatureFlagPayloadStateless(key, distinctId) {
271
- let groups = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, personProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, groupProperties = arguments.length > 4 && void 0 !== arguments[4] ? arguments[4] : {}, disableGeoip = arguments.length > 5 ? arguments[5] : void 0;
272
- await this._initPromise;
273
- const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
274
- key
275
- ]);
276
- if (!payloads) return;
277
- const response = payloads[key];
278
- if (void 0 === response) return null;
279
- return response;
280
- }
281
- async getFeatureFlagPayloadsStateless(distinctId) {
282
- let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
283
- await this._initPromise;
284
- const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
285
- return payloads;
286
- }
287
- async getFeatureFlagsStateless(distinctId) {
288
- let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
289
- await this._initPromise;
290
- return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
291
- }
292
- async getFeatureFlagsAndPayloadsStateless(distinctId) {
293
- let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
294
- await this._initPromise;
295
- const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
296
- if (!featureFlagDetails) return {
297
- flags: void 0,
298
- payloads: void 0,
299
- requestId: void 0
300
- };
301
- return {
302
- flags: featureFlagDetails.featureFlags,
303
- payloads: featureFlagDetails.featureFlagPayloads,
304
- requestId: featureFlagDetails.requestId
305
- };
306
- }
307
- async getFeatureFlagDetailsStateless(distinctId) {
308
- let groups = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}, personProperties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, groupProperties = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : {}, disableGeoip = arguments.length > 4 ? arguments[4] : void 0, flagKeysToEvaluate = arguments.length > 5 ? arguments[5] : void 0;
309
- var _flagsResponse_quotaLimited;
310
- await this._initPromise;
311
- const extraPayload = {};
312
- if (null != disableGeoip ? disableGeoip : this.disableGeoip) extraPayload['geoip_disable'] = true;
313
- if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
314
- const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
315
- if (void 0 === flagsResponse) return;
316
- if (flagsResponse.errorsWhileComputingFlags) console.error('[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices');
317
- if (null == (_flagsResponse_quotaLimited = flagsResponse.quotaLimited) ? void 0 : _flagsResponse_quotaLimited.includes("feature_flags")) {
318
- console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
319
- return {
320
- flags: {},
321
- featureFlags: {},
322
- featureFlagPayloads: {},
323
- requestId: null == flagsResponse ? void 0 : flagsResponse.requestId
324
- };
325
- }
326
- return flagsResponse;
327
- }
328
- async getSurveysStateless() {
329
- await this._initPromise;
330
- if (true === this.disableSurveys) {
331
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Loading surveys is disabled.'));
332
- return [];
333
- }
334
- const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
335
- const fetchOptions = {
336
- method: 'GET',
337
- headers: {
338
- ...this.getCustomHeaders(),
339
- 'Content-Type': 'application/json'
340
- }
341
- };
342
- const response = await this.fetchWithRetry(url, fetchOptions).then((response)=>{
343
- if (200 !== response.status || !response.json) {
344
- const msg = `Surveys API could not be loaded: ${response.status}`;
345
- const error = new Error(msg);
346
- this.logMsgIfDebug(()=>console.error(error));
347
- this._events.emit('error', new Error(msg));
348
- return;
349
- }
350
- return response.json();
351
- }).catch((error)=>{
352
- this.logMsgIfDebug(()=>console.error('Surveys API could not be loaded', error));
353
- this._events.emit('error', error);
354
- });
355
- const newSurveys = null == response ? void 0 : response.surveys;
356
- if (newSurveys) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
357
- return null != newSurveys ? newSurveys : [];
358
- }
359
- get props() {
360
- if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
361
- return this._props || {};
362
- }
363
- set props(val) {
364
- this._props = val;
365
- }
366
- async register(properties) {
367
- this.wrap(()=>{
368
- this.props = {
369
- ...this.props,
370
- ...properties
371
- };
372
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
373
- });
374
- }
375
- async unregister(property) {
376
- this.wrap(()=>{
377
- delete this.props[property];
378
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
379
- });
380
- }
381
- enqueue(type, _message, options) {
382
- this.wrap(()=>{
383
- if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
384
- const message = this.prepareMessage(type, _message, options);
385
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
386
- if (queue.length >= this.maxQueueSize) {
387
- queue.shift();
388
- this.logMsgIfDebug(()=>console.info('Queue is full, the oldest event is dropped.'));
389
- }
390
- queue.push({
391
- message
392
- });
393
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
394
- this._events.emit(type, message);
395
- if (queue.length >= this.flushAt) this.flushBackground();
396
- if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(()=>this.flushBackground(), this.flushInterval);
397
- });
398
- }
399
- async sendImmediate(type, _message, options) {
400
- if (this.disabled) return void this.logMsgIfDebug(()=>console.warn('[PostHog] The client is disabled'));
401
- if (!this._isInitialized) await this._initPromise;
402
- if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
403
- const data = {
404
- api_key: this.apiKey,
405
- batch: [
406
- this.prepareMessage(type, _message, options)
407
- ],
408
- sent_at: currentISOTime()
409
- };
410
- if (this.historicalMigration) data.historical_migration = true;
411
- const payload = JSON.stringify(data);
412
- const url = `${this.host}/batch/`;
413
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
414
- const fetchOptions = {
415
- method: 'POST',
416
- headers: {
417
- ...this.getCustomHeaders(),
418
- 'Content-Type': 'application/json',
419
- ...null !== gzippedPayload && {
420
- 'Content-Encoding': 'gzip'
421
- }
422
- },
423
- body: gzippedPayload || payload
424
- };
425
- try {
426
- await this.fetchWithRetry(url, fetchOptions);
427
- } catch (err) {
428
- this._events.emit('error', err);
429
- }
430
- }
431
- prepareMessage(type, _message, options) {
432
- const message = {
433
- ..._message,
434
- type: type,
435
- library: this.getLibraryId(),
436
- library_version: this.getLibraryVersion(),
437
- timestamp: (null == options ? void 0 : options.timestamp) ? null == options ? void 0 : options.timestamp : currentISOTime(),
438
- uuid: (null == options ? void 0 : options.uuid) ? options.uuid : uuidv7()
439
- };
440
- var _options_disableGeoip;
441
- const addGeoipDisableProperty = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : this.disableGeoip;
442
- if (addGeoipDisableProperty) {
443
- if (!message.properties) message.properties = {};
444
- message['properties']['$geoip_disable'] = true;
445
- }
446
- if (message.distinctId) {
447
- message.distinct_id = message.distinctId;
448
- delete message.distinctId;
449
- }
450
- return message;
451
- }
452
- clearFlushTimer() {
453
- if (this._flushTimer) {
454
- clearTimeout(this._flushTimer);
455
- this._flushTimer = void 0;
456
- }
457
- }
458
- flushBackground() {
459
- this.flush().catch(async (err)=>{
460
- await logFlushError(err);
461
- });
462
- }
463
- async flush() {
464
- const nextFlushPromise = allSettled([
465
- this.flushPromise
466
- ]).then(()=>this._flush());
467
- this.flushPromise = nextFlushPromise;
468
- this.addPendingPromise(nextFlushPromise);
469
- allSettled([
470
- nextFlushPromise
471
- ]).then(()=>{
472
- if (this.flushPromise === nextFlushPromise) this.flushPromise = null;
473
- });
474
- return nextFlushPromise;
475
- }
476
- getCustomHeaders() {
477
- const customUserAgent = this.getCustomUserAgent();
478
- const headers = {};
479
- if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;
480
- return headers;
481
- }
482
- async _flush() {
483
- this.clearFlushTimer();
484
- await this._initPromise;
485
- let queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
486
- if (!queue.length) return;
487
- const sentMessages = [];
488
- const originalQueueLength = queue.length;
489
- while(queue.length > 0 && sentMessages.length < originalQueueLength){
490
- const batchItems = queue.slice(0, this.maxBatchSize);
491
- const batchMessages = batchItems.map((item)=>item.message);
492
- const persistQueueChange = ()=>{
493
- const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
494
- const newQueue = refreshedQueue.slice(batchItems.length);
495
- this.setPersistedProperty(PostHogPersistedProperty.Queue, newQueue);
496
- queue = newQueue;
497
- };
498
- const data = {
499
- api_key: this.apiKey,
500
- batch: batchMessages,
501
- sent_at: currentISOTime()
502
- };
503
- if (this.historicalMigration) data.historical_migration = true;
504
- const payload = JSON.stringify(data);
505
- const url = `${this.host}/batch/`;
506
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
507
- const fetchOptions = {
508
- method: 'POST',
509
- headers: {
510
- ...this.getCustomHeaders(),
511
- 'Content-Type': 'application/json',
512
- ...null !== gzippedPayload && {
513
- 'Content-Encoding': 'gzip'
514
- }
515
- },
516
- body: gzippedPayload || payload
517
- };
518
- const retryOptions = {
519
- retryCheck: (err)=>{
520
- if (isPostHogFetchContentTooLargeError(err)) return false;
521
- return isPostHogFetchError(err);
522
- }
523
- };
524
- try {
525
- await this.fetchWithRetry(url, fetchOptions, retryOptions);
526
- } catch (err) {
527
- if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
528
- this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
529
- this.logMsgIfDebug(()=>console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
530
- continue;
531
- }
532
- if (!(err instanceof PostHogFetchNetworkError)) persistQueueChange();
533
- this._events.emit('error', err);
534
- throw err;
535
- }
536
- persistQueueChange();
537
- sentMessages.push(...batchMessages);
538
- }
539
- this._events.emit('flush', sentMessages);
540
- }
541
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
542
- var _AbortSignal;
543
- null != (_AbortSignal = AbortSignal).timeout || (_AbortSignal.timeout = function(ms) {
544
- const ctrl = new AbortController();
545
- setTimeout(()=>ctrl.abort(), ms);
546
- return ctrl.signal;
547
- });
548
- const body = options.body ? options.body : '';
549
- let reqByteLength = -1;
550
- try {
551
- reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
552
- } catch (e) {
553
- if (body instanceof Blob) reqByteLength = body.size;
554
- else {
555
- const encoded = new TextEncoder().encode(body);
556
- reqByteLength = encoded.length;
557
- }
558
- }
559
- return await retriable(async ()=>{
560
- let res = null;
561
- try {
562
- res = await this.fetch(url, {
563
- signal: AbortSignal.timeout(null != requestTimeout ? requestTimeout : this.requestTimeout),
564
- ...options
565
- });
566
- } catch (e) {
567
- throw new PostHogFetchNetworkError(e);
568
- }
569
- const isNoCors = 'no-cors' === options.mode;
570
- if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);
571
- return res;
572
- }, {
573
- ...this._retryOptions,
574
- ...retryOptions
575
- });
576
- }
577
- async _shutdown() {
578
- let shutdownTimeoutMs = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 30000;
579
- await this._initPromise;
580
- let hasTimedOut = false;
581
- this.clearFlushTimer();
582
- const doShutdown = async ()=>{
583
- try {
584
- await this.promiseQueue.join();
585
- while(true){
586
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
587
- if (0 === queue.length) break;
588
- await this.flush();
589
- if (hasTimedOut) break;
590
- }
591
- } catch (e) {
592
- if (!isPostHogFetchError(e)) throw e;
593
- await logFlushError(e);
594
- }
595
- };
596
- return Promise.race([
597
- new Promise((_, reject)=>{
598
- safeSetTimeout(()=>{
599
- this.logMsgIfDebug(()=>console.error('Timed out while shutting down PostHog'));
600
- hasTimedOut = true;
601
- reject('Timeout while shutting down PostHog. Some events may not have been sent.');
602
- }, shutdownTimeoutMs);
603
- }),
604
- doShutdown()
605
- ]);
606
- }
607
- async shutdown() {
608
- let shutdownTimeoutMs = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 30000;
609
- if (this.shutdownPromise) this.logMsgIfDebug(()=>console.warn('shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup'));
610
- else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{
611
- this.shutdownPromise = null;
612
- });
613
- return this.shutdownPromise;
614
- }
615
- constructor(apiKey, options){
616
- this.flushPromise = null;
617
- this.shutdownPromise = null;
618
- this.promiseQueue = new PromiseQueue();
619
- this._events = new SimpleEventEmitter();
620
- this._isInitialized = false;
621
- assert(apiKey, "You must pass your PostHog project's api key.");
622
- this.apiKey = apiKey;
623
- this.host = removeTrailingSlash((null == options ? void 0 : options.host) || 'https://us.i.posthog.com');
624
- this.flushAt = (null == options ? void 0 : options.flushAt) ? Math.max(null == options ? void 0 : options.flushAt, 1) : 20;
625
- var _options_maxBatchSize;
626
- this.maxBatchSize = Math.max(this.flushAt, null != (_options_maxBatchSize = null == options ? void 0 : options.maxBatchSize) ? _options_maxBatchSize : 100);
627
- var _options_maxQueueSize;
628
- this.maxQueueSize = Math.max(this.flushAt, null != (_options_maxQueueSize = null == options ? void 0 : options.maxQueueSize) ? _options_maxQueueSize : 1000);
629
- var _options_flushInterval;
630
- this.flushInterval = null != (_options_flushInterval = null == options ? void 0 : options.flushInterval) ? _options_flushInterval : 10000;
631
- var _options_preloadFeatureFlags;
632
- this.preloadFeatureFlags = null != (_options_preloadFeatureFlags = null == options ? void 0 : options.preloadFeatureFlags) ? _options_preloadFeatureFlags : true;
633
- var _options_defaultOptIn;
634
- this.defaultOptIn = null != (_options_defaultOptIn = null == options ? void 0 : options.defaultOptIn) ? _options_defaultOptIn : true;
635
- var _options_disableSurveys;
636
- this.disableSurveys = null != (_options_disableSurveys = null == options ? void 0 : options.disableSurveys) ? _options_disableSurveys : false;
637
- var _options_fetchRetryCount, _options_fetchRetryDelay;
638
- this._retryOptions = {
639
- retryCount: null != (_options_fetchRetryCount = null == options ? void 0 : options.fetchRetryCount) ? _options_fetchRetryCount : 3,
640
- retryDelay: null != (_options_fetchRetryDelay = null == options ? void 0 : options.fetchRetryDelay) ? _options_fetchRetryDelay : 3000,
641
- retryCheck: isPostHogFetchError
642
- };
643
- var _options_requestTimeout;
644
- this.requestTimeout = null != (_options_requestTimeout = null == options ? void 0 : options.requestTimeout) ? _options_requestTimeout : 10000;
645
- var _options_featureFlagsRequestTimeoutMs;
646
- this.featureFlagsRequestTimeoutMs = null != (_options_featureFlagsRequestTimeoutMs = null == options ? void 0 : options.featureFlagsRequestTimeoutMs) ? _options_featureFlagsRequestTimeoutMs : 3000;
647
- var _options_remoteConfigRequestTimeoutMs;
648
- this.remoteConfigRequestTimeoutMs = null != (_options_remoteConfigRequestTimeoutMs = null == options ? void 0 : options.remoteConfigRequestTimeoutMs) ? _options_remoteConfigRequestTimeoutMs : 3000;
649
- var _options_disableGeoip;
650
- this.disableGeoip = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : true;
651
- var _options_disabled;
652
- this.disabled = null != (_options_disabled = null == options ? void 0 : options.disabled) ? _options_disabled : false;
653
- var _options_historicalMigration;
654
- this.historicalMigration = null != (_options_historicalMigration = null == options ? void 0 : options.historicalMigration) ? _options_historicalMigration : false;
655
- this._initPromise = Promise.resolve();
656
- this._isInitialized = true;
657
- var _options_disableCompression;
658
- this.disableCompression = !isGzipSupported() || (null != (_options_disableCompression = null == options ? void 0 : options.disableCompression) ? _options_disableCompression : false);
659
- }
660
- }
661
- class PostHogCore extends PostHogCoreStateless {
662
- setupBootstrap(options) {
663
- const bootstrap = null == options ? void 0 : options.bootstrap;
664
- if (!bootstrap) return;
665
- if (bootstrap.distinctId) if (bootstrap.isIdentifiedId) {
666
- const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
667
- if (!distinctId) this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);
668
- } else {
669
- const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
670
- if (!anonymousId) this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);
671
- }
672
- const bootstrapFeatureFlags = bootstrap.featureFlags;
673
- var _bootstrap_featureFlagPayloads;
674
- const bootstrapFeatureFlagPayloads = null != (_bootstrap_featureFlagPayloads = bootstrap.featureFlagPayloads) ? _bootstrap_featureFlagPayloads : {};
675
- if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {
676
- const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(bootstrapFeatureFlags, bootstrapFeatureFlagPayloads);
677
- if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {
678
- this.setBootstrappedFeatureFlagDetails(normalizedBootstrapFeatureFlagDetails);
679
- const currentFeatureFlagDetails = this.getKnownFeatureFlagDetails() || {
680
- flags: {},
681
- requestId: void 0
682
- };
683
- const newFeatureFlagDetails = {
684
- flags: {
685
- ...normalizedBootstrapFeatureFlagDetails.flags,
686
- ...currentFeatureFlagDetails.flags
687
- },
688
- requestId: normalizedBootstrapFeatureFlagDetails.requestId
689
- };
690
- this.setKnownFeatureFlagDetails(newFeatureFlagDetails);
691
- }
692
- }
693
- }
694
- clearProps() {
695
- this.props = void 0;
696
- this.sessionProps = {};
697
- this.flagCallReported = {};
698
- }
699
- on(event, cb) {
700
- return this._events.on(event, cb);
701
- }
702
- reset(propertiesToKeep) {
703
- this.wrap(()=>{
704
- const allPropertiesToKeep = [
705
- PostHogPersistedProperty.Queue,
706
- ...propertiesToKeep || []
707
- ];
708
- this.clearProps();
709
- for (const key of Object.keys(PostHogPersistedProperty))if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) this.setPersistedProperty(PostHogPersistedProperty[key], null);
710
- this.reloadFeatureFlags();
711
- });
712
- }
713
- getCommonEventProperties() {
714
- const featureFlags = this.getFeatureFlags();
715
- const featureVariantProperties = {};
716
- if (featureFlags) for (const [feature, variant] of Object.entries(featureFlags))featureVariantProperties[`$feature/${feature}`] = variant;
717
- return {
718
- ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : void 0),
719
- ...featureVariantProperties,
720
- ...super.getCommonEventProperties()
721
- };
722
- }
723
- enrichProperties(properties) {
724
- return {
725
- ...this.props,
726
- ...this.sessionProps,
727
- ...properties || {},
728
- ...this.getCommonEventProperties(),
729
- $session_id: this.getSessionId()
730
- };
731
- }
732
- getSessionId() {
733
- if (!this._isInitialized) return '';
734
- let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
735
- const sessionLastTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
736
- const sessionStartTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp) || 0;
737
- const now = Date.now();
738
- const sessionLastDif = now - sessionLastTimestamp;
739
- const sessionStartDif = now - sessionStartTimestamp;
740
- if (!sessionId || sessionLastDif > 1000 * this._sessionExpirationTimeSeconds || sessionStartDif > 1000 * this._sessionMaxLengthSeconds) {
741
- sessionId = uuidv7();
742
- this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
743
- this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, now);
744
- }
745
- this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, now);
746
- return sessionId;
747
- }
748
- resetSessionId() {
749
- this.wrap(()=>{
750
- this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);
751
- this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);
752
- this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null);
753
- });
754
- }
755
- getAnonymousId() {
756
- if (!this._isInitialized) return '';
757
- let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);
758
- if (!anonId) {
759
- anonId = uuidv7();
760
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);
761
- }
762
- return anonId;
763
- }
764
- getDistinctId() {
765
- if (!this._isInitialized) return '';
766
- return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();
767
- }
768
- registerForSession(properties) {
769
- this.sessionProps = {
770
- ...this.sessionProps,
771
- ...properties
772
- };
773
- }
774
- unregisterForSession(property) {
775
- delete this.sessionProps[property];
776
- }
777
- identify(distinctId, properties, options) {
778
- this.wrap(()=>{
779
- const previousDistinctId = this.getDistinctId();
780
- distinctId = distinctId || previousDistinctId;
781
- if (null == properties ? void 0 : properties.$groups) this.groups(properties.$groups);
782
- const userPropsOnce = null == properties ? void 0 : properties.$set_once;
783
- null == properties || delete properties.$set_once;
784
- const userProps = (null == properties ? void 0 : properties.$set) || properties;
785
- const allProperties = this.enrichProperties({
786
- $anon_distinct_id: this.getAnonymousId(),
787
- ...maybeAdd('$set', userProps),
788
- ...maybeAdd('$set_once', userPropsOnce)
789
- });
790
- if (distinctId !== previousDistinctId) {
791
- this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);
792
- this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
793
- this.reloadFeatureFlags();
794
- }
795
- super.identifyStateless(distinctId, allProperties, options);
796
- });
797
- }
798
- capture(event, properties, options) {
799
- this.wrap(()=>{
800
- const distinctId = this.getDistinctId();
801
- if (null == properties ? void 0 : properties.$groups) this.groups(properties.$groups);
802
- const allProperties = this.enrichProperties(properties);
803
- super.captureStateless(distinctId, event, allProperties, options);
804
- });
805
- }
806
- alias(alias) {
807
- this.wrap(()=>{
808
- const distinctId = this.getDistinctId();
809
- const allProperties = this.enrichProperties({});
810
- super.aliasStateless(alias, distinctId, allProperties);
811
- });
812
- }
813
- autocapture(eventType, elements) {
814
- let properties = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}, options = arguments.length > 3 ? arguments[3] : void 0;
815
- this.wrap(()=>{
816
- const distinctId = this.getDistinctId();
817
- const payload = {
818
- distinct_id: distinctId,
819
- event: '$autocapture',
820
- properties: {
821
- ...this.enrichProperties(properties),
822
- $event_type: eventType,
823
- $elements: elements
824
- }
825
- };
826
- this.enqueue('autocapture', payload, options);
827
- });
828
- }
829
- groups(groups) {
830
- this.wrap(()=>{
831
- const existingGroups = this.props.$groups || {};
832
- this.register({
833
- $groups: {
834
- ...existingGroups,
835
- ...groups
836
- }
837
- });
838
- if (Object.keys(groups).find((type)=>existingGroups[type] !== groups[type])) this.reloadFeatureFlags();
839
- });
840
- }
841
- group(groupType, groupKey, groupProperties, options) {
842
- this.wrap(()=>{
843
- this.groups({
844
- [groupType]: groupKey
845
- });
846
- if (groupProperties) this.groupIdentify(groupType, groupKey, groupProperties, options);
847
- });
848
- }
849
- groupIdentify(groupType, groupKey, groupProperties, options) {
850
- this.wrap(()=>{
851
- const distinctId = this.getDistinctId();
852
- const eventProperties = this.enrichProperties({});
853
- super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);
854
- });
855
- }
856
- setPersonPropertiesForFlags(properties) {
857
- this.wrap(()=>{
858
- const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
859
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {
860
- ...existingProperties,
861
- ...properties
862
- });
863
- });
864
- }
865
- resetPersonPropertiesForFlags() {
866
- this.wrap(()=>{
867
- this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, null);
868
- });
869
- }
870
- setGroupPropertiesForFlags(properties) {
871
- this.wrap(()=>{
872
- const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
873
- if (0 !== Object.keys(existingProperties).length) Object.keys(existingProperties).forEach((groupType)=>{
874
- existingProperties[groupType] = {
875
- ...existingProperties[groupType],
876
- ...properties[groupType]
877
- };
878
- delete properties[groupType];
879
- });
880
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {
881
- ...existingProperties,
882
- ...properties
883
- });
884
- });
885
- }
886
- resetGroupPropertiesForFlags() {
887
- this.wrap(()=>{
888
- this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, null);
889
- });
890
- }
891
- async remoteConfigAsync() {
892
- await this._initPromise;
893
- if (this._remoteConfigResponsePromise) return this._remoteConfigResponsePromise;
894
- return this._remoteConfigAsync();
895
- }
896
- async flagsAsync() {
897
- let sendAnonDistinctId = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
898
- await this._initPromise;
899
- if (this._flagsResponsePromise) return this._flagsResponsePromise;
900
- return this._flagsAsync(sendAnonDistinctId);
901
- }
902
- cacheSessionReplay(source, response) {
903
- const sessionReplay = null == response ? void 0 : response.sessionRecording;
904
- if (sessionReplay) {
905
- this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);
906
- this.logMsgIfDebug(()=>console.log('PostHog Debug', `Session replay config from ${source}: `, JSON.stringify(sessionReplay)));
907
- } else if ('boolean' == typeof sessionReplay && false === sessionReplay) {
908
- this.logMsgIfDebug(()=>console.info('PostHog Debug', `Session replay config from ${source} disabled.`));
909
- this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);
910
- }
911
- }
912
- async _remoteConfigAsync() {
913
- this._remoteConfigResponsePromise = this._initPromise.then(()=>{
914
- let remoteConfig = this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig);
915
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Cached remote config: ', JSON.stringify(remoteConfig)));
916
- return super.getRemoteConfig().then((response)=>{
917
- if (response) {
918
- var _response_supportedCompression;
919
- const remoteConfigWithoutSurveys = {
920
- ...response
921
- };
922
- delete remoteConfigWithoutSurveys.surveys;
923
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Fetched remote config: ', JSON.stringify(remoteConfigWithoutSurveys)));
924
- if (false === this.disableSurveys) {
925
- const surveys = response.surveys;
926
- let hasSurveys = true;
927
- if (Array.isArray(surveys)) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Surveys fetched from remote config: ', JSON.stringify(surveys)));
928
- else {
929
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'There are no surveys.'));
930
- hasSurveys = false;
931
- }
932
- if (hasSurveys) this.setPersistedProperty(PostHogPersistedProperty.Surveys, surveys);
933
- else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);
934
- } else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);
935
- this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, remoteConfigWithoutSurveys);
936
- this.cacheSessionReplay('remote config', response);
937
- if (false === response.hasFeatureFlags) {
938
- this.setKnownFeatureFlagDetails({
939
- flags: {}
940
- });
941
- this.logMsgIfDebug(()=>console.warn('Remote config has no feature flags, will not load feature flags.'));
942
- } else if (false !== this.preloadFeatureFlags) this.reloadFeatureFlags();
943
- if (!(null == (_response_supportedCompression = response.supportedCompression) ? void 0 : _response_supportedCompression.includes(Compression.GZipJS))) this.disableCompression = true;
944
- remoteConfig = response;
945
- }
946
- return remoteConfig;
947
- });
948
- }).finally(()=>{
949
- this._remoteConfigResponsePromise = void 0;
950
- });
951
- return this._remoteConfigResponsePromise;
952
- }
953
- async _flagsAsync() {
954
- let sendAnonDistinctId = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : true;
955
- this._flagsResponsePromise = this._initPromise.then(async ()=>{
956
- var _res_quotaLimited;
957
- const distinctId = this.getDistinctId();
958
- const groups = this.props.$groups || {};
959
- const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};
960
- const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};
961
- const extraProperties = {
962
- $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : void 0
963
- };
964
- const res = await super.getFlags(distinctId, groups, personProperties, groupProperties, extraProperties);
965
- if (null == res ? void 0 : null == (_res_quotaLimited = res.quotaLimited) ? void 0 : _res_quotaLimited.includes("feature_flags")) {
966
- this.setKnownFeatureFlagDetails(null);
967
- console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
968
- return res;
969
- }
970
- if (null == res ? void 0 : res.featureFlags) {
971
- if (this.sendFeatureFlagEvent) this.flagCallReported = {};
972
- let newFeatureFlagDetails = res;
973
- if (res.errorsWhileComputingFlags) {
974
- const currentFlagDetails = this.getKnownFeatureFlagDetails();
975
- this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Cached feature flags: ', JSON.stringify(currentFlagDetails)));
976
- newFeatureFlagDetails = {
977
- ...res,
978
- flags: {
979
- ...null == currentFlagDetails ? void 0 : currentFlagDetails.flags,
980
- ...res.flags
981
- }
982
- };
983
- }
984
- this.setKnownFeatureFlagDetails(newFeatureFlagDetails);
985
- this.setPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit, true);
986
- this.cacheSessionReplay('flags', res);
987
- }
988
- return res;
989
- }).finally(()=>{
990
- this._flagsResponsePromise = void 0;
991
- });
992
- return this._flagsResponsePromise;
993
- }
994
- setKnownFeatureFlagDetails(flagsResponse) {
995
- this.wrap(()=>{
996
- this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails, flagsResponse);
997
- var _flagsResponse_flags;
998
- this._events.emit('featureflags', getFlagValuesFromFlags(null != (_flagsResponse_flags = null == flagsResponse ? void 0 : flagsResponse.flags) ? _flagsResponse_flags : {}));
999
- });
1000
- }
1001
- getKnownFeatureFlagDetails() {
1002
- const storedDetails = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);
1003
- if (!storedDetails) {
1004
- const featureFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
1005
- const featureFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1006
- if (void 0 === featureFlags && void 0 === featureFlagPayloads) return;
1007
- return createFlagsResponseFromFlagsAndPayloads(null != featureFlags ? featureFlags : {}, null != featureFlagPayloads ? featureFlagPayloads : {});
1008
- }
1009
- return normalizeFlagsResponse(storedDetails);
1010
- }
1011
- getKnownFeatureFlags() {
1012
- const featureFlagDetails = this.getKnownFeatureFlagDetails();
1013
- if (!featureFlagDetails) return;
1014
- return getFlagValuesFromFlags(featureFlagDetails.flags);
1015
- }
1016
- getKnownFeatureFlagPayloads() {
1017
- const featureFlagDetails = this.getKnownFeatureFlagDetails();
1018
- if (!featureFlagDetails) return;
1019
- return getPayloadsFromFlags(featureFlagDetails.flags);
1020
- }
1021
- getBootstrappedFeatureFlagDetails() {
1022
- const details = this.getPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails);
1023
- if (!details) return;
1024
- return details;
1025
- }
1026
- setBootstrappedFeatureFlagDetails(details) {
1027
- this.setPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails, details);
1028
- }
1029
- getBootstrappedFeatureFlags() {
1030
- const details = this.getBootstrappedFeatureFlagDetails();
1031
- if (!details) return;
1032
- return getFlagValuesFromFlags(details.flags);
1033
- }
1034
- getBootstrappedFeatureFlagPayloads() {
1035
- const details = this.getBootstrappedFeatureFlagDetails();
1036
- if (!details) return;
1037
- return getPayloadsFromFlags(details.flags);
1038
- }
1039
- getFeatureFlag(key) {
1040
- const details = this.getFeatureFlagDetails();
1041
- if (!details) return;
1042
- const featureFlag = details.flags[key];
1043
- let response = getFeatureFlagValue(featureFlag);
1044
- if (void 0 === response) response = false;
1045
- if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
1046
- var _this_getBootstrappedFeatureFlags, _this_getBootstrappedFeatureFlagPayloads, _featureFlag_metadata, _featureFlag_metadata1, _featureFlag_reason, _featureFlag_reason1;
1047
- const bootstrappedResponse = null == (_this_getBootstrappedFeatureFlags = this.getBootstrappedFeatureFlags()) ? void 0 : _this_getBootstrappedFeatureFlags[key];
1048
- const bootstrappedPayload = null == (_this_getBootstrappedFeatureFlagPayloads = this.getBootstrappedFeatureFlagPayloads()) ? void 0 : _this_getBootstrappedFeatureFlagPayloads[key];
1049
- this.flagCallReported[key] = true;
1050
- var _featureFlag_reason_description;
1051
- this.capture('$feature_flag_called', {
1052
- $feature_flag: key,
1053
- $feature_flag_response: response,
1054
- ...maybeAdd('$feature_flag_id', null == featureFlag ? void 0 : null == (_featureFlag_metadata = featureFlag.metadata) ? void 0 : _featureFlag_metadata.id),
1055
- ...maybeAdd('$feature_flag_version', null == featureFlag ? void 0 : null == (_featureFlag_metadata1 = featureFlag.metadata) ? void 0 : _featureFlag_metadata1.version),
1056
- ...maybeAdd('$feature_flag_reason', null != (_featureFlag_reason_description = null == featureFlag ? void 0 : null == (_featureFlag_reason = featureFlag.reason) ? void 0 : _featureFlag_reason.description) ? _featureFlag_reason_description : null == featureFlag ? void 0 : null == (_featureFlag_reason1 = featureFlag.reason) ? void 0 : _featureFlag_reason1.code),
1057
- ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),
1058
- ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),
1059
- $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),
1060
- ...maybeAdd('$feature_flag_request_id', details.requestId)
1061
- });
1062
- }
1063
- return response;
1064
- }
1065
- getFeatureFlagPayload(key) {
1066
- const payloads = this.getFeatureFlagPayloads();
1067
- if (!payloads) return;
1068
- const response = payloads[key];
1069
- if (void 0 === response) return null;
1070
- return response;
1071
- }
1072
- getFeatureFlagPayloads() {
1073
- var _this_getFeatureFlagDetails;
1074
- return null == (_this_getFeatureFlagDetails = this.getFeatureFlagDetails()) ? void 0 : _this_getFeatureFlagDetails.featureFlagPayloads;
1075
- }
1076
- getFeatureFlags() {
1077
- var _this_getFeatureFlagDetails;
1078
- return null == (_this_getFeatureFlagDetails = this.getFeatureFlagDetails()) ? void 0 : _this_getFeatureFlagDetails.featureFlags;
1079
- }
1080
- getFeatureFlagDetails() {
1081
- let details = this.getKnownFeatureFlagDetails();
1082
- const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
1083
- if (!overriddenFlags) return details;
1084
- details = null != details ? details : {
1085
- featureFlags: {},
1086
- featureFlagPayloads: {},
1087
- flags: {}
1088
- };
1089
- var _details_flags;
1090
- const flags = null != (_details_flags = details.flags) ? _details_flags : {};
1091
- for(const key in overriddenFlags)if (overriddenFlags[key]) flags[key] = updateFlagValue(flags[key], overriddenFlags[key]);
1092
- else delete flags[key];
1093
- const result = {
1094
- ...details,
1095
- flags
1096
- };
1097
- return normalizeFlagsResponse(result);
1098
- }
1099
- getFeatureFlagsAndPayloads() {
1100
- const flags = this.getFeatureFlags();
1101
- const payloads = this.getFeatureFlagPayloads();
1102
- return {
1103
- flags,
1104
- payloads
1105
- };
1106
- }
1107
- isFeatureEnabled(key) {
1108
- const response = this.getFeatureFlag(key);
1109
- if (void 0 === response) return;
1110
- return !!response;
1111
- }
1112
- reloadFeatureFlags(options) {
1113
- this.flagsAsync(true).then((res)=>{
1114
- var _options_cb;
1115
- null == options || null == (_options_cb = options.cb) || _options_cb.call(options, void 0, null == res ? void 0 : res.featureFlags);
1116
- }).catch((e)=>{
1117
- var _options_cb;
1118
- null == options || null == (_options_cb = options.cb) || _options_cb.call(options, e, void 0);
1119
- if (!(null == options ? void 0 : options.cb)) this.logMsgIfDebug(()=>console.log('PostHog Debug', 'Error reloading feature flags', e));
1120
- });
1121
- }
1122
- async reloadRemoteConfigAsync() {
1123
- return await this.remoteConfigAsync();
1124
- }
1125
- async reloadFeatureFlagsAsync(sendAnonDistinctId) {
1126
- var _this;
1127
- return null == (_this = await this.flagsAsync(null != sendAnonDistinctId ? sendAnonDistinctId : true)) ? void 0 : _this.featureFlags;
1128
- }
1129
- onFeatureFlags(cb) {
1130
- return this.on('featureflags', async ()=>{
1131
- const flags = this.getFeatureFlags();
1132
- if (flags) cb(flags);
1133
- });
1134
- }
1135
- onFeatureFlag(key, cb) {
1136
- return this.on('featureflags', async ()=>{
1137
- const flagResponse = this.getFeatureFlag(key);
1138
- if (void 0 !== flagResponse) cb(flagResponse);
1139
- });
1140
- }
1141
- async overrideFeatureFlag(flags) {
1142
- this.wrap(()=>{
1143
- if (null === flags) return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
1144
- return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1145
- });
1146
- }
1147
- captureException(error, additionalProperties) {
1148
- const properties = {
1149
- $exception_level: 'error',
1150
- $exception_list: [
1151
- {
1152
- type: isPlainError(error) ? error.name : 'Error',
1153
- value: isPlainError(error) ? error.message : error,
1154
- mechanism: {
1155
- handled: true,
1156
- synthetic: false
1157
- }
1158
- }
1159
- ],
1160
- ...additionalProperties
1161
- };
1162
- properties.$exception_personURL = new URL(`/project/${this.apiKey}/person/${this.getDistinctId()}`, this.host).toString();
1163
- this.capture('$exception', properties);
1164
- }
1165
- captureTraceFeedback(traceId, userFeedback) {
1166
- this.capture('$ai_feedback', {
1167
- $ai_feedback_text: userFeedback,
1168
- $ai_trace_id: String(traceId)
1169
- });
1170
- }
1171
- captureTraceMetric(traceId, metricName, metricValue) {
1172
- this.capture('$ai_metric', {
1173
- $ai_metric_name: metricName,
1174
- $ai_metric_value: String(metricValue),
1175
- $ai_trace_id: String(traceId)
1176
- });
1177
- }
1178
- constructor(apiKey, options){
1179
- var _options_disableGeoip;
1180
- const disableGeoipOption = null != (_options_disableGeoip = null == options ? void 0 : options.disableGeoip) ? _options_disableGeoip : false;
1181
- var _options_featureFlagsRequestTimeoutMs;
1182
- const featureFlagsRequestTimeoutMs = null != (_options_featureFlagsRequestTimeoutMs = null == options ? void 0 : options.featureFlagsRequestTimeoutMs) ? _options_featureFlagsRequestTimeoutMs : 10000;
1183
- super(apiKey, {
1184
- ...options,
1185
- disableGeoip: disableGeoipOption,
1186
- featureFlagsRequestTimeoutMs
1187
- }), this.flagCallReported = {}, this._sessionMaxLengthSeconds = 86400, this.sessionProps = {};
1188
- var _options_sendFeatureFlagEvent;
1189
- this.sendFeatureFlagEvent = null != (_options_sendFeatureFlagEvent = null == options ? void 0 : options.sendFeatureFlagEvent) ? _options_sendFeatureFlagEvent : true;
1190
- var _options_sessionExpirationTimeSeconds;
1191
- this._sessionExpirationTimeSeconds = null != (_options_sessionExpirationTimeSeconds = null == options ? void 0 : options.sessionExpirationTimeSeconds) ? _options_sessionExpirationTimeSeconds : 1800;
1192
- }
1193
- }
1194
- export { __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ as ErrorTracking, PostHogCore, PostHogCoreStateless, getFeatureFlagValue, logFlushError, maybeAdd };
8
+ import * as __WEBPACK_EXTERNAL_MODULE__testing_index_mjs_6f0b91da__ from "./testing/index.mjs";
9
+ export { __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ as ErrorTracking, getFeatureFlagValue, __WEBPACK_EXTERNAL_MODULE__testing_index_mjs_6f0b91da__ as testing, uuidv7 };