posthog-js-lite 3.0.0-beta.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.ts CHANGED
@@ -7,6 +7,10 @@ declare type PostHogCoreOptions = {
7
7
  flushInterval?: number;
8
8
  /** The maximum number of queued messages to be flushed as part of a single batch (must be higher than `flushAt`) */
9
9
  maxBatchSize?: number;
10
+ /** The maximum number of cached messages either in memory or on the local storage.
11
+ * Defaults to 1000, (must be higher than `flushAt`)
12
+ */
13
+ maxQueueSize?: number;
10
14
  /** If set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) */
11
15
  disabled?: boolean;
12
16
  /** If set to false the SDK will not track until the `optIn` function is called. */
@@ -32,7 +36,7 @@ declare type PostHogCoreOptions = {
32
36
  featureFlagsRequestTimeoutMs?: number;
33
37
  /** For Session Analysis how long before we expire a session (defaults to 30 mins) */
34
38
  sessionExpirationTimeSeconds?: number;
35
- /** Whether to post events to PostHog in JSON or compressed format */
39
+ /** Whether to post events to PostHog in JSON or compressed format. Defaults to 'form' */
36
40
  captureMode?: 'json' | 'form';
37
41
  disableGeoip?: boolean;
38
42
  };
@@ -130,6 +134,7 @@ declare abstract class PostHogCoreStateless {
130
134
  host: string;
131
135
  private flushAt;
132
136
  private maxBatchSize;
137
+ private maxQueueSize;
133
138
  private flushInterval;
134
139
  private flushPromise;
135
140
  private requestTimeout;
@@ -200,6 +205,9 @@ declare abstract class PostHogCoreStateless {
200
205
  */
201
206
  private flushBackground;
202
207
  flush(): Promise<any[]>;
208
+ protected getCustomHeaders(): {
209
+ [key: string]: string;
210
+ };
203
211
  private _flush;
204
212
  private fetchWithRetry;
205
213
  shutdown(shutdownTimeoutMs?: number): Promise<void>;
package/lib/index.esm.js CHANGED
@@ -955,6 +955,7 @@ class PostHogCoreStateless {
955
955
  this.host = removeTrailingSlash(options?.host || 'https://app.posthog.com');
956
956
  this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
957
957
  this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
958
+ this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
958
959
  this.flushInterval = options?.flushInterval ?? 10000;
959
960
  this.captureMode = options?.captureMode || 'form';
960
961
  // If enable is explicitly set to false we override the optout
@@ -1103,7 +1104,7 @@ class PostHogCoreStateless {
1103
1104
  const url = `${this.host}/decide/?v=3`;
1104
1105
  const fetchOptions = {
1105
1106
  method: 'POST',
1106
- headers: { 'Content-Type': 'application/json' },
1107
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1107
1108
  body: JSON.stringify({
1108
1109
  token: this.apiKey,
1109
1110
  distinct_id: distinctId,
@@ -1148,14 +1149,11 @@ class PostHogCoreStateless {
1148
1149
  if (response === undefined) {
1149
1150
  return null;
1150
1151
  }
1151
- return this._parsePayload(response);
1152
+ return response;
1152
1153
  }
1153
1154
  async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1154
1155
  await this._initPromise;
1155
1156
  const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip)).payloads;
1156
- if (payloads) {
1157
- return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1158
- }
1159
1157
  return payloads;
1160
1158
  }
1161
1159
  _parsePayload(response) {
@@ -1179,9 +1177,13 @@ class PostHogCoreStateless {
1179
1177
  const decideResponse = await this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload);
1180
1178
  const flags = decideResponse?.featureFlags;
1181
1179
  const payloads = decideResponse?.featureFlagPayloads;
1180
+ let parsedPayloads = payloads;
1181
+ if (payloads) {
1182
+ parsedPayloads = Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1183
+ }
1182
1184
  return {
1183
1185
  flags,
1184
- payloads,
1186
+ payloads: parsedPayloads,
1185
1187
  };
1186
1188
  }
1187
1189
  /***
@@ -1213,6 +1215,10 @@ class PostHogCoreStateless {
1213
1215
  delete message.distinctId;
1214
1216
  }
1215
1217
  const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1218
+ if (queue.length >= this.maxQueueSize) {
1219
+ queue.shift();
1220
+ console.info('Queue is full, the oldest event is dropped.');
1221
+ }
1216
1222
  queue.push({ message });
1217
1223
  this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1218
1224
  this._events.emit(type, message);
@@ -1247,6 +1253,18 @@ class PostHogCoreStateless {
1247
1253
  }
1248
1254
  return this.flushPromise;
1249
1255
  }
1256
+ getCustomHeaders() {
1257
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1258
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1259
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1260
+ // but browsers such as Chrome and Safari have not caught up.
1261
+ const customUserAgent = this.getCustomUserAgent();
1262
+ const headers = {};
1263
+ if (customUserAgent && customUserAgent !== '') {
1264
+ headers['User-Agent'] = customUserAgent;
1265
+ }
1266
+ return headers;
1267
+ }
1250
1268
  async _flush() {
1251
1269
  this.clearFlushTimer();
1252
1270
  await this._initPromise;
@@ -1265,11 +1283,6 @@ class PostHogCoreStateless {
1265
1283
  batch: messages,
1266
1284
  sent_at: currentISOTime(),
1267
1285
  };
1268
- // Don't set the user agent if we're not on a browser. The latest spec allows
1269
- // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1270
- // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1271
- // but browsers such as Chrome and Safari have not caught up.
1272
- this.getCustomUserAgent();
1273
1286
  const payload = JSON.stringify(data);
1274
1287
  const url = this.captureMode === 'form'
1275
1288
  ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
@@ -1279,12 +1292,12 @@ class PostHogCoreStateless {
1279
1292
  method: 'POST',
1280
1293
  mode: 'no-cors',
1281
1294
  credentials: 'omit',
1282
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1295
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' },
1283
1296
  body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
1284
1297
  }
1285
1298
  : {
1286
1299
  method: 'POST',
1287
- headers: { 'Content-Type': 'application/json' },
1300
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1288
1301
  body: payload,
1289
1302
  };
1290
1303
  try {
@@ -1688,7 +1701,7 @@ class PostHogCore extends PostHogCoreStateless {
1688
1701
  newFeatureFlagPayloads = { ...currentFlagPayloads, ...res.featureFlagPayloads };
1689
1702
  }
1690
1703
  this.setKnownFeatureFlags(newFeatureFlags);
1691
- this.setKnownFeatureFlagPayloads(newFeatureFlagPayloads);
1704
+ this.setKnownFeatureFlagPayloads(Object.fromEntries(Object.entries(newFeatureFlagPayloads || {}).map(([k, v]) => [k, this._parsePayload(v)])));
1692
1705
  }
1693
1706
  return res;
1694
1707
  });
@@ -1741,13 +1754,10 @@ class PostHogCore extends PostHogCoreStateless {
1741
1754
  if (response === undefined) {
1742
1755
  return null;
1743
1756
  }
1744
- return this._parsePayload(response);
1757
+ return response;
1745
1758
  }
1746
1759
  getFeatureFlagPayloads() {
1747
1760
  const payloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);
1748
- if (payloads) {
1749
- return Object.fromEntries(Object.entries(payloads).map(([k, v]) => [k, this._parsePayload(v)]));
1750
- }
1751
1761
  return payloads;
1752
1762
  }
1753
1763
  getFeatureFlags() {
@@ -1826,7 +1836,7 @@ class PostHogCore extends PostHogCoreStateless {
1826
1836
  }
1827
1837
  }
1828
1838
 
1829
- var version = "3.0.0-beta.2";
1839
+ var version = "3.0.1";
1830
1840
 
1831
1841
  function getContext(window) {
1832
1842
  let context = {};