posthog-node 5.0.0-alpha.1 → 5.1.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/lib/edge/index.cjs +3455 -0
  3. package/lib/edge/index.cjs.map +1 -0
  4. package/lib/edge/index.mjs +3429 -0
  5. package/lib/edge/index.mjs.map +1 -0
  6. package/lib/index.d.ts +938 -810
  7. package/lib/{index.cjs.js → node/index.cjs} +2910 -3107
  8. package/lib/node/index.cjs.map +1 -0
  9. package/lib/{index.esm.js → node/index.mjs} +2911 -3105
  10. package/lib/node/index.mjs.map +1 -0
  11. package/package.json +33 -6
  12. package/index.ts +0 -3
  13. package/lib/index.cjs.js.map +0 -1
  14. package/lib/index.esm.js.map +0 -1
  15. package/lib/posthog-core/src/eventemitter.d.ts +0 -8
  16. package/lib/posthog-core/src/featureFlagUtils.d.ts +0 -34
  17. package/lib/posthog-core/src/index.d.ts +0 -242
  18. package/lib/posthog-core/src/lz-string.d.ts +0 -8
  19. package/lib/posthog-core/src/storage-memory.d.ts +0 -6
  20. package/lib/posthog-core/src/types.d.ts +0 -422
  21. package/lib/posthog-core/src/utils.d.ts +0 -19
  22. package/lib/posthog-core/src/vendor/uuidv7.d.ts +0 -179
  23. package/lib/posthog-node/index.d.ts +0 -3
  24. package/lib/posthog-node/src/crypto-helpers.d.ts +0 -3
  25. package/lib/posthog-node/src/crypto.d.ts +0 -2
  26. package/lib/posthog-node/src/error-tracking.d.ts +0 -12
  27. package/lib/posthog-node/src/extensions/error-tracking/autocapture.d.ts +0 -3
  28. package/lib/posthog-node/src/extensions/error-tracking/context-lines.d.ts +0 -6
  29. package/lib/posthog-node/src/extensions/error-tracking/error-conversion.d.ts +0 -2
  30. package/lib/posthog-node/src/extensions/error-tracking/reduceable-cache.d.ts +0 -12
  31. package/lib/posthog-node/src/extensions/error-tracking/stack-trace.d.ts +0 -15
  32. package/lib/posthog-node/src/extensions/error-tracking/type-checking.d.ts +0 -7
  33. package/lib/posthog-node/src/extensions/error-tracking/types.d.ts +0 -57
  34. package/lib/posthog-node/src/extensions/express.d.ts +0 -17
  35. package/lib/posthog-node/src/extensions/sentry-integration.d.ts +0 -51
  36. package/lib/posthog-node/src/feature-flags.d.ts +0 -84
  37. package/lib/posthog-node/src/lazy.d.ts +0 -23
  38. package/lib/posthog-node/src/posthog-node.d.ts +0 -91
  39. package/lib/posthog-node/src/types.d.ts +0 -203
  40. package/lib/posthog-node/test/test-utils.d.ts +0 -17
  41. package/src/crypto-helpers.ts +0 -36
  42. package/src/crypto.ts +0 -22
  43. package/src/error-tracking.ts +0 -67
  44. package/src/extensions/error-tracking/autocapture.ts +0 -65
  45. package/src/extensions/error-tracking/context-lines.ts +0 -425
  46. package/src/extensions/error-tracking/error-conversion.ts +0 -262
  47. package/src/extensions/error-tracking/reduceable-cache.ts +0 -39
  48. package/src/extensions/error-tracking/stack-trace.ts +0 -269
  49. package/src/extensions/error-tracking/type-checking.ts +0 -40
  50. package/src/extensions/error-tracking/types.ts +0 -65
  51. package/src/extensions/express.ts +0 -37
  52. package/src/extensions/sentry-integration.ts +0 -196
  53. package/src/feature-flags.ts +0 -863
  54. package/src/lazy.ts +0 -55
  55. package/src/posthog-node.ts +0 -567
  56. package/src/types.ts +0 -231
  57. package/test/crypto.spec.ts +0 -36
  58. package/test/extensions/error-conversion.spec.ts +0 -44
  59. package/test/extensions/sentry-integration.spec.ts +0 -162
  60. package/test/feature-flags.decide.spec.ts +0 -378
  61. package/test/feature-flags.spec.ts +0 -4681
  62. package/test/lazy.spec.ts +0 -71
  63. package/test/posthog-node.spec.ts +0 -1341
  64. package/test/test-utils.ts +0 -106
  65. package/tsconfig.json +0 -7
@@ -0,0 +1,3429 @@
1
+ /**
2
+ * @file Adapted from [posthog-js](https://github.com/PostHog/posthog-js/blob/8157df935a4d0e71d2fefef7127aa85ee51c82d1/src/extensions/sentry-integration.ts) with modifications for the Node SDK.
3
+ */
4
+ /**
5
+ * Integrate Sentry with PostHog. This will add a direct link to the person in Sentry, and an $exception event in PostHog.
6
+ *
7
+ * ### Usage
8
+ *
9
+ * Sentry.init({
10
+ * dsn: 'https://example',
11
+ * integrations: [
12
+ * new PostHogSentryIntegration(posthog)
13
+ * ]
14
+ * })
15
+ *
16
+ * Sentry.setTag(PostHogSentryIntegration.POSTHOG_ID_TAG, 'some distinct id');
17
+ *
18
+ * @param {Object} [posthog] The posthog object
19
+ * @param {string} [organization] Optional: The Sentry organization, used to send a direct link from PostHog to Sentry
20
+ * @param {Number} [projectId] Optional: The Sentry project id, used to send a direct link from PostHog to Sentry
21
+ * @param {string} [prefix] Optional: Url of a self-hosted sentry instance (default: https://sentry.io/organizations/)
22
+ * @param {SeverityLevel[] | '*'} [severityAllowList] Optional: send events matching the provided levels. Use '*' to send all events (default: ['error'])
23
+ */
24
+ const NAME = 'posthog-node';
25
+ function createEventProcessor(_posthog, {
26
+ organization,
27
+ projectId,
28
+ prefix,
29
+ severityAllowList = ['error']
30
+ } = {}) {
31
+ return event => {
32
+ const shouldProcessLevel = severityAllowList === '*' || severityAllowList.includes(event.level);
33
+ if (!shouldProcessLevel) {
34
+ return event;
35
+ }
36
+ if (!event.tags) {
37
+ event.tags = {};
38
+ }
39
+ // Get the PostHog user ID from a specific tag, which users can set on their Sentry scope as they need.
40
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
41
+ if (userId === undefined) {
42
+ // If we can't find a user ID, don't bother linking the event. We won't be able to send anything meaningful to PostHog without it.
43
+ return event;
44
+ }
45
+ const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';
46
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
47
+ event.tags['PostHog Person URL'] = personUrl;
48
+ const exceptions = event.exception?.values || [];
49
+ const exceptionList = exceptions.map(exception => ({
50
+ ...exception,
51
+ stacktrace: exception.stacktrace ? {
52
+ ...exception.stacktrace,
53
+ type: 'raw',
54
+ frames: (exception.stacktrace.frames || []).map(frame => {
55
+ return {
56
+ ...frame,
57
+ platform: 'node:javascript'
58
+ };
59
+ })
60
+ } : undefined
61
+ }));
62
+ const properties = {
63
+ // PostHog Exception Properties,
64
+ $exception_message: exceptions[0]?.value || event.message,
65
+ $exception_type: exceptions[0]?.type,
66
+ $exception_personURL: personUrl,
67
+ $exception_level: event.level,
68
+ $exception_list: exceptionList,
69
+ // Sentry Exception Properties
70
+ $sentry_event_id: event.event_id,
71
+ $sentry_exception: event.exception,
72
+ $sentry_exception_message: exceptions[0]?.value || event.message,
73
+ $sentry_exception_type: exceptions[0]?.type,
74
+ $sentry_tags: event.tags
75
+ };
76
+ if (organization && projectId) {
77
+ properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;
78
+ }
79
+ _posthog.capture({
80
+ event: '$exception',
81
+ distinctId: userId,
82
+ properties
83
+ });
84
+ return event;
85
+ };
86
+ }
87
+ // V8 integration - function based
88
+ function sentryIntegration(_posthog, options) {
89
+ const processor = createEventProcessor(_posthog, options);
90
+ return {
91
+ name: NAME,
92
+ processEvent(event) {
93
+ return processor(event);
94
+ }
95
+ };
96
+ }
97
+ // V7 integration - class based
98
+ class PostHogSentryIntegration {
99
+ constructor(_posthog, organization, prefix, severityAllowList) {
100
+ this.name = NAME;
101
+ // setupOnce gets called by Sentry when it intializes the plugin
102
+ this.name = NAME;
103
+ this.setupOnce = function (addGlobalEventProcessor, getCurrentHub) {
104
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
105
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
106
+ organization,
107
+ projectId,
108
+ prefix,
109
+ severityAllowList
110
+ }));
111
+ };
112
+ }
113
+ }
114
+ PostHogSentryIntegration.POSTHOG_ID_TAG = 'posthog_distinct_id';
115
+
116
+ // vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts
117
+ // https://github.com/LiosK/uuidv7#license
118
+ /**
119
+ * uuidv7: An experimental implementation of the proposed UUID Version 7
120
+ *
121
+ * @license Apache-2.0
122
+ * @copyright 2021-2023 LiosK
123
+ * @packageDocumentation
124
+ */
125
+ const DIGITS = "0123456789abcdef";
126
+ /** Represents a UUID as a 16-byte byte array. */
127
+ class UUID {
128
+ /** @param bytes - The 16-byte byte array representation. */
129
+ constructor(bytes) {
130
+ this.bytes = bytes;
131
+ }
132
+ /**
133
+ * Creates an object from the internal representation, a 16-byte byte array
134
+ * containing the binary UUID representation in the big-endian byte order.
135
+ *
136
+ * This method does NOT shallow-copy the argument, and thus the created object
137
+ * holds the reference to the underlying buffer.
138
+ *
139
+ * @throws TypeError if the length of the argument is not 16.
140
+ */
141
+ static ofInner(bytes) {
142
+ if (bytes.length !== 16) {
143
+ throw new TypeError("not 128-bit length");
144
+ }
145
+ else {
146
+ return new UUID(bytes);
147
+ }
148
+ }
149
+ /**
150
+ * Builds a byte array from UUIDv7 field values.
151
+ *
152
+ * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
153
+ * @param randA - A 12-bit `rand_a` field value.
154
+ * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
155
+ * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
156
+ * @throws RangeError if any field value is out of the specified range.
157
+ */
158
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
159
+ if (!Number.isInteger(unixTsMs) ||
160
+ !Number.isInteger(randA) ||
161
+ !Number.isInteger(randBHi) ||
162
+ !Number.isInteger(randBLo) ||
163
+ unixTsMs < 0 ||
164
+ randA < 0 ||
165
+ randBHi < 0 ||
166
+ randBLo < 0 ||
167
+ unixTsMs > 281474976710655 ||
168
+ randA > 0xfff ||
169
+ randBHi > 1073741823 ||
170
+ randBLo > 4294967295) {
171
+ throw new RangeError("invalid field value");
172
+ }
173
+ const bytes = new Uint8Array(16);
174
+ bytes[0] = unixTsMs / 2 ** 40;
175
+ bytes[1] = unixTsMs / 2 ** 32;
176
+ bytes[2] = unixTsMs / 2 ** 24;
177
+ bytes[3] = unixTsMs / 2 ** 16;
178
+ bytes[4] = unixTsMs / 2 ** 8;
179
+ bytes[5] = unixTsMs;
180
+ bytes[6] = 0x70 | (randA >>> 8);
181
+ bytes[7] = randA;
182
+ bytes[8] = 0x80 | (randBHi >>> 24);
183
+ bytes[9] = randBHi >>> 16;
184
+ bytes[10] = randBHi >>> 8;
185
+ bytes[11] = randBHi;
186
+ bytes[12] = randBLo >>> 24;
187
+ bytes[13] = randBLo >>> 16;
188
+ bytes[14] = randBLo >>> 8;
189
+ bytes[15] = randBLo;
190
+ return new UUID(bytes);
191
+ }
192
+ /**
193
+ * Builds a byte array from a string representation.
194
+ *
195
+ * This method accepts the following formats:
196
+ *
197
+ * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
198
+ * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
199
+ * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
200
+ * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
201
+ *
202
+ * Leading and trailing whitespaces represents an error.
203
+ *
204
+ * @throws SyntaxError if the argument could not parse as a valid UUID string.
205
+ */
206
+ static parse(uuid) {
207
+ let hex = undefined;
208
+ switch (uuid.length) {
209
+ case 32:
210
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
211
+ break;
212
+ case 36:
213
+ hex =
214
+ /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
215
+ .exec(uuid)
216
+ ?.slice(1, 6)
217
+ .join("");
218
+ break;
219
+ case 38:
220
+ hex =
221
+ /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
222
+ .exec(uuid)
223
+ ?.slice(1, 6)
224
+ .join("");
225
+ break;
226
+ case 45:
227
+ hex =
228
+ /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
229
+ .exec(uuid)
230
+ ?.slice(1, 6)
231
+ .join("");
232
+ break;
233
+ }
234
+ if (hex) {
235
+ const inner = new Uint8Array(16);
236
+ for (let i = 0; i < 16; i += 4) {
237
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
238
+ inner[i + 0] = n >>> 24;
239
+ inner[i + 1] = n >>> 16;
240
+ inner[i + 2] = n >>> 8;
241
+ inner[i + 3] = n;
242
+ }
243
+ return new UUID(inner);
244
+ }
245
+ else {
246
+ throw new SyntaxError("could not parse UUID string");
247
+ }
248
+ }
249
+ /**
250
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
251
+ * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
252
+ */
253
+ toString() {
254
+ let text = "";
255
+ for (let i = 0; i < this.bytes.length; i++) {
256
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
257
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
258
+ if (i === 3 || i === 5 || i === 7 || i === 9) {
259
+ text += "-";
260
+ }
261
+ }
262
+ return text;
263
+ }
264
+ /**
265
+ * @returns The 32-digit hexadecimal representation without hyphens
266
+ * (`0189dcd553117d408db09496a2eef37b`).
267
+ */
268
+ toHex() {
269
+ let text = "";
270
+ for (let i = 0; i < this.bytes.length; i++) {
271
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
272
+ text += DIGITS.charAt(this.bytes[i] & 0xf);
273
+ }
274
+ return text;
275
+ }
276
+ /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
277
+ toJSON() {
278
+ return this.toString();
279
+ }
280
+ /**
281
+ * Reports the variant field value of the UUID or, if appropriate, "NIL" or
282
+ * "MAX".
283
+ *
284
+ * For convenience, this method reports "NIL" or "MAX" if `this` represents
285
+ * the Nil or Max UUID, although the Nil and Max UUIDs are technically
286
+ * subsumed under the variants `0b0` and `0b111`, respectively.
287
+ */
288
+ getVariant() {
289
+ const n = this.bytes[8] >>> 4;
290
+ if (n < 0) {
291
+ throw new Error("unreachable");
292
+ }
293
+ else if (n <= 0b0111) {
294
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
295
+ }
296
+ else if (n <= 0b1011) {
297
+ return "VAR_10";
298
+ }
299
+ else if (n <= 0b1101) {
300
+ return "VAR_110";
301
+ }
302
+ else if (n <= 0b1111) {
303
+ return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
304
+ }
305
+ else {
306
+ throw new Error("unreachable");
307
+ }
308
+ }
309
+ /**
310
+ * Returns the version field value of the UUID or `undefined` if the UUID does
311
+ * not have the variant field value of `0b10`.
312
+ */
313
+ getVersion() {
314
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
315
+ }
316
+ /** Creates an object from `this`. */
317
+ clone() {
318
+ return new UUID(this.bytes.slice(0));
319
+ }
320
+ /** Returns true if `this` is equivalent to `other`. */
321
+ equals(other) {
322
+ return this.compareTo(other) === 0;
323
+ }
324
+ /**
325
+ * Returns a negative integer, zero, or positive integer if `this` is less
326
+ * than, equal to, or greater than `other`, respectively.
327
+ */
328
+ compareTo(other) {
329
+ for (let i = 0; i < 16; i++) {
330
+ const diff = this.bytes[i] - other.bytes[i];
331
+ if (diff !== 0) {
332
+ return Math.sign(diff);
333
+ }
334
+ }
335
+ return 0;
336
+ }
337
+ }
338
+ /**
339
+ * Encapsulates the monotonic counter state.
340
+ *
341
+ * This class provides APIs to utilize a separate counter state from that of the
342
+ * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
343
+ * the default {@link generate} method, this class has {@link generateOrAbort}
344
+ * that is useful to absolutely guarantee the monotonically increasing order of
345
+ * generated UUIDs. See their respective documentation for details.
346
+ */
347
+ class V7Generator {
348
+ /**
349
+ * Creates a generator object with the default random number generator, or
350
+ * with the specified one if passed as an argument. The specified random
351
+ * number generator should be cryptographically strong and securely seeded.
352
+ */
353
+ constructor(randomNumberGenerator) {
354
+ this.timestamp = 0;
355
+ this.counter = 0;
356
+ this.random = randomNumberGenerator ?? getDefaultRandom();
357
+ }
358
+ /**
359
+ * Generates a new UUIDv7 object from the current timestamp, or resets the
360
+ * generator upon significant timestamp rollback.
361
+ *
362
+ * This method returns a monotonically increasing UUID by reusing the previous
363
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
364
+ * preceding UUID's. However, when such a clock rollback is considered
365
+ * significant (i.e., by more than ten seconds), this method resets the
366
+ * generator and returns a new UUID based on the given timestamp, breaking the
367
+ * increasing order of UUIDs.
368
+ *
369
+ * See {@link generateOrAbort} for the other mode of generation and
370
+ * {@link generateOrResetCore} for the low-level primitive.
371
+ */
372
+ generate() {
373
+ return this.generateOrResetCore(Date.now(), 10000);
374
+ }
375
+ /**
376
+ * Generates a new UUIDv7 object from the current timestamp, or returns
377
+ * `undefined` upon significant timestamp rollback.
378
+ *
379
+ * This method returns a monotonically increasing UUID by reusing the previous
380
+ * timestamp even if the up-to-date timestamp is smaller than the immediately
381
+ * preceding UUID's. However, when such a clock rollback is considered
382
+ * significant (i.e., by more than ten seconds), this method aborts and
383
+ * returns `undefined` immediately.
384
+ *
385
+ * See {@link generate} for the other mode of generation and
386
+ * {@link generateOrAbortCore} for the low-level primitive.
387
+ */
388
+ generateOrAbort() {
389
+ return this.generateOrAbortCore(Date.now(), 10000);
390
+ }
391
+ /**
392
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
393
+ * generator upon significant timestamp rollback.
394
+ *
395
+ * This method is equivalent to {@link generate} except that it takes a custom
396
+ * timestamp and clock rollback allowance.
397
+ *
398
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
399
+ * considered significant. A suggested value is `10_000` (milliseconds).
400
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
401
+ */
402
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
403
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
404
+ if (value === undefined) {
405
+ // reset state and resume
406
+ this.timestamp = 0;
407
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
408
+ }
409
+ return value;
410
+ }
411
+ /**
412
+ * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
413
+ * `undefined` upon significant timestamp rollback.
414
+ *
415
+ * This method is equivalent to {@link generateOrAbort} except that it takes a
416
+ * custom timestamp and clock rollback allowance.
417
+ *
418
+ * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
419
+ * considered significant. A suggested value is `10_000` (milliseconds).
420
+ * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
421
+ */
422
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
423
+ const MAX_COUNTER = 4398046511103;
424
+ if (!Number.isInteger(unixTsMs) ||
425
+ unixTsMs < 1 ||
426
+ unixTsMs > 281474976710655) {
427
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
428
+ }
429
+ else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
430
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
431
+ }
432
+ if (unixTsMs > this.timestamp) {
433
+ this.timestamp = unixTsMs;
434
+ this.resetCounter();
435
+ }
436
+ else if (unixTsMs + rollbackAllowance >= this.timestamp) {
437
+ // go on with previous timestamp if new one is not much smaller
438
+ this.counter++;
439
+ if (this.counter > MAX_COUNTER) {
440
+ // increment timestamp at counter overflow
441
+ this.timestamp++;
442
+ this.resetCounter();
443
+ }
444
+ }
445
+ else {
446
+ // abort if clock went backwards to unbearable extent
447
+ return undefined;
448
+ }
449
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
450
+ }
451
+ /** Initializes the counter at a 42-bit random integer. */
452
+ resetCounter() {
453
+ this.counter =
454
+ this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
455
+ }
456
+ /**
457
+ * Generates a new UUIDv4 object utilizing the random number generator inside.
458
+ *
459
+ * @internal
460
+ */
461
+ generateV4() {
462
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
463
+ bytes[6] = 0x40 | (bytes[6] >>> 4);
464
+ bytes[8] = 0x80 | (bytes[8] >>> 2);
465
+ return UUID.ofInner(bytes);
466
+ }
467
+ }
468
+ /** A global flag to force use of cryptographically strong RNG. */
469
+ // declare const UUIDV7_DENY_WEAK_RNG: boolean;
470
+ /** Returns the default random number generator available in the environment. */
471
+ const getDefaultRandom = () => {
472
+ // fix: crypto isn't available in react-native, always use Math.random
473
+ // // detect Web Crypto API
474
+ // if (
475
+ // typeof crypto !== "undefined" &&
476
+ // typeof crypto.getRandomValues !== "undefined"
477
+ // ) {
478
+ // return new BufferedCryptoRandom();
479
+ // } else {
480
+ // // fall back on Math.random() unless the flag is set to true
481
+ // if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
482
+ // throw new Error("no cryptographically strong RNG available");
483
+ // }
484
+ // return {
485
+ // nextUint32: (): number =>
486
+ // Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 +
487
+ // Math.trunc(Math.random() * 0x1_0000),
488
+ // };
489
+ // }
490
+ return {
491
+ nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
492
+ Math.trunc(Math.random() * 65536),
493
+ };
494
+ };
495
+ // /**
496
+ // * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
497
+ // * buffer by default to avoid both unbearable throughput decline in some
498
+ // * environments and the waste of time and space for unused values.
499
+ // */
500
+ // class BufferedCryptoRandom {
501
+ // private readonly buffer = new Uint32Array(8);
502
+ // private cursor = 0xffff;
503
+ // nextUint32(): number {
504
+ // if (this.cursor >= this.buffer.length) {
505
+ // crypto.getRandomValues(this.buffer);
506
+ // this.cursor = 0;
507
+ // }
508
+ // return this.buffer[this.cursor++];
509
+ // }
510
+ // }
511
+ let defaultGenerator;
512
+ /**
513
+ * Generates a UUIDv7 string.
514
+ *
515
+ * @returns The 8-4-4-4-12 canonical hexadecimal string representation
516
+ * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
517
+ */
518
+ const uuidv7 = () => uuidv7obj().toString();
519
+ /** Generates a UUIDv7 object. */
520
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
521
+
522
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
523
+ // Licensed under the MIT License
524
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
525
+ let calledFatalError = false;
526
+ return Object.assign(error => {
527
+ // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not
528
+ // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust
529
+ // exit behaviour of the SDK accordingly:
530
+ // - If other listeners are attached, do not exit.
531
+ // - If the only listener attached is ours, exit.
532
+ const userProvidedListenersCount = global.process.listeners('uncaughtException').filter(listener => {
533
+ // There are 2 listeners we ignore:
534
+ return (
535
+ // as soon as we're using domains this listener is attached by node itself
536
+ listener.name !== 'domainUncaughtExceptionClear' &&
537
+ // the handler we register in this integration
538
+ listener._posthogErrorHandler !== true
539
+ );
540
+ }).length;
541
+ const processWouldExit = userProvidedListenersCount === 0;
542
+ captureFn(error, {
543
+ mechanism: {
544
+ type: 'onuncaughtexception',
545
+ handled: false
546
+ }
547
+ });
548
+ if (!calledFatalError && processWouldExit) {
549
+ calledFatalError = true;
550
+ onFatalFn();
551
+ }
552
+ }, {
553
+ _posthogErrorHandler: true
554
+ });
555
+ }
556
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
557
+ global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
558
+ }
559
+ function addUnhandledRejectionListener(captureFn) {
560
+ global.process.on('unhandledRejection', reason => {
561
+ captureFn(reason, {
562
+ mechanism: {
563
+ type: 'onunhandledrejection',
564
+ handled: false
565
+ }
566
+ });
567
+ });
568
+ }
569
+
570
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
571
+ // Licensed under the MIT License
572
+ let parsedStackResults;
573
+ let lastKeysCount;
574
+ let cachedFilenameChunkIds;
575
+ function getFilenameToChunkIdMap(stackParser) {
576
+ const chunkIdMap = globalThis._posthogChunkIds;
577
+ if (!chunkIdMap) {
578
+ console.error('No chunk id map found');
579
+ return {};
580
+ }
581
+ const chunkIdKeys = Object.keys(chunkIdMap);
582
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) {
583
+ return cachedFilenameChunkIds;
584
+ }
585
+ lastKeysCount = chunkIdKeys.length;
586
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
587
+ if (!parsedStackResults) {
588
+ parsedStackResults = {};
589
+ }
590
+ const result = parsedStackResults[stackKey];
591
+ if (result) {
592
+ acc[result[0]] = result[1];
593
+ } else {
594
+ const parsedStack = stackParser(stackKey);
595
+ for (let i = parsedStack.length - 1; i >= 0; i--) {
596
+ const stackFrame = parsedStack[i];
597
+ const filename = stackFrame?.filename;
598
+ const chunkId = chunkIdMap[stackKey];
599
+ if (filename && chunkId) {
600
+ acc[filename] = chunkId;
601
+ parsedStackResults[stackKey] = [filename, chunkId];
602
+ break;
603
+ }
604
+ }
605
+ }
606
+ return acc;
607
+ }, {});
608
+ return cachedFilenameChunkIds;
609
+ }
610
+
611
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
612
+ // Licensed under the MIT License
613
+ function isEvent(candidate) {
614
+ return typeof Event !== 'undefined' && isInstanceOf(candidate, Event);
615
+ }
616
+ function isPlainObject(candidate) {
617
+ return isBuiltin(candidate, 'Object');
618
+ }
619
+ function isError(candidate) {
620
+ switch (Object.prototype.toString.call(candidate)) {
621
+ case '[object Error]':
622
+ case '[object Exception]':
623
+ case '[object DOMException]':
624
+ case '[object WebAssembly.Exception]':
625
+ return true;
626
+ default:
627
+ return isInstanceOf(candidate, Error);
628
+ }
629
+ }
630
+ function isInstanceOf(candidate, base) {
631
+ try {
632
+ return candidate instanceof base;
633
+ } catch {
634
+ return false;
635
+ }
636
+ }
637
+ function isErrorEvent(event) {
638
+ return isBuiltin(event, 'ErrorEvent');
639
+ }
640
+ function isBuiltin(candidate, className) {
641
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
642
+ }
643
+
644
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
645
+ async function propertiesFromUnknownInput(stackParser, frameModifiers, input, hint) {
646
+ const providedMechanism = hint && hint.mechanism;
647
+ const mechanism = providedMechanism || {
648
+ handled: true,
649
+ type: 'generic'
650
+ };
651
+ const errorList = getErrorList(mechanism, input, hint);
652
+ const exceptionList = await Promise.all(errorList.map(async error => {
653
+ const exception = await exceptionFromError(stackParser, frameModifiers, error);
654
+ exception.value = exception.value || '';
655
+ exception.type = exception.type || 'Error';
656
+ exception.mechanism = mechanism;
657
+ return exception;
658
+ }));
659
+ const properties = {
660
+ $exception_list: exceptionList
661
+ };
662
+ return properties;
663
+ }
664
+ // Flatten error causes into a list of errors
665
+ // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
666
+ function getErrorList(mechanism, input, hint) {
667
+ const error = getError(mechanism, input, hint);
668
+ if (error.cause) {
669
+ return [error, ...getErrorList(mechanism, error.cause, hint)];
670
+ }
671
+ return [error];
672
+ }
673
+ function getError(mechanism, exception, hint) {
674
+ if (isError(exception)) {
675
+ return exception;
676
+ }
677
+ mechanism.synthetic = true;
678
+ if (isPlainObject(exception)) {
679
+ const errorFromProp = getErrorPropertyFromObject(exception);
680
+ if (errorFromProp) {
681
+ return errorFromProp;
682
+ }
683
+ const message = getMessageForObject(exception);
684
+ const ex = hint?.syntheticException || new Error(message);
685
+ ex.message = message;
686
+ return ex;
687
+ }
688
+ // This handles when someone does: `throw "something awesome";`
689
+ // We use synthesized Error here so we can extract a (rough) stack trace.
690
+ const ex = hint?.syntheticException || new Error(exception);
691
+ ex.message = `${exception}`;
692
+ return ex;
693
+ }
694
+ /** If a plain object has a property that is an `Error`, return this error. */
695
+ function getErrorPropertyFromObject(obj) {
696
+ for (const prop in obj) {
697
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
698
+ const value = obj[prop];
699
+ if (isError(value)) {
700
+ return value;
701
+ }
702
+ }
703
+ }
704
+ return undefined;
705
+ }
706
+ function getMessageForObject(exception) {
707
+ if ('name' in exception && typeof exception.name === 'string') {
708
+ let message = `'${exception.name}' captured as exception`;
709
+ if ('message' in exception && typeof exception.message === 'string') {
710
+ message += ` with message '${exception.message}'`;
711
+ }
712
+ return message;
713
+ } else if ('message' in exception && typeof exception.message === 'string') {
714
+ return exception.message;
715
+ }
716
+ const keys = extractExceptionKeysForMessage(exception);
717
+ // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before
718
+ // We still want to try to get a decent message for these cases
719
+ if (isErrorEvent(exception)) {
720
+ return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
721
+ }
722
+ const className = getObjectClassName(exception);
723
+ return `${className && className !== 'Object' ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;
724
+ }
725
+ function getObjectClassName(obj) {
726
+ try {
727
+ const prototype = Object.getPrototypeOf(obj);
728
+ return prototype ? prototype.constructor.name : undefined;
729
+ } catch (e) {
730
+ // ignore errors here
731
+ }
732
+ }
733
+ /**
734
+ * Given any captured exception, extract its keys and create a sorted
735
+ * and truncated list that will be used inside the event message.
736
+ * eg. `Non-error exception captured with keys: foo, bar, baz`
737
+ */
738
+ function extractExceptionKeysForMessage(exception, maxLength = 40) {
739
+ const keys = Object.keys(convertToPlainObject(exception));
740
+ keys.sort();
741
+ const firstKey = keys[0];
742
+ if (!firstKey) {
743
+ return '[object has no keys]';
744
+ }
745
+ if (firstKey.length >= maxLength) {
746
+ return truncate(firstKey, maxLength);
747
+ }
748
+ for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
749
+ const serialized = keys.slice(0, includedKeys).join(', ');
750
+ if (serialized.length > maxLength) {
751
+ continue;
752
+ }
753
+ if (includedKeys === keys.length) {
754
+ return serialized;
755
+ }
756
+ return truncate(serialized, maxLength);
757
+ }
758
+ return '';
759
+ }
760
+ function truncate(str, max = 0) {
761
+ if (typeof str !== 'string' || max === 0) {
762
+ return str;
763
+ }
764
+ return str.length <= max ? str : `${str.slice(0, max)}...`;
765
+ }
766
+ /**
767
+ * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
768
+ * non-enumerable properties attached.
769
+ *
770
+ * @param value Initial source that we have to transform in order for it to be usable by the serializer
771
+ * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
772
+ * an Error.
773
+ */
774
+ function convertToPlainObject(value) {
775
+ if (isError(value)) {
776
+ return {
777
+ message: value.message,
778
+ name: value.name,
779
+ stack: value.stack,
780
+ ...getOwnProperties(value)
781
+ };
782
+ } else if (isEvent(value)) {
783
+ const newObj = {
784
+ type: value.type,
785
+ target: serializeEventTarget(value.target),
786
+ currentTarget: serializeEventTarget(value.currentTarget),
787
+ ...getOwnProperties(value)
788
+ };
789
+ // TODO: figure out why this fails typing (I think CustomEvent is only supported in Node 19 onwards)
790
+ // if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
791
+ // newObj.detail = (value as unknown as CustomEvent).detail
792
+ // }
793
+ return newObj;
794
+ } else {
795
+ return value;
796
+ }
797
+ }
798
+ /** Filters out all but an object's own properties */
799
+ function getOwnProperties(obj) {
800
+ if (typeof obj === 'object' && obj !== null) {
801
+ const extractedProps = {};
802
+ for (const property in obj) {
803
+ if (Object.prototype.hasOwnProperty.call(obj, property)) {
804
+ extractedProps[property] = obj[property];
805
+ }
806
+ }
807
+ return extractedProps;
808
+ } else {
809
+ return {};
810
+ }
811
+ }
812
+ /** Creates a string representation of the target of an `Event` object */
813
+ function serializeEventTarget(target) {
814
+ try {
815
+ return Object.prototype.toString.call(target);
816
+ } catch (_oO) {
817
+ return '<unknown>';
818
+ }
819
+ }
820
+ /**
821
+ * Extracts stack frames from the error and builds an Exception
822
+ */
823
+ async function exceptionFromError(stackParser, frameModifiers, error) {
824
+ const exception = {
825
+ type: error.name || error.constructor.name,
826
+ value: error.message
827
+ };
828
+ let frames = parseStackFrames(stackParser, error);
829
+ for (const modifier of frameModifiers) {
830
+ frames = await modifier(frames);
831
+ }
832
+ if (frames.length) {
833
+ exception.stacktrace = {
834
+ frames,
835
+ type: 'raw'
836
+ };
837
+ }
838
+ return exception;
839
+ }
840
+ /**
841
+ * Extracts stack frames from the error.stack string
842
+ */
843
+ function parseStackFrames(stackParser, error) {
844
+ return applyChunkIds(stackParser(error.stack || '', 1), stackParser);
845
+ }
846
+ function applyChunkIds(frames, parser) {
847
+ const filenameChunkIdMap = getFilenameToChunkIdMap(parser);
848
+ frames.forEach(frame => {
849
+ if (frame.filename) {
850
+ frame.chunk_id = filenameChunkIdMap[frame.filename];
851
+ }
852
+ });
853
+ return frames;
854
+ }
855
+
856
+ const SHUTDOWN_TIMEOUT = 2000;
857
+ class ErrorTracking {
858
+ static async captureException(client, error, hint, distinctId, additionalProperties) {
859
+ const properties = {
860
+ ...additionalProperties
861
+ };
862
+ // Given stateless nature of Node SDK we capture exceptions using personless processing when no
863
+ // user can be determined because a distinct_id is not provided e.g. exception autocapture
864
+ if (!distinctId) {
865
+ properties.$process_person_profile = false;
866
+ }
867
+ const exceptionProperties = await propertiesFromUnknownInput(this.stackParser, this.frameModifiers, error, hint);
868
+ client.capture({
869
+ event: '$exception',
870
+ distinctId: distinctId || uuidv7(),
871
+ properties: {
872
+ ...exceptionProperties,
873
+ ...properties
874
+ }
875
+ });
876
+ }
877
+ constructor(client, options) {
878
+ this.client = client;
879
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
880
+ this.startAutocaptureIfEnabled();
881
+ }
882
+ startAutocaptureIfEnabled() {
883
+ if (this.isEnabled()) {
884
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
885
+ addUnhandledRejectionListener(this.onException.bind(this));
886
+ }
887
+ }
888
+ onException(exception, hint) {
889
+ ErrorTracking.captureException(this.client, exception, hint);
890
+ }
891
+ async onFatalError() {
892
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
893
+ }
894
+ isEnabled() {
895
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
896
+ }
897
+ }
898
+
899
+ function setupExpressErrorHandler(_posthog, app) {
900
+ app.use((error, _, __, next) => {
901
+ const hint = {
902
+ mechanism: {
903
+ type: 'middleware',
904
+ handled: false
905
+ }
906
+ };
907
+ // Given stateless nature of Node SDK we capture exceptions using personless processing
908
+ // when no user can be determined e.g. in the case of exception autocapture
909
+ ErrorTracking.captureException(_posthog, error, hint, uuidv7(), {
910
+ $process_person_profile: false
911
+ });
912
+ next(error);
913
+ });
914
+ }
915
+
916
+ var version = "5.1.0";
917
+
918
+ var PostHogPersistedProperty;
919
+ (function (PostHogPersistedProperty) {
920
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
921
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
922
+ PostHogPersistedProperty["Props"] = "props";
923
+ PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
924
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
925
+ PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
926
+ PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
927
+ PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
928
+ PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
929
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
930
+ PostHogPersistedProperty["Queue"] = "queue";
931
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
932
+ PostHogPersistedProperty["SessionId"] = "session_id";
933
+ PostHogPersistedProperty["SessionStartTimestamp"] = "session_start_timestamp";
934
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
935
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
936
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
937
+ PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
938
+ PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
939
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
940
+ PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
941
+ PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
942
+ PostHogPersistedProperty["Surveys"] = "surveys";
943
+ PostHogPersistedProperty["RemoteConfig"] = "remote_config";
944
+ PostHogPersistedProperty["FlagsEndpointWasHit"] = "flags_endpoint_was_hit";
945
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
946
+ // Any key prefixed with `attr__` can be added
947
+ var Compression;
948
+ (function (Compression) {
949
+ Compression["GZipJS"] = "gzip-js";
950
+ Compression["Base64"] = "base64";
951
+ })(Compression || (Compression = {}));
952
+ var SurveyPosition;
953
+ (function (SurveyPosition) {
954
+ SurveyPosition["Left"] = "left";
955
+ SurveyPosition["Right"] = "right";
956
+ SurveyPosition["Center"] = "center";
957
+ })(SurveyPosition || (SurveyPosition = {}));
958
+ var SurveyWidgetType;
959
+ (function (SurveyWidgetType) {
960
+ SurveyWidgetType["Button"] = "button";
961
+ SurveyWidgetType["Tab"] = "tab";
962
+ SurveyWidgetType["Selector"] = "selector";
963
+ })(SurveyWidgetType || (SurveyWidgetType = {}));
964
+ var SurveyType;
965
+ (function (SurveyType) {
966
+ SurveyType["Popover"] = "popover";
967
+ SurveyType["API"] = "api";
968
+ SurveyType["Widget"] = "widget";
969
+ })(SurveyType || (SurveyType = {}));
970
+ var SurveyQuestionDescriptionContentType;
971
+ (function (SurveyQuestionDescriptionContentType) {
972
+ SurveyQuestionDescriptionContentType["Html"] = "html";
973
+ SurveyQuestionDescriptionContentType["Text"] = "text";
974
+ })(SurveyQuestionDescriptionContentType || (SurveyQuestionDescriptionContentType = {}));
975
+ var SurveyRatingDisplay;
976
+ (function (SurveyRatingDisplay) {
977
+ SurveyRatingDisplay["Number"] = "number";
978
+ SurveyRatingDisplay["Emoji"] = "emoji";
979
+ })(SurveyRatingDisplay || (SurveyRatingDisplay = {}));
980
+ var SurveyQuestionType;
981
+ (function (SurveyQuestionType) {
982
+ SurveyQuestionType["Open"] = "open";
983
+ SurveyQuestionType["MultipleChoice"] = "multiple_choice";
984
+ SurveyQuestionType["SingleChoice"] = "single_choice";
985
+ SurveyQuestionType["Rating"] = "rating";
986
+ SurveyQuestionType["Link"] = "link";
987
+ })(SurveyQuestionType || (SurveyQuestionType = {}));
988
+ var SurveyQuestionBranchingType;
989
+ (function (SurveyQuestionBranchingType) {
990
+ SurveyQuestionBranchingType["NextQuestion"] = "next_question";
991
+ SurveyQuestionBranchingType["End"] = "end";
992
+ SurveyQuestionBranchingType["ResponseBased"] = "response_based";
993
+ SurveyQuestionBranchingType["SpecificQuestion"] = "specific_question";
994
+ })(SurveyQuestionBranchingType || (SurveyQuestionBranchingType = {}));
995
+ var SurveyMatchType;
996
+ (function (SurveyMatchType) {
997
+ SurveyMatchType["Regex"] = "regex";
998
+ SurveyMatchType["NotRegex"] = "not_regex";
999
+ SurveyMatchType["Exact"] = "exact";
1000
+ SurveyMatchType["IsNot"] = "is_not";
1001
+ SurveyMatchType["Icontains"] = "icontains";
1002
+ SurveyMatchType["NotIcontains"] = "not_icontains";
1003
+ })(SurveyMatchType || (SurveyMatchType = {}));
1004
+ /** Sync with plugin-server/src/types.ts */
1005
+ var ActionStepStringMatching;
1006
+ (function (ActionStepStringMatching) {
1007
+ ActionStepStringMatching["Contains"] = "contains";
1008
+ ActionStepStringMatching["Exact"] = "exact";
1009
+ ActionStepStringMatching["Regex"] = "regex";
1010
+ })(ActionStepStringMatching || (ActionStepStringMatching = {}));
1011
+
1012
+ const normalizeFlagsResponse = (flagsResponse) => {
1013
+ if ('flags' in flagsResponse) {
1014
+ // Convert v2 format to v1 format
1015
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
1016
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
1017
+ return {
1018
+ ...flagsResponse,
1019
+ featureFlags,
1020
+ featureFlagPayloads,
1021
+ };
1022
+ }
1023
+ else {
1024
+ // Convert v1 format to v2 format
1025
+ const featureFlags = flagsResponse.featureFlags ?? {};
1026
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [k, parsePayload(v)]));
1027
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
1028
+ key,
1029
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key]),
1030
+ ]));
1031
+ return {
1032
+ ...flagsResponse,
1033
+ featureFlags,
1034
+ featureFlagPayloads,
1035
+ flags,
1036
+ };
1037
+ }
1038
+ };
1039
+ function getFlagDetailFromFlagAndPayload(key, value, payload) {
1040
+ return {
1041
+ key: key,
1042
+ enabled: typeof value === 'string' ? true : value,
1043
+ variant: typeof value === 'string' ? value : undefined,
1044
+ reason: undefined,
1045
+ metadata: {
1046
+ id: undefined,
1047
+ version: undefined,
1048
+ payload: payload ? JSON.stringify(payload) : undefined,
1049
+ description: undefined,
1050
+ },
1051
+ };
1052
+ }
1053
+ /**
1054
+ * Get the flag values from the flags v4 response.
1055
+ * @param flags - The flags
1056
+ * @returns The flag values
1057
+ */
1058
+ const getFlagValuesFromFlags = (flags) => {
1059
+ return Object.fromEntries(Object.entries(flags ?? {})
1060
+ .map(([key, detail]) => [key, getFeatureFlagValue(detail)])
1061
+ .filter(([, value]) => value !== undefined));
1062
+ };
1063
+ /**
1064
+ * Get the payloads from the flags v4 response.
1065
+ * @param flags - The flags
1066
+ * @returns The payloads
1067
+ */
1068
+ const getPayloadsFromFlags = (flags) => {
1069
+ const safeFlags = flags ?? {};
1070
+ return Object.fromEntries(Object.keys(safeFlags)
1071
+ .filter((flag) => {
1072
+ const details = safeFlags[flag];
1073
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
1074
+ })
1075
+ .map((flag) => {
1076
+ const payload = safeFlags[flag].metadata?.payload;
1077
+ return [flag, payload ? parsePayload(payload) : undefined];
1078
+ }));
1079
+ };
1080
+ const getFeatureFlagValue = (detail) => {
1081
+ return detail === undefined ? undefined : detail.variant ?? detail.enabled;
1082
+ };
1083
+ const parsePayload = (response) => {
1084
+ if (typeof response !== 'string') {
1085
+ return response;
1086
+ }
1087
+ try {
1088
+ return JSON.parse(response);
1089
+ }
1090
+ catch {
1091
+ return response;
1092
+ }
1093
+ };
1094
+
1095
+ const STRING_FORMAT = 'utf8';
1096
+ function assert(truthyValue, message) {
1097
+ if (!truthyValue || typeof truthyValue !== 'string' || isEmpty(truthyValue)) {
1098
+ throw new Error(message);
1099
+ }
1100
+ }
1101
+ function isEmpty(truthyValue) {
1102
+ if (truthyValue.trim().length === 0) {
1103
+ return true;
1104
+ }
1105
+ return false;
1106
+ }
1107
+ function removeTrailingSlash(url) {
1108
+ return url?.replace(/\/+$/, '');
1109
+ }
1110
+ async function retriable(fn, props) {
1111
+ let lastError = null;
1112
+ for (let i = 0; i < props.retryCount + 1; i++) {
1113
+ if (i > 0) {
1114
+ // don't wait when it's the last try
1115
+ await new Promise((r) => setTimeout(r, props.retryDelay));
1116
+ }
1117
+ try {
1118
+ const res = await fn();
1119
+ return res;
1120
+ }
1121
+ catch (e) {
1122
+ lastError = e;
1123
+ if (!props.retryCheck(e)) {
1124
+ throw e;
1125
+ }
1126
+ }
1127
+ }
1128
+ throw lastError;
1129
+ }
1130
+ function currentISOTime() {
1131
+ return new Date().toISOString();
1132
+ }
1133
+ function safeSetTimeout(fn, timeout) {
1134
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
1135
+ // rather than setImmediate.
1136
+ const t = setTimeout(fn, timeout);
1137
+ // We unref if available to prevent Node.js hanging on exit
1138
+ t?.unref && t?.unref();
1139
+ return t;
1140
+ }
1141
+ function allSettled(promises) {
1142
+ return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({ status: 'fulfilled', value }), (reason) => ({ status: 'rejected', reason }))));
1143
+ }
1144
+
1145
+ /**
1146
+ * Older browsers and some runtimes don't support this yet
1147
+ * This API (as of 2025-05-07) is not available on React Native.
1148
+ */
1149
+ function isGzipSupported() {
1150
+ return 'CompressionStream' in globalThis;
1151
+ }
1152
+ /**
1153
+ * Gzip a string using Compression Streams API if it's available
1154
+ */
1155
+ async function gzipCompress(input, isDebug = true) {
1156
+ try {
1157
+ // Turn the string into a stream using a Blob, and then compress it
1158
+ const dataStream = new Blob([input], {
1159
+ type: 'text/plain',
1160
+ }).stream();
1161
+ const compressedStream = dataStream.pipeThrough(new CompressionStream('gzip'));
1162
+ // Using a Response to easily extract the readablestream value. Decoding into a string for fetch
1163
+ return await new Response(compressedStream).blob();
1164
+ }
1165
+ catch (error) {
1166
+ if (isDebug) {
1167
+ console.error('Failed to gzip compress data', error);
1168
+ }
1169
+ return null;
1170
+ }
1171
+ }
1172
+
1173
+ class SimpleEventEmitter {
1174
+ constructor() {
1175
+ this.events = {};
1176
+ this.events = {};
1177
+ }
1178
+ on(event, listener) {
1179
+ if (!this.events[event]) {
1180
+ this.events[event] = [];
1181
+ }
1182
+ this.events[event].push(listener);
1183
+ return () => {
1184
+ this.events[event] = this.events[event].filter((x) => x !== listener);
1185
+ };
1186
+ }
1187
+ emit(event, payload) {
1188
+ for (const listener of this.events[event] || []) {
1189
+ listener(payload);
1190
+ }
1191
+ for (const listener of this.events['*'] || []) {
1192
+ listener(event, payload);
1193
+ }
1194
+ }
1195
+ }
1196
+
1197
+ class PostHogFetchHttpError extends Error {
1198
+ constructor(response, reqByteLength) {
1199
+ super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength);
1200
+ this.response = response;
1201
+ this.reqByteLength = reqByteLength;
1202
+ this.name = 'PostHogFetchHttpError';
1203
+ }
1204
+ get status() {
1205
+ return this.response.status;
1206
+ }
1207
+ get text() {
1208
+ return this.response.text();
1209
+ }
1210
+ get json() {
1211
+ return this.response.json();
1212
+ }
1213
+ }
1214
+ class PostHogFetchNetworkError extends Error {
1215
+ constructor(error) {
1216
+ // TRICKY: "cause" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.
1217
+ // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1218
+ // @ts-ignore
1219
+ super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {});
1220
+ this.error = error;
1221
+ this.name = 'PostHogFetchNetworkError';
1222
+ }
1223
+ }
1224
+ async function logFlushError(err) {
1225
+ if (err instanceof PostHogFetchHttpError) {
1226
+ let text = '';
1227
+ try {
1228
+ text = await err.text;
1229
+ }
1230
+ catch { }
1231
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
1232
+ }
1233
+ else {
1234
+ console.error('Error while flushing PostHog', err);
1235
+ }
1236
+ return Promise.resolve();
1237
+ }
1238
+ function isPostHogFetchError(err) {
1239
+ return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
1240
+ }
1241
+ function isPostHogFetchContentTooLargeError(err) {
1242
+ return typeof err === 'object' && err instanceof PostHogFetchHttpError && err.status === 413;
1243
+ }
1244
+ var QuotaLimitedFeature;
1245
+ (function (QuotaLimitedFeature) {
1246
+ QuotaLimitedFeature["FeatureFlags"] = "feature_flags";
1247
+ QuotaLimitedFeature["Recordings"] = "recordings";
1248
+ })(QuotaLimitedFeature || (QuotaLimitedFeature = {}));
1249
+ class PostHogCoreStateless {
1250
+ constructor(apiKey, options) {
1251
+ this.flushPromise = null;
1252
+ this.shutdownPromise = null;
1253
+ this.pendingPromises = {};
1254
+ // internal
1255
+ this._events = new SimpleEventEmitter();
1256
+ this._isInitialized = false;
1257
+ assert(apiKey, "You must pass your PostHog project's api key.");
1258
+ this.apiKey = apiKey;
1259
+ this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com');
1260
+ this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
1261
+ this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
1262
+ this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
1263
+ this.flushInterval = options?.flushInterval ?? 10000;
1264
+ this.preloadFeatureFlags = options?.preloadFeatureFlags ?? true;
1265
+ // If enable is explicitly set to false we override the optout
1266
+ this.defaultOptIn = options?.defaultOptIn ?? true;
1267
+ this.disableSurveys = options?.disableSurveys ?? false;
1268
+ this._retryOptions = {
1269
+ retryCount: options?.fetchRetryCount ?? 3,
1270
+ retryDelay: options?.fetchRetryDelay ?? 3000,
1271
+ retryCheck: isPostHogFetchError,
1272
+ };
1273
+ this.requestTimeout = options?.requestTimeout ?? 10000; // 10 seconds
1274
+ this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
1275
+ this.remoteConfigRequestTimeoutMs = options?.remoteConfigRequestTimeoutMs ?? 3000; // 3 seconds
1276
+ this.disableGeoip = options?.disableGeoip ?? true;
1277
+ this.disabled = options?.disabled ?? false;
1278
+ this.historicalMigration = options?.historicalMigration ?? false;
1279
+ // Init promise allows the derived class to block calls until it is ready
1280
+ this._initPromise = Promise.resolve();
1281
+ this._isInitialized = true;
1282
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
1283
+ }
1284
+ logMsgIfDebug(fn) {
1285
+ if (this.isDebug) {
1286
+ fn();
1287
+ }
1288
+ }
1289
+ wrap(fn) {
1290
+ if (this.disabled) {
1291
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
1292
+ return;
1293
+ }
1294
+ if (this._isInitialized) {
1295
+ // NOTE: We could also check for the "opt in" status here...
1296
+ return fn();
1297
+ }
1298
+ this._initPromise.then(() => fn());
1299
+ }
1300
+ getCommonEventProperties() {
1301
+ return {
1302
+ $lib: this.getLibraryId(),
1303
+ $lib_version: this.getLibraryVersion(),
1304
+ };
1305
+ }
1306
+ get optedOut() {
1307
+ return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
1308
+ }
1309
+ async optIn() {
1310
+ this.wrap(() => {
1311
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
1312
+ });
1313
+ }
1314
+ async optOut() {
1315
+ this.wrap(() => {
1316
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
1317
+ });
1318
+ }
1319
+ on(event, cb) {
1320
+ return this._events.on(event, cb);
1321
+ }
1322
+ debug(enabled = true) {
1323
+ this.removeDebugCallback?.();
1324
+ if (enabled) {
1325
+ const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload));
1326
+ this.removeDebugCallback = () => {
1327
+ removeDebugCallback();
1328
+ this.removeDebugCallback = undefined;
1329
+ };
1330
+ }
1331
+ }
1332
+ get isDebug() {
1333
+ return !!this.removeDebugCallback;
1334
+ }
1335
+ get isDisabled() {
1336
+ return this.disabled;
1337
+ }
1338
+ buildPayload(payload) {
1339
+ return {
1340
+ distinct_id: payload.distinct_id,
1341
+ event: payload.event,
1342
+ properties: {
1343
+ ...(payload.properties || {}),
1344
+ ...this.getCommonEventProperties(), // Common PH props
1345
+ },
1346
+ };
1347
+ }
1348
+ addPendingPromise(promise) {
1349
+ const promiseUUID = uuidv7();
1350
+ this.pendingPromises[promiseUUID] = promise;
1351
+ promise
1352
+ .catch(() => { })
1353
+ .finally(() => {
1354
+ delete this.pendingPromises[promiseUUID];
1355
+ });
1356
+ return promise;
1357
+ }
1358
+ /***
1359
+ *** TRACKING
1360
+ ***/
1361
+ identifyStateless(distinctId, properties, options) {
1362
+ this.wrap(() => {
1363
+ // The properties passed to identifyStateless are event properties.
1364
+ // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.
1365
+ const payload = {
1366
+ ...this.buildPayload({
1367
+ distinct_id: distinctId,
1368
+ event: '$identify',
1369
+ properties,
1370
+ }),
1371
+ };
1372
+ this.enqueue('identify', payload, options);
1373
+ });
1374
+ }
1375
+ async identifyStatelessImmediate(distinctId, properties, options) {
1376
+ const payload = {
1377
+ ...this.buildPayload({
1378
+ distinct_id: distinctId,
1379
+ event: '$identify',
1380
+ properties,
1381
+ }),
1382
+ };
1383
+ await this.sendImmediate('identify', payload, options);
1384
+ }
1385
+ captureStateless(distinctId, event, properties, options) {
1386
+ this.wrap(() => {
1387
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1388
+ this.enqueue('capture', payload, options);
1389
+ });
1390
+ }
1391
+ async captureStatelessImmediate(distinctId, event, properties, options) {
1392
+ const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
1393
+ await this.sendImmediate('capture', payload, options);
1394
+ }
1395
+ aliasStateless(alias, distinctId, properties, options) {
1396
+ this.wrap(() => {
1397
+ const payload = this.buildPayload({
1398
+ event: '$create_alias',
1399
+ distinct_id: distinctId,
1400
+ properties: {
1401
+ ...(properties || {}),
1402
+ distinct_id: distinctId,
1403
+ alias,
1404
+ },
1405
+ });
1406
+ this.enqueue('alias', payload, options);
1407
+ });
1408
+ }
1409
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
1410
+ const payload = this.buildPayload({
1411
+ event: '$create_alias',
1412
+ distinct_id: distinctId,
1413
+ properties: {
1414
+ ...(properties || {}),
1415
+ distinct_id: distinctId,
1416
+ alias,
1417
+ },
1418
+ });
1419
+ await this.sendImmediate('alias', payload, options);
1420
+ }
1421
+ /***
1422
+ *** GROUPS
1423
+ ***/
1424
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1425
+ this.wrap(() => {
1426
+ const payload = this.buildPayload({
1427
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
1428
+ event: '$groupidentify',
1429
+ properties: {
1430
+ $group_type: groupType,
1431
+ $group_key: groupKey,
1432
+ $group_set: groupProperties || {},
1433
+ ...(eventProperties || {}),
1434
+ },
1435
+ });
1436
+ this.enqueue('capture', payload, options);
1437
+ });
1438
+ }
1439
+ async getRemoteConfig() {
1440
+ await this._initPromise;
1441
+ let host = this.host;
1442
+ if (host === 'https://us.i.posthog.com') {
1443
+ host = 'https://us-assets.i.posthog.com';
1444
+ }
1445
+ else if (host === 'https://eu.i.posthog.com') {
1446
+ host = 'https://eu-assets.i.posthog.com';
1447
+ }
1448
+ const url = `${host}/array/${this.apiKey}/config`;
1449
+ const fetchOptions = {
1450
+ method: 'GET',
1451
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1452
+ };
1453
+ // Don't retry remote config API calls
1454
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.remoteConfigRequestTimeoutMs)
1455
+ .then((response) => response.json())
1456
+ .catch((error) => {
1457
+ this.logMsgIfDebug(() => console.error('Remote config could not be loaded', error));
1458
+ this._events.emit('error', error);
1459
+ return undefined;
1460
+ });
1461
+ }
1462
+ /***
1463
+ *** FEATURE FLAGS
1464
+ ***/
1465
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
1466
+ await this._initPromise;
1467
+ const url = `${this.host}/flags/?v=2&config=true`;
1468
+ const fetchOptions = {
1469
+ method: 'POST',
1470
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1471
+ body: JSON.stringify({
1472
+ token: this.apiKey,
1473
+ distinct_id: distinctId,
1474
+ groups,
1475
+ person_properties: personProperties,
1476
+ group_properties: groupProperties,
1477
+ ...extraPayload,
1478
+ }),
1479
+ };
1480
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Flags URL', url));
1481
+ // Don't retry /flags API calls
1482
+ return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)
1483
+ .then((response) => response.json())
1484
+ .then((response) => normalizeFlagsResponse(response))
1485
+ .catch((error) => {
1486
+ this._events.emit('error', error);
1487
+ return undefined;
1488
+ });
1489
+ }
1490
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1491
+ await this._initPromise;
1492
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
1493
+ if (flagDetailResponse === undefined) {
1494
+ // If we haven't loaded flags yet, or errored out, we respond with undefined
1495
+ return {
1496
+ response: undefined,
1497
+ requestId: undefined,
1498
+ };
1499
+ }
1500
+ let response = getFeatureFlagValue(flagDetailResponse.response);
1501
+ if (response === undefined) {
1502
+ // For cases where the flag is unknown, return false
1503
+ response = false;
1504
+ }
1505
+ // If we have flags we either return the value (true or string) or false
1506
+ return {
1507
+ response,
1508
+ requestId: flagDetailResponse.requestId,
1509
+ };
1510
+ }
1511
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1512
+ await this._initPromise;
1513
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
1514
+ if (flagsResponse === undefined) {
1515
+ return undefined;
1516
+ }
1517
+ const featureFlags = flagsResponse.flags;
1518
+ const flagDetail = featureFlags[key];
1519
+ return {
1520
+ response: flagDetail,
1521
+ requestId: flagsResponse.requestId,
1522
+ };
1523
+ }
1524
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1525
+ await this._initPromise;
1526
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
1527
+ if (!payloads) {
1528
+ return undefined;
1529
+ }
1530
+ const response = payloads[key];
1531
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
1532
+ if (response === undefined) {
1533
+ return null;
1534
+ }
1535
+ return response;
1536
+ }
1537
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1538
+ await this._initPromise;
1539
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
1540
+ return payloads;
1541
+ }
1542
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1543
+ await this._initPromise;
1544
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1545
+ }
1546
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1547
+ await this._initPromise;
1548
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1549
+ if (!featureFlagDetails) {
1550
+ return {
1551
+ flags: undefined,
1552
+ payloads: undefined,
1553
+ requestId: undefined,
1554
+ };
1555
+ }
1556
+ return {
1557
+ flags: featureFlagDetails.featureFlags,
1558
+ payloads: featureFlagDetails.featureFlagPayloads,
1559
+ requestId: featureFlagDetails.requestId,
1560
+ };
1561
+ }
1562
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1563
+ await this._initPromise;
1564
+ const extraPayload = {};
1565
+ if (disableGeoip ?? this.disableGeoip) {
1566
+ extraPayload['geoip_disable'] = true;
1567
+ }
1568
+ if (flagKeysToEvaluate) {
1569
+ extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
1570
+ }
1571
+ const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
1572
+ if (flagsResponse === undefined) {
1573
+ // We probably errored out, so return undefined
1574
+ return undefined;
1575
+ }
1576
+ // if there's an error on the flagsResponse, log a console error, but don't throw an error
1577
+ if (flagsResponse.errorsWhileComputingFlags) {
1578
+ 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');
1579
+ }
1580
+ // Add check for quota limitation on feature flags
1581
+ if (flagsResponse.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {
1582
+ 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');
1583
+ return {
1584
+ flags: {},
1585
+ featureFlags: {},
1586
+ featureFlagPayloads: {},
1587
+ requestId: flagsResponse?.requestId,
1588
+ };
1589
+ }
1590
+ return flagsResponse;
1591
+ }
1592
+ /***
1593
+ *** SURVEYS
1594
+ ***/
1595
+ async getSurveysStateless() {
1596
+ await this._initPromise;
1597
+ if (this.disableSurveys === true) {
1598
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Loading surveys is disabled.'));
1599
+ return [];
1600
+ }
1601
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
1602
+ const fetchOptions = {
1603
+ method: 'GET',
1604
+ headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
1605
+ };
1606
+ const response = await this.fetchWithRetry(url, fetchOptions)
1607
+ .then((response) => {
1608
+ if (response.status !== 200 || !response.json) {
1609
+ const msg = `Surveys API could not be loaded: ${response.status}`;
1610
+ const error = new Error(msg);
1611
+ this.logMsgIfDebug(() => console.error(error));
1612
+ this._events.emit('error', new Error(msg));
1613
+ return undefined;
1614
+ }
1615
+ return response.json();
1616
+ })
1617
+ .catch((error) => {
1618
+ this.logMsgIfDebug(() => console.error('Surveys API could not be loaded', error));
1619
+ this._events.emit('error', error);
1620
+ return undefined;
1621
+ });
1622
+ const newSurveys = response?.surveys;
1623
+ if (newSurveys) {
1624
+ this.logMsgIfDebug(() => console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
1625
+ }
1626
+ return newSurveys ?? [];
1627
+ }
1628
+ get props() {
1629
+ if (!this._props) {
1630
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
1631
+ }
1632
+ return this._props || {};
1633
+ }
1634
+ set props(val) {
1635
+ this._props = val;
1636
+ }
1637
+ async register(properties) {
1638
+ this.wrap(() => {
1639
+ this.props = {
1640
+ ...this.props,
1641
+ ...properties,
1642
+ };
1643
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1644
+ });
1645
+ }
1646
+ async unregister(property) {
1647
+ this.wrap(() => {
1648
+ delete this.props[property];
1649
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
1650
+ });
1651
+ }
1652
+ /***
1653
+ *** QUEUEING AND FLUSHING
1654
+ ***/
1655
+ enqueue(type, _message, options) {
1656
+ this.wrap(() => {
1657
+ if (this.optedOut) {
1658
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
1659
+ return;
1660
+ }
1661
+ const message = this.prepareMessage(type, _message, options);
1662
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1663
+ if (queue.length >= this.maxQueueSize) {
1664
+ queue.shift();
1665
+ this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'));
1666
+ }
1667
+ queue.push({ message });
1668
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1669
+ this._events.emit(type, message);
1670
+ // Flush queued events if we meet the flushAt length
1671
+ if (queue.length >= this.flushAt) {
1672
+ this.flushBackground();
1673
+ }
1674
+ if (this.flushInterval && !this._flushTimer) {
1675
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
1676
+ }
1677
+ });
1678
+ }
1679
+ async sendImmediate(type, _message, options) {
1680
+ if (this.disabled) {
1681
+ this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
1682
+ return;
1683
+ }
1684
+ if (!this._isInitialized) {
1685
+ await this._initPromise;
1686
+ }
1687
+ if (this.optedOut) {
1688
+ this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
1689
+ return;
1690
+ }
1691
+ const data = {
1692
+ api_key: this.apiKey,
1693
+ batch: [this.prepareMessage(type, _message, options)],
1694
+ sent_at: currentISOTime(),
1695
+ };
1696
+ if (this.historicalMigration) {
1697
+ data.historical_migration = true;
1698
+ }
1699
+ const payload = JSON.stringify(data);
1700
+ const url = `${this.host}/batch/`;
1701
+ const gzippedPayload = !this.disableCompression ? await gzipCompress(payload, this.isDebug) : null;
1702
+ const fetchOptions = {
1703
+ method: 'POST',
1704
+ headers: {
1705
+ ...this.getCustomHeaders(),
1706
+ 'Content-Type': 'application/json',
1707
+ ...(gzippedPayload !== null && { 'Content-Encoding': 'gzip' }),
1708
+ },
1709
+ body: gzippedPayload || payload,
1710
+ };
1711
+ try {
1712
+ await this.fetchWithRetry(url, fetchOptions);
1713
+ }
1714
+ catch (err) {
1715
+ this._events.emit('error', err);
1716
+ }
1717
+ }
1718
+ prepareMessage(type, _message, options) {
1719
+ const message = {
1720
+ ..._message,
1721
+ type: type,
1722
+ library: this.getLibraryId(),
1723
+ library_version: this.getLibraryVersion(),
1724
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1725
+ uuid: options?.uuid ? options.uuid : uuidv7(),
1726
+ };
1727
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1728
+ if (addGeoipDisableProperty) {
1729
+ if (!message.properties) {
1730
+ message.properties = {};
1731
+ }
1732
+ message['properties']['$geoip_disable'] = true;
1733
+ }
1734
+ if (message.distinctId) {
1735
+ message.distinct_id = message.distinctId;
1736
+ delete message.distinctId;
1737
+ }
1738
+ return message;
1739
+ }
1740
+ clearFlushTimer() {
1741
+ if (this._flushTimer) {
1742
+ clearTimeout(this._flushTimer);
1743
+ this._flushTimer = undefined;
1744
+ }
1745
+ }
1746
+ /**
1747
+ * Helper for flushing the queue in the background
1748
+ * Avoids unnecessary promise errors
1749
+ */
1750
+ flushBackground() {
1751
+ void this.flush().catch(async (err) => {
1752
+ await logFlushError(err);
1753
+ });
1754
+ }
1755
+ /**
1756
+ * Flushes the queue
1757
+ *
1758
+ * This function will return a promise that will resolve when the flush is complete,
1759
+ * or reject if there was an error (for example if the server or network is down).
1760
+ *
1761
+ * If there is already a flush in progress, this function will wait for that flush to complete.
1762
+ *
1763
+ * It's recommended to do error handling in the callback of the promise.
1764
+ *
1765
+ * @example
1766
+ * posthog.flush().then(() => {
1767
+ * console.log('Flush complete')
1768
+ * }).catch((err) => {
1769
+ * console.error('Flush failed', err)
1770
+ * })
1771
+ *
1772
+ *
1773
+ * @throws PostHogFetchHttpError
1774
+ * @throws PostHogFetchNetworkError
1775
+ * @throws Error
1776
+ */
1777
+ async flush() {
1778
+ // Wait for the current flush operation to finish (regardless of success or failure), then try to flush again.
1779
+ // Use allSettled instead of finally to be defensive around flush throwing errors immediately rather than rejecting.
1780
+ // Use a custom allSettled implementation to avoid issues with patching Promise on RN
1781
+ const nextFlushPromise = allSettled([this.flushPromise]).then(() => {
1782
+ return this._flush();
1783
+ });
1784
+ this.flushPromise = nextFlushPromise;
1785
+ void this.addPendingPromise(nextFlushPromise);
1786
+ allSettled([nextFlushPromise]).then(() => {
1787
+ // If there are no others waiting to flush, clear the promise.
1788
+ // We don't strictly need to do this, but it could make debugging easier
1789
+ if (this.flushPromise === nextFlushPromise) {
1790
+ this.flushPromise = null;
1791
+ }
1792
+ });
1793
+ return nextFlushPromise;
1794
+ }
1795
+ getCustomHeaders() {
1796
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1797
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1798
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1799
+ // but browsers such as Chrome and Safari have not caught up.
1800
+ const customUserAgent = this.getCustomUserAgent();
1801
+ const headers = {};
1802
+ if (customUserAgent && customUserAgent !== '') {
1803
+ headers['User-Agent'] = customUserAgent;
1804
+ }
1805
+ return headers;
1806
+ }
1807
+ async _flush() {
1808
+ this.clearFlushTimer();
1809
+ await this._initPromise;
1810
+ let queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1811
+ if (!queue.length) {
1812
+ return;
1813
+ }
1814
+ const sentMessages = [];
1815
+ const originalQueueLength = queue.length;
1816
+ while (queue.length > 0 && sentMessages.length < originalQueueLength) {
1817
+ const batchItems = queue.slice(0, this.maxBatchSize);
1818
+ const batchMessages = batchItems.map((item) => item.message);
1819
+ const persistQueueChange = () => {
1820
+ const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1821
+ const newQueue = refreshedQueue.slice(batchItems.length);
1822
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, newQueue);
1823
+ queue = newQueue;
1824
+ };
1825
+ const data = {
1826
+ api_key: this.apiKey,
1827
+ batch: batchMessages,
1828
+ sent_at: currentISOTime(),
1829
+ };
1830
+ if (this.historicalMigration) {
1831
+ data.historical_migration = true;
1832
+ }
1833
+ const payload = JSON.stringify(data);
1834
+ const url = `${this.host}/batch/`;
1835
+ const gzippedPayload = !this.disableCompression ? await gzipCompress(payload, this.isDebug) : null;
1836
+ const fetchOptions = {
1837
+ method: 'POST',
1838
+ headers: {
1839
+ ...this.getCustomHeaders(),
1840
+ 'Content-Type': 'application/json',
1841
+ ...(gzippedPayload !== null && { 'Content-Encoding': 'gzip' }),
1842
+ },
1843
+ body: gzippedPayload || payload,
1844
+ };
1845
+ const retryOptions = {
1846
+ retryCheck: (err) => {
1847
+ // don't automatically retry on 413 errors, we want to reduce the batch size first
1848
+ if (isPostHogFetchContentTooLargeError(err)) {
1849
+ return false;
1850
+ }
1851
+ // otherwise, retry on network errors
1852
+ return isPostHogFetchError(err);
1853
+ },
1854
+ };
1855
+ try {
1856
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
1857
+ }
1858
+ catch (err) {
1859
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
1860
+ // if we get a 413 error, we want to reduce the batch size and try again
1861
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
1862
+ this.logMsgIfDebug(() => console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
1863
+ // do not persist the queue change, we want to retry the same batch
1864
+ continue;
1865
+ }
1866
+ // depending on the error type, eg a malformed JSON or broken queue, it'll always return an error
1867
+ // and this will be an endless loop, in this case, if the error isn't a network issue, we always remove the items from the queue
1868
+ if (!(err instanceof PostHogFetchNetworkError)) {
1869
+ persistQueueChange();
1870
+ }
1871
+ this._events.emit('error', err);
1872
+ throw err;
1873
+ }
1874
+ persistQueueChange();
1875
+ sentMessages.push(...batchMessages);
1876
+ }
1877
+ this._events.emit('flush', sentMessages);
1878
+ }
1879
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1880
+ var _a;
1881
+ (_a = AbortSignal).timeout ?? (_a.timeout = function timeout(ms) {
1882
+ const ctrl = new AbortController();
1883
+ setTimeout(() => ctrl.abort(), ms);
1884
+ return ctrl.signal;
1885
+ });
1886
+ const body = options.body ? options.body : '';
1887
+ let reqByteLength = -1;
1888
+ try {
1889
+ if (body instanceof Blob) {
1890
+ reqByteLength = body.size;
1891
+ }
1892
+ else {
1893
+ reqByteLength = Buffer.byteLength(body, STRING_FORMAT);
1894
+ }
1895
+ }
1896
+ catch {
1897
+ if (body instanceof Blob) {
1898
+ reqByteLength = body.size;
1899
+ }
1900
+ else {
1901
+ const encoded = new TextEncoder().encode(body);
1902
+ reqByteLength = encoded.length;
1903
+ }
1904
+ }
1905
+ return await retriable(async () => {
1906
+ let res = null;
1907
+ try {
1908
+ res = await this.fetch(url, {
1909
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1910
+ ...options,
1911
+ });
1912
+ }
1913
+ catch (e) {
1914
+ // fetch will only throw on network errors or on timeouts
1915
+ throw new PostHogFetchNetworkError(e);
1916
+ }
1917
+ // If we're in no-cors mode, we can't access the response status
1918
+ // We only throw on HTTP errors if we're not in no-cors mode
1919
+ // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors
1920
+ const isNoCors = options.mode === 'no-cors';
1921
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) {
1922
+ throw new PostHogFetchHttpError(res, reqByteLength);
1923
+ }
1924
+ return res;
1925
+ }, { ...this._retryOptions, ...retryOptions });
1926
+ }
1927
+ async _shutdown(shutdownTimeoutMs = 30000) {
1928
+ // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some
1929
+ // dangling promises. We'll keep track of the timeout and resolve/reject based on that.
1930
+ await this._initPromise;
1931
+ let hasTimedOut = false;
1932
+ this.clearFlushTimer();
1933
+ const doShutdown = async () => {
1934
+ try {
1935
+ await Promise.all(Object.values(this.pendingPromises));
1936
+ while (true) {
1937
+ const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1938
+ if (queue.length === 0) {
1939
+ break;
1940
+ }
1941
+ // flush again to make sure we send all events, some of which might've been added
1942
+ // while we were waiting for the pending promises to resolve
1943
+ // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
1944
+ await this.flush();
1945
+ if (hasTimedOut) {
1946
+ break;
1947
+ }
1948
+ }
1949
+ }
1950
+ catch (e) {
1951
+ if (!isPostHogFetchError(e)) {
1952
+ throw e;
1953
+ }
1954
+ await logFlushError(e);
1955
+ }
1956
+ };
1957
+ return Promise.race([
1958
+ new Promise((_, reject) => {
1959
+ safeSetTimeout(() => {
1960
+ this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'));
1961
+ hasTimedOut = true;
1962
+ reject('Timeout while shutting down PostHog. Some events may not have been sent.');
1963
+ }, shutdownTimeoutMs);
1964
+ }),
1965
+ doShutdown(),
1966
+ ]);
1967
+ }
1968
+ /**
1969
+ * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
1970
+ * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
1971
+ * @param shutdownTimeoutMs
1972
+ */
1973
+ async shutdown(shutdownTimeoutMs = 30000) {
1974
+ if (this.shutdownPromise) {
1975
+ 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'));
1976
+ }
1977
+ else {
1978
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
1979
+ this.shutdownPromise = null;
1980
+ });
1981
+ }
1982
+ return this.shutdownPromise;
1983
+ }
1984
+ }
1985
+
1986
+ /**
1987
+ * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.
1988
+ */
1989
+ class Lazy {
1990
+ constructor(factory) {
1991
+ this.factory = factory;
1992
+ }
1993
+ /**
1994
+ * Gets the value, initializing it if necessary.
1995
+ * Multiple concurrent calls will share the same initialization promise.
1996
+ */
1997
+ async getValue() {
1998
+ if (this.value !== undefined) {
1999
+ return this.value;
2000
+ }
2001
+ if (this.initializationPromise === undefined) {
2002
+ this.initializationPromise = (async () => {
2003
+ try {
2004
+ const result = await this.factory();
2005
+ this.value = result;
2006
+ return result;
2007
+ } finally {
2008
+ // Clear the promise so we can retry if needed
2009
+ this.initializationPromise = undefined;
2010
+ }
2011
+ })();
2012
+ }
2013
+ return this.initializationPromise;
2014
+ }
2015
+ /**
2016
+ * Returns true if the value has been initialized.
2017
+ */
2018
+ isInitialized() {
2019
+ return this.value !== undefined;
2020
+ }
2021
+ /**
2022
+ * Returns a promise that resolves when the value is initialized.
2023
+ * If already initialized, resolves immediately.
2024
+ */
2025
+ async waitForInitialization() {
2026
+ if (this.isInitialized()) {
2027
+ return;
2028
+ }
2029
+ await this.getValue();
2030
+ }
2031
+ }
2032
+
2033
+ /// <reference lib="dom" />
2034
+ const nodeCrypto = new Lazy(async () => {
2035
+ try {
2036
+ return await import('crypto');
2037
+ } catch {
2038
+ return undefined;
2039
+ }
2040
+ });
2041
+ async function getNodeCrypto() {
2042
+ return await nodeCrypto.getValue();
2043
+ }
2044
+ const webCrypto = new Lazy(async () => {
2045
+ if (typeof globalThis.crypto?.subtle !== 'undefined') {
2046
+ return globalThis.crypto.subtle;
2047
+ }
2048
+ try {
2049
+ // Node.js: use built-in webcrypto and assign it if needed
2050
+ const crypto = await nodeCrypto.getValue();
2051
+ if (crypto?.webcrypto?.subtle) {
2052
+ return crypto.webcrypto.subtle;
2053
+ }
2054
+ } catch {
2055
+ // Ignore if not available
2056
+ }
2057
+ return undefined;
2058
+ });
2059
+ async function getWebCrypto() {
2060
+ return await webCrypto.getValue();
2061
+ }
2062
+
2063
+ /// <reference lib="dom" />
2064
+ async function hashSHA1(text) {
2065
+ // Try Node.js crypto first
2066
+ const nodeCrypto = await getNodeCrypto();
2067
+ if (nodeCrypto) {
2068
+ return nodeCrypto.createHash('sha1').update(text).digest('hex');
2069
+ }
2070
+ const webCrypto = await getWebCrypto();
2071
+ // Fall back to Web Crypto API
2072
+ if (webCrypto) {
2073
+ const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text));
2074
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
2075
+ return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
2076
+ }
2077
+ throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API');
2078
+ }
2079
+
2080
+ const SIXTY_SECONDS = 60 * 1000;
2081
+ // eslint-disable-next-line
2082
+ const LONG_SCALE = 0xfffffffffffffff;
2083
+ const NULL_VALUES_ALLOWED_OPERATORS = ['is_not'];
2084
+ class ClientError extends Error {
2085
+ constructor(message) {
2086
+ super();
2087
+ Error.captureStackTrace(this, this.constructor);
2088
+ this.name = 'ClientError';
2089
+ this.message = message;
2090
+ Object.setPrototypeOf(this, ClientError.prototype);
2091
+ }
2092
+ }
2093
+ class InconclusiveMatchError extends Error {
2094
+ constructor(message) {
2095
+ super(message);
2096
+ this.name = this.constructor.name;
2097
+ Error.captureStackTrace(this, this.constructor);
2098
+ // instanceof doesn't work in ES3 or ES5
2099
+ // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
2100
+ // this is the workaround
2101
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
2102
+ }
2103
+ }
2104
+ class FeatureFlagsPoller {
2105
+ constructor({
2106
+ pollingInterval,
2107
+ personalApiKey,
2108
+ projectApiKey,
2109
+ timeout,
2110
+ host,
2111
+ customHeaders,
2112
+ ...options
2113
+ }) {
2114
+ this.debugMode = false;
2115
+ this.shouldBeginExponentialBackoff = false;
2116
+ this.backOffCount = 0;
2117
+ this.pollingInterval = pollingInterval;
2118
+ this.personalApiKey = personalApiKey;
2119
+ this.featureFlags = [];
2120
+ this.featureFlagsByKey = {};
2121
+ this.groupTypeMapping = {};
2122
+ this.cohorts = {};
2123
+ this.loadedSuccessfullyOnce = false;
2124
+ this.timeout = timeout;
2125
+ this.projectApiKey = projectApiKey;
2126
+ this.host = host;
2127
+ this.poller = undefined;
2128
+ this.fetch = options.fetch || fetch;
2129
+ this.onError = options.onError;
2130
+ this.customHeaders = customHeaders;
2131
+ this.onLoad = options.onLoad;
2132
+ void this.loadFeatureFlags();
2133
+ }
2134
+ debug(enabled = true) {
2135
+ this.debugMode = enabled;
2136
+ }
2137
+ logMsgIfDebug(fn) {
2138
+ if (this.debugMode) {
2139
+ fn();
2140
+ }
2141
+ }
2142
+ async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2143
+ await this.loadFeatureFlags();
2144
+ let response = undefined;
2145
+ let featureFlag = undefined;
2146
+ if (!this.loadedSuccessfullyOnce) {
2147
+ return response;
2148
+ }
2149
+ for (const flag of this.featureFlags) {
2150
+ if (key === flag.key) {
2151
+ featureFlag = flag;
2152
+ break;
2153
+ }
2154
+ }
2155
+ if (featureFlag !== undefined) {
2156
+ try {
2157
+ response = await this.computeFlagLocally(featureFlag, distinctId, groups, personProperties, groupProperties);
2158
+ this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2159
+ } catch (e) {
2160
+ if (e instanceof InconclusiveMatchError) {
2161
+ this.logMsgIfDebug(() => console.debug(`InconclusiveMatchError when computing flag locally: ${key}: ${e}`));
2162
+ } else if (e instanceof Error) {
2163
+ this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2164
+ }
2165
+ }
2166
+ }
2167
+ return response;
2168
+ }
2169
+ async computeFeatureFlagPayloadLocally(key, matchValue) {
2170
+ await this.loadFeatureFlags();
2171
+ let response = undefined;
2172
+ if (!this.loadedSuccessfullyOnce) {
2173
+ return undefined;
2174
+ }
2175
+ if (typeof matchValue == 'boolean') {
2176
+ response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue.toString()];
2177
+ } else if (typeof matchValue == 'string') {
2178
+ response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue];
2179
+ }
2180
+ // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
2181
+ if (response === undefined || response === null) {
2182
+ return null;
2183
+ }
2184
+ try {
2185
+ return JSON.parse(response);
2186
+ } catch {
2187
+ return response;
2188
+ }
2189
+ }
2190
+ async getAllFlagsAndPayloads(distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2191
+ await this.loadFeatureFlags();
2192
+ const response = {};
2193
+ const payloads = {};
2194
+ let fallbackToFlags = this.featureFlags.length == 0;
2195
+ await Promise.all(this.featureFlags.map(async flag => {
2196
+ try {
2197
+ const matchValue = await this.computeFlagLocally(flag, distinctId, groups, personProperties, groupProperties);
2198
+ response[flag.key] = matchValue;
2199
+ const matchPayload = await this.computeFeatureFlagPayloadLocally(flag.key, matchValue);
2200
+ if (matchPayload) {
2201
+ payloads[flag.key] = matchPayload;
2202
+ }
2203
+ } catch (e) {
2204
+ if (e instanceof InconclusiveMatchError) ; else if (e instanceof Error) {
2205
+ this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2206
+ }
2207
+ fallbackToFlags = true;
2208
+ }
2209
+ }));
2210
+ return {
2211
+ response,
2212
+ payloads,
2213
+ fallbackToFlags
2214
+ };
2215
+ }
2216
+ async computeFlagLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2217
+ if (flag.ensure_experience_continuity) {
2218
+ throw new InconclusiveMatchError('Flag has experience continuity enabled');
2219
+ }
2220
+ if (!flag.active) {
2221
+ return false;
2222
+ }
2223
+ const flagFilters = flag.filters || {};
2224
+ const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2225
+ if (aggregation_group_type_index != undefined) {
2226
+ const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2227
+ if (!groupName) {
2228
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2229
+ throw new InconclusiveMatchError('Flag has unknown group type index');
2230
+ }
2231
+ if (!(groupName in groups)) {
2232
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2233
+ return false;
2234
+ }
2235
+ const focusedGroupProperties = groupProperties[groupName];
2236
+ return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties);
2237
+ } else {
2238
+ return await this.matchFeatureFlagProperties(flag, distinctId, personProperties);
2239
+ }
2240
+ }
2241
+ async matchFeatureFlagProperties(flag, distinctId, properties) {
2242
+ const flagFilters = flag.filters || {};
2243
+ const flagConditions = flagFilters.groups || [];
2244
+ let isInconclusive = false;
2245
+ let result = undefined;
2246
+ // # Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are
2247
+ // # evaluated first, and the variant override is applied to the first matching condition.
2248
+ const sortedFlagConditions = [...flagConditions].sort((conditionA, conditionB) => {
2249
+ const AHasVariantOverride = !!conditionA.variant;
2250
+ const BHasVariantOverride = !!conditionB.variant;
2251
+ if (AHasVariantOverride && BHasVariantOverride) {
2252
+ return 0;
2253
+ } else if (AHasVariantOverride) {
2254
+ return -1;
2255
+ } else if (BHasVariantOverride) {
2256
+ return 1;
2257
+ } else {
2258
+ return 0;
2259
+ }
2260
+ });
2261
+ for (const condition of sortedFlagConditions) {
2262
+ try {
2263
+ if (await this.isConditionMatch(flag, distinctId, condition, properties)) {
2264
+ const variantOverride = condition.variant;
2265
+ const flagVariants = flagFilters.multivariate?.variants || [];
2266
+ if (variantOverride && flagVariants.some(variant => variant.key === variantOverride)) {
2267
+ result = variantOverride;
2268
+ } else {
2269
+ result = (await this.getMatchingVariant(flag, distinctId)) || true;
2270
+ }
2271
+ break;
2272
+ }
2273
+ } catch (e) {
2274
+ if (e instanceof InconclusiveMatchError) {
2275
+ isInconclusive = true;
2276
+ } else {
2277
+ throw e;
2278
+ }
2279
+ }
2280
+ }
2281
+ if (result !== undefined) {
2282
+ return result;
2283
+ } else if (isInconclusive) {
2284
+ throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
2285
+ }
2286
+ // We can only return False when all conditions are False
2287
+ return false;
2288
+ }
2289
+ async isConditionMatch(flag, distinctId, condition, properties) {
2290
+ const rolloutPercentage = condition.rollout_percentage;
2291
+ const warnFunction = msg => {
2292
+ this.logMsgIfDebug(() => console.warn(msg));
2293
+ };
2294
+ if ((condition.properties || []).length > 0) {
2295
+ for (const prop of condition.properties) {
2296
+ const propertyType = prop.type;
2297
+ let matches = false;
2298
+ if (propertyType === 'cohort') {
2299
+ matches = matchCohort(prop, properties, this.cohorts, this.debugMode);
2300
+ } else {
2301
+ matches = matchProperty(prop, properties, warnFunction);
2302
+ }
2303
+ if (!matches) {
2304
+ return false;
2305
+ }
2306
+ }
2307
+ if (rolloutPercentage == undefined) {
2308
+ return true;
2309
+ }
2310
+ }
2311
+ if (rolloutPercentage != undefined && (await _hash(flag.key, distinctId)) > rolloutPercentage / 100.0) {
2312
+ return false;
2313
+ }
2314
+ return true;
2315
+ }
2316
+ async getMatchingVariant(flag, distinctId) {
2317
+ const hashValue = await _hash(flag.key, distinctId, 'variant');
2318
+ const matchingVariant = this.variantLookupTable(flag).find(variant => {
2319
+ return hashValue >= variant.valueMin && hashValue < variant.valueMax;
2320
+ });
2321
+ if (matchingVariant) {
2322
+ return matchingVariant.key;
2323
+ }
2324
+ return undefined;
2325
+ }
2326
+ variantLookupTable(flag) {
2327
+ const lookupTable = [];
2328
+ let valueMin = 0;
2329
+ let valueMax = 0;
2330
+ const flagFilters = flag.filters || {};
2331
+ const multivariates = flagFilters.multivariate?.variants || [];
2332
+ multivariates.forEach(variant => {
2333
+ valueMax = valueMin + variant.rollout_percentage / 100.0;
2334
+ lookupTable.push({
2335
+ valueMin,
2336
+ valueMax,
2337
+ key: variant.key
2338
+ });
2339
+ valueMin = valueMax;
2340
+ });
2341
+ return lookupTable;
2342
+ }
2343
+ async loadFeatureFlags(forceReload = false) {
2344
+ if (!this.loadedSuccessfullyOnce || forceReload) {
2345
+ await this._loadFeatureFlags();
2346
+ }
2347
+ }
2348
+ /**
2349
+ * Returns true if the feature flags poller has loaded successfully at least once and has more than 0 feature flags.
2350
+ * This is useful to check if local evaluation is ready before calling getFeatureFlag.
2351
+ */
2352
+ isLocalEvaluationReady() {
2353
+ return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
2354
+ }
2355
+ /**
2356
+ * If a client is misconfigured with an invalid or improper API key, the polling interval is doubled each time
2357
+ * until a successful request is made, up to a maximum of 60 seconds.
2358
+ *
2359
+ * @returns The polling interval to use for the next request.
2360
+ */
2361
+ getPollingInterval() {
2362
+ if (!this.shouldBeginExponentialBackoff) {
2363
+ return this.pollingInterval;
2364
+ }
2365
+ return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
2366
+ }
2367
+ async _loadFeatureFlags() {
2368
+ if (this.poller) {
2369
+ clearTimeout(this.poller);
2370
+ this.poller = undefined;
2371
+ }
2372
+ this.poller = setTimeout(() => this._loadFeatureFlags(), this.getPollingInterval());
2373
+ try {
2374
+ const res = await this._requestFeatureFlagDefinitions();
2375
+ // Handle undefined res case, this shouldn't happen, but it doesn't hurt to handle it anyway
2376
+ if (!res) {
2377
+ // Don't override existing flags when something goes wrong
2378
+ return;
2379
+ }
2380
+ // NB ON ERROR HANDLING & `loadedSuccessfullyOnce`:
2381
+ //
2382
+ // `loadedSuccessfullyOnce` indicates we've successfully loaded a valid set of flags at least once.
2383
+ // If we set it to `true` in an error scenario (e.g. 402 Over Quota, 401 Invalid Key, etc.),
2384
+ // any manual call to `loadFeatureFlags()` (without forceReload) will skip refetching entirely,
2385
+ // leaving us stuck with zero or outdated flags. The poller does keep running, but we also want
2386
+ // manual reloads to be possible as soon as the error condition is resolved.
2387
+ //
2388
+ // Therefore, on error statuses, we do *not* set `loadedSuccessfullyOnce = true`, ensuring that
2389
+ // both the background poller and any subsequent manual calls can keep trying to load flags
2390
+ // once the issue (quota, permission, rate limit, etc.) is resolved.
2391
+ switch (res.status) {
2392
+ case 401:
2393
+ // Invalid API key
2394
+ this.shouldBeginExponentialBackoff = true;
2395
+ this.backOffCount += 1;
2396
+ throw new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2397
+ case 402:
2398
+ // Quota exceeded - clear all flags
2399
+ console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');
2400
+ this.featureFlags = [];
2401
+ this.featureFlagsByKey = {};
2402
+ this.groupTypeMapping = {};
2403
+ this.cohorts = {};
2404
+ return;
2405
+ case 403:
2406
+ // Permissions issue
2407
+ this.shouldBeginExponentialBackoff = true;
2408
+ this.backOffCount += 1;
2409
+ throw new ClientError(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);
2410
+ case 429:
2411
+ // Rate limited
2412
+ this.shouldBeginExponentialBackoff = true;
2413
+ this.backOffCount += 1;
2414
+ throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
2415
+ case 200:
2416
+ {
2417
+ // Process successful response
2418
+ const responseJson = (await res.json()) ?? {};
2419
+ if (!('flags' in responseJson)) {
2420
+ this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
2421
+ return;
2422
+ }
2423
+ this.featureFlags = responseJson.flags ?? [];
2424
+ this.featureFlagsByKey = this.featureFlags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
2425
+ this.groupTypeMapping = responseJson.group_type_mapping || {};
2426
+ this.cohorts = responseJson.cohorts || {};
2427
+ this.loadedSuccessfullyOnce = true;
2428
+ this.shouldBeginExponentialBackoff = false;
2429
+ this.backOffCount = 0;
2430
+ this.onLoad?.(this.featureFlags.length);
2431
+ break;
2432
+ }
2433
+ default:
2434
+ // Something else went wrong, or the server is down.
2435
+ // In this case, don't override existing flags
2436
+ return;
2437
+ }
2438
+ } catch (err) {
2439
+ if (err instanceof ClientError) {
2440
+ this.onError?.(err);
2441
+ }
2442
+ }
2443
+ }
2444
+ getPersonalApiKeyRequestOptions(method = 'GET') {
2445
+ return {
2446
+ method,
2447
+ headers: {
2448
+ ...this.customHeaders,
2449
+ 'Content-Type': 'application/json',
2450
+ Authorization: `Bearer ${this.personalApiKey}`
2451
+ }
2452
+ };
2453
+ }
2454
+ async _requestFeatureFlagDefinitions() {
2455
+ const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
2456
+ const options = this.getPersonalApiKeyRequestOptions();
2457
+ let abortTimeout = null;
2458
+ if (this.timeout && typeof this.timeout === 'number') {
2459
+ const controller = new AbortController();
2460
+ abortTimeout = safeSetTimeout(() => {
2461
+ controller.abort();
2462
+ }, this.timeout);
2463
+ options.signal = controller.signal;
2464
+ }
2465
+ try {
2466
+ return await this.fetch(url, options);
2467
+ } finally {
2468
+ clearTimeout(abortTimeout);
2469
+ }
2470
+ }
2471
+ stopPoller() {
2472
+ clearTimeout(this.poller);
2473
+ }
2474
+ _requestRemoteConfigPayload(flagKey) {
2475
+ const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config/`;
2476
+ const options = this.getPersonalApiKeyRequestOptions();
2477
+ let abortTimeout = null;
2478
+ if (this.timeout && typeof this.timeout === 'number') {
2479
+ const controller = new AbortController();
2480
+ abortTimeout = safeSetTimeout(() => {
2481
+ controller.abort();
2482
+ }, this.timeout);
2483
+ options.signal = controller.signal;
2484
+ }
2485
+ try {
2486
+ return this.fetch(url, options);
2487
+ } finally {
2488
+ clearTimeout(abortTimeout);
2489
+ }
2490
+ }
2491
+ }
2492
+ // # This function takes a distinct_id and a feature flag key and returns a float between 0 and 1.
2493
+ // # Given the same distinct_id and key, it'll always return the same float. These floats are
2494
+ // # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic
2495
+ // # we can do _hash(key, distinct_id) < 0.2
2496
+ async function _hash(key, distinctId, salt = '') {
2497
+ const hashString = await hashSHA1(`${key}.${distinctId}${salt}`);
2498
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
2499
+ }
2500
+ function matchProperty(property, propertyValues, warnFunction) {
2501
+ const key = property.key;
2502
+ const value = property.value;
2503
+ const operator = property.operator || 'exact';
2504
+ if (!(key in propertyValues)) {
2505
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
2506
+ } else if (operator === 'is_not_set') {
2507
+ throw new InconclusiveMatchError(`Operator is_not_set is not supported`);
2508
+ }
2509
+ const overrideValue = propertyValues[key];
2510
+ if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
2511
+ // if the value is null, just fail the feature flag comparison
2512
+ // this isn't an InconclusiveMatchError because the property value was provided.
2513
+ if (warnFunction) {
2514
+ warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
2515
+ }
2516
+ return false;
2517
+ }
2518
+ function computeExactMatch(value, overrideValue) {
2519
+ if (Array.isArray(value)) {
2520
+ return value.map(val => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
2521
+ }
2522
+ return String(value).toLowerCase() === String(overrideValue).toLowerCase();
2523
+ }
2524
+ function compare(lhs, rhs, operator) {
2525
+ if (operator === 'gt') {
2526
+ return lhs > rhs;
2527
+ } else if (operator === 'gte') {
2528
+ return lhs >= rhs;
2529
+ } else if (operator === 'lt') {
2530
+ return lhs < rhs;
2531
+ } else if (operator === 'lte') {
2532
+ return lhs <= rhs;
2533
+ } else {
2534
+ throw new Error(`Invalid operator: ${operator}`);
2535
+ }
2536
+ }
2537
+ switch (operator) {
2538
+ case 'exact':
2539
+ return computeExactMatch(value, overrideValue);
2540
+ case 'is_not':
2541
+ return !computeExactMatch(value, overrideValue);
2542
+ case 'is_set':
2543
+ return key in propertyValues;
2544
+ case 'icontains':
2545
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2546
+ case 'not_icontains':
2547
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2548
+ case 'regex':
2549
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
2550
+ case 'not_regex':
2551
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
2552
+ case 'gt':
2553
+ case 'gte':
2554
+ case 'lt':
2555
+ case 'lte':
2556
+ {
2557
+ // :TRICKY: We adjust comparison based on the override value passed in,
2558
+ // to make sure we handle both numeric and string comparisons appropriately.
2559
+ let parsedValue = typeof value === 'number' ? value : null;
2560
+ if (typeof value === 'string') {
2561
+ try {
2562
+ parsedValue = parseFloat(value);
2563
+ } catch (err) {
2564
+ // pass
2565
+ }
2566
+ }
2567
+ if (parsedValue != null && overrideValue != null) {
2568
+ // check both null and undefined
2569
+ if (typeof overrideValue === 'string') {
2570
+ return compare(overrideValue, String(value), operator);
2571
+ } else {
2572
+ return compare(overrideValue, parsedValue, operator);
2573
+ }
2574
+ } else {
2575
+ return compare(String(overrideValue), String(value), operator);
2576
+ }
2577
+ }
2578
+ case 'is_date_after':
2579
+ case 'is_date_before':
2580
+ {
2581
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
2582
+ if (parsedDate == null) {
2583
+ parsedDate = convertToDateTime(value);
2584
+ }
2585
+ if (parsedDate == null) {
2586
+ throw new InconclusiveMatchError(`Invalid date: ${value}`);
2587
+ }
2588
+ const overrideDate = convertToDateTime(overrideValue);
2589
+ if (['is_date_before'].includes(operator)) {
2590
+ return overrideDate < parsedDate;
2591
+ }
2592
+ return overrideDate > parsedDate;
2593
+ }
2594
+ default:
2595
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
2596
+ }
2597
+ }
2598
+ function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
2599
+ const cohortId = String(property.value);
2600
+ if (!(cohortId in cohortProperties)) {
2601
+ throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
2602
+ }
2603
+ const propertyGroup = cohortProperties[cohortId];
2604
+ return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
2605
+ }
2606
+ function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
2607
+ if (!propertyGroup) {
2608
+ return true;
2609
+ }
2610
+ const propertyGroupType = propertyGroup.type;
2611
+ const properties = propertyGroup.values;
2612
+ if (!properties || properties.length === 0) {
2613
+ // empty groups are no-ops, always match
2614
+ return true;
2615
+ }
2616
+ let errorMatchingLocally = false;
2617
+ if ('values' in properties[0]) {
2618
+ // a nested property group
2619
+ for (const prop of properties) {
2620
+ try {
2621
+ const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
2622
+ if (propertyGroupType === 'AND') {
2623
+ if (!matches) {
2624
+ return false;
2625
+ }
2626
+ } else {
2627
+ // OR group
2628
+ if (matches) {
2629
+ return true;
2630
+ }
2631
+ }
2632
+ } catch (err) {
2633
+ if (err instanceof InconclusiveMatchError) {
2634
+ if (debugMode) {
2635
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
2636
+ }
2637
+ errorMatchingLocally = true;
2638
+ } else {
2639
+ throw err;
2640
+ }
2641
+ }
2642
+ }
2643
+ if (errorMatchingLocally) {
2644
+ throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
2645
+ }
2646
+ // if we get here, all matched in AND case, or none matched in OR case
2647
+ return propertyGroupType === 'AND';
2648
+ } else {
2649
+ for (const prop of properties) {
2650
+ try {
2651
+ let matches;
2652
+ if (prop.type === 'cohort') {
2653
+ matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
2654
+ } else {
2655
+ matches = matchProperty(prop, propertyValues);
2656
+ }
2657
+ const negation = prop.negation || false;
2658
+ if (propertyGroupType === 'AND') {
2659
+ // if negated property, do the inverse
2660
+ if (!matches && !negation) {
2661
+ return false;
2662
+ }
2663
+ if (matches && negation) {
2664
+ return false;
2665
+ }
2666
+ } else {
2667
+ // OR group
2668
+ if (matches && !negation) {
2669
+ return true;
2670
+ }
2671
+ if (!matches && negation) {
2672
+ return true;
2673
+ }
2674
+ }
2675
+ } catch (err) {
2676
+ if (err instanceof InconclusiveMatchError) {
2677
+ if (debugMode) {
2678
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
2679
+ }
2680
+ errorMatchingLocally = true;
2681
+ } else {
2682
+ throw err;
2683
+ }
2684
+ }
2685
+ }
2686
+ if (errorMatchingLocally) {
2687
+ throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
2688
+ }
2689
+ // if we get here, all matched in AND case, or none matched in OR case
2690
+ return propertyGroupType === 'AND';
2691
+ }
2692
+ }
2693
+ function isValidRegex(regex) {
2694
+ try {
2695
+ new RegExp(regex);
2696
+ return true;
2697
+ } catch (err) {
2698
+ return false;
2699
+ }
2700
+ }
2701
+ function convertToDateTime(value) {
2702
+ if (value instanceof Date) {
2703
+ return value;
2704
+ } else if (typeof value === 'string' || typeof value === 'number') {
2705
+ const date = new Date(value);
2706
+ if (!isNaN(date.valueOf())) {
2707
+ return date;
2708
+ }
2709
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
2710
+ } else {
2711
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
2712
+ }
2713
+ }
2714
+ function relativeDateParseForFeatureFlagMatching(value) {
2715
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
2716
+ const match = value.match(regex);
2717
+ const parsedDt = new Date(new Date().toISOString());
2718
+ if (match) {
2719
+ if (!match.groups) {
2720
+ return null;
2721
+ }
2722
+ const number = parseInt(match.groups['number']);
2723
+ if (number >= 10000) {
2724
+ // Guard against overflow, disallow numbers greater than 10_000
2725
+ return null;
2726
+ }
2727
+ const interval = match.groups['interval'];
2728
+ if (interval == 'h') {
2729
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
2730
+ } else if (interval == 'd') {
2731
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
2732
+ } else if (interval == 'w') {
2733
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number * 7);
2734
+ } else if (interval == 'm') {
2735
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
2736
+ } else if (interval == 'y') {
2737
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
2738
+ } else {
2739
+ return null;
2740
+ }
2741
+ return parsedDt;
2742
+ } else {
2743
+ return null;
2744
+ }
2745
+ }
2746
+
2747
+ class PostHogMemoryStorage {
2748
+ constructor() {
2749
+ this._memoryStorage = {};
2750
+ }
2751
+ getProperty(key) {
2752
+ return this._memoryStorage[key];
2753
+ }
2754
+ setProperty(key, value) {
2755
+ this._memoryStorage[key] = value !== null ? value : undefined;
2756
+ }
2757
+ }
2758
+
2759
+ // Standard local evaluation rate limit is 600 per minute (10 per second),
2760
+ // so the fastest a poller should ever be set is 100ms.
2761
+ const MINIMUM_POLLING_INTERVAL = 100;
2762
+ const THIRTY_SECONDS = 30 * 1000;
2763
+ const MAX_CACHE_SIZE = 50 * 1000;
2764
+ // The actual exported Nodejs API.
2765
+ class PostHogBackendClient extends PostHogCoreStateless {
2766
+ constructor(apiKey, options = {}) {
2767
+ super(apiKey, options);
2768
+ this._memoryStorage = new PostHogMemoryStorage();
2769
+ this.options = options;
2770
+ this.options.featureFlagsPollingInterval = typeof options.featureFlagsPollingInterval === 'number' ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
2771
+ if (options.personalApiKey) {
2772
+ if (options.personalApiKey.includes('phc_')) {
2773
+ throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
2774
+ }
2775
+ this.featureFlagsPoller = new FeatureFlagsPoller({
2776
+ pollingInterval: this.options.featureFlagsPollingInterval,
2777
+ personalApiKey: options.personalApiKey,
2778
+ projectApiKey: apiKey,
2779
+ timeout: options.requestTimeout ?? 10000,
2780
+ host: this.host,
2781
+ fetch: options.fetch,
2782
+ onError: err => {
2783
+ this._events.emit('error', err);
2784
+ },
2785
+ onLoad: count => {
2786
+ this._events.emit('localEvaluationFlagsLoaded', count);
2787
+ },
2788
+ customHeaders: this.getCustomHeaders()
2789
+ });
2790
+ }
2791
+ this.errorTracking = new ErrorTracking(this, options);
2792
+ this.distinctIdHasSentFlagCalls = {};
2793
+ this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
2794
+ }
2795
+ getPersistedProperty(key) {
2796
+ return this._memoryStorage.getProperty(key);
2797
+ }
2798
+ setPersistedProperty(key, value) {
2799
+ return this._memoryStorage.setProperty(key, value);
2800
+ }
2801
+ fetch(url, options) {
2802
+ return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
2803
+ }
2804
+ getLibraryVersion() {
2805
+ return version;
2806
+ }
2807
+ getCustomUserAgent() {
2808
+ return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
2809
+ }
2810
+ enable() {
2811
+ return super.optIn();
2812
+ }
2813
+ disable() {
2814
+ return super.optOut();
2815
+ }
2816
+ debug(enabled = true) {
2817
+ super.debug(enabled);
2818
+ this.featureFlagsPoller?.debug(enabled);
2819
+ }
2820
+ capture(props) {
2821
+ if (typeof props === 'string') {
2822
+ this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
2823
+ }
2824
+ const {
2825
+ distinctId,
2826
+ event,
2827
+ properties,
2828
+ groups,
2829
+ sendFeatureFlags,
2830
+ timestamp,
2831
+ disableGeoip,
2832
+ uuid
2833
+ } = props;
2834
+ const _capture = props => {
2835
+ super.captureStateless(distinctId, event, props, {
2836
+ timestamp,
2837
+ disableGeoip,
2838
+ uuid
2839
+ });
2840
+ };
2841
+ const _getFlags = async (distinctId, groups, disableGeoip) => {
2842
+ return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
2843
+ };
2844
+ // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush
2845
+ const capturePromise = Promise.resolve().then(async () => {
2846
+ if (sendFeatureFlags) {
2847
+ // If we are sending feature flags, we need to make sure we have the latest flags
2848
+ // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
2849
+ return await _getFlags(distinctId, groups, disableGeoip);
2850
+ }
2851
+ if (event === '$feature_flag_called') {
2852
+ // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.
2853
+ return {};
2854
+ }
2855
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
2856
+ // Otherwise we may as well check for the flags locally and include them if they are already loaded
2857
+ const groupsWithStringValues = {};
2858
+ for (const [key, value] of Object.entries(groups || {})) {
2859
+ groupsWithStringValues[key] = String(value);
2860
+ }
2861
+ return await this.getAllFlags(distinctId, {
2862
+ groups: groupsWithStringValues,
2863
+ disableGeoip,
2864
+ onlyEvaluateLocally: true
2865
+ });
2866
+ }
2867
+ return {};
2868
+ }).then(flags => {
2869
+ // Derive the relevant flag properties to add
2870
+ const additionalProperties = {};
2871
+ if (flags) {
2872
+ for (const [feature, variant] of Object.entries(flags)) {
2873
+ additionalProperties[`$feature/${feature}`] = variant;
2874
+ }
2875
+ }
2876
+ const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
2877
+ if (activeFlags.length > 0) {
2878
+ additionalProperties['$active_feature_flags'] = activeFlags;
2879
+ }
2880
+ return additionalProperties;
2881
+ }).catch(() => {
2882
+ // Something went wrong getting the flag info - we should capture the event anyways
2883
+ return {};
2884
+ }).then(additionalProperties => {
2885
+ // No matter what - capture the event
2886
+ _capture({
2887
+ ...additionalProperties,
2888
+ ...properties,
2889
+ $groups: groups
2890
+ });
2891
+ });
2892
+ this.addPendingPromise(capturePromise);
2893
+ }
2894
+ async captureImmediate(props) {
2895
+ if (typeof props === 'string') {
2896
+ this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
2897
+ }
2898
+ const {
2899
+ distinctId,
2900
+ event,
2901
+ properties,
2902
+ groups,
2903
+ sendFeatureFlags,
2904
+ timestamp,
2905
+ disableGeoip,
2906
+ uuid
2907
+ } = props;
2908
+ const _capture = props => {
2909
+ return super.captureStatelessImmediate(distinctId, event, props, {
2910
+ timestamp,
2911
+ disableGeoip,
2912
+ uuid
2913
+ });
2914
+ };
2915
+ const _getFlags = async (distinctId, groups, disableGeoip) => {
2916
+ return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
2917
+ };
2918
+ const capturePromise = Promise.resolve().then(async () => {
2919
+ if (sendFeatureFlags) {
2920
+ // If we are sending feature flags, we need to make sure we have the latest flags
2921
+ // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
2922
+ return await _getFlags(distinctId, groups, disableGeoip);
2923
+ }
2924
+ if (event === '$feature_flag_called') {
2925
+ // If we're capturing a $feature_flag_called event, we don't want to enrich the event with cached flags that may be out of date.
2926
+ return {};
2927
+ }
2928
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
2929
+ // Otherwise we may as well check for the flags locally and include them if they are already loaded
2930
+ const groupsWithStringValues = {};
2931
+ for (const [key, value] of Object.entries(groups || {})) {
2932
+ groupsWithStringValues[key] = String(value);
2933
+ }
2934
+ return await this.getAllFlags(distinctId, {
2935
+ groups: groupsWithStringValues,
2936
+ disableGeoip,
2937
+ onlyEvaluateLocally: true
2938
+ });
2939
+ }
2940
+ return {};
2941
+ }).then(flags => {
2942
+ // Derive the relevant flag properties to add
2943
+ const additionalProperties = {};
2944
+ if (flags) {
2945
+ for (const [feature, variant] of Object.entries(flags)) {
2946
+ additionalProperties[`$feature/${feature}`] = variant;
2947
+ }
2948
+ }
2949
+ const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
2950
+ if (activeFlags.length > 0) {
2951
+ additionalProperties['$active_feature_flags'] = activeFlags;
2952
+ }
2953
+ return additionalProperties;
2954
+ }).catch(() => {
2955
+ // Something went wrong getting the flag info - we should capture the event anyways
2956
+ return {};
2957
+ }).then(additionalProperties => {
2958
+ // No matter what - capture the event
2959
+ _capture({
2960
+ ...additionalProperties,
2961
+ ...properties,
2962
+ $groups: groups
2963
+ });
2964
+ });
2965
+ await capturePromise;
2966
+ }
2967
+ identify({
2968
+ distinctId,
2969
+ properties,
2970
+ disableGeoip
2971
+ }) {
2972
+ // Catch properties passed as $set and move them to the top level
2973
+ // promote $set and $set_once to top level
2974
+ const userPropsOnce = properties?.$set_once;
2975
+ delete properties?.$set_once;
2976
+ // if no $set is provided we assume all properties are $set
2977
+ const userProps = properties?.$set || properties;
2978
+ super.identifyStateless(distinctId, {
2979
+ $set: userProps,
2980
+ $set_once: userPropsOnce
2981
+ }, {
2982
+ disableGeoip
2983
+ });
2984
+ }
2985
+ async identifyImmediate({
2986
+ distinctId,
2987
+ properties,
2988
+ disableGeoip
2989
+ }) {
2990
+ // promote $set and $set_once to top level
2991
+ const userPropsOnce = properties?.$set_once;
2992
+ delete properties?.$set_once;
2993
+ // if no $set is provided we assume all properties are $set
2994
+ const userProps = properties?.$set || properties;
2995
+ await super.identifyStatelessImmediate(distinctId, {
2996
+ $set: userProps,
2997
+ $set_once: userPropsOnce
2998
+ }, {
2999
+ disableGeoip
3000
+ });
3001
+ }
3002
+ alias(data) {
3003
+ super.aliasStateless(data.alias, data.distinctId, undefined, {
3004
+ disableGeoip: data.disableGeoip
3005
+ });
3006
+ }
3007
+ async aliasImmediate(data) {
3008
+ await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
3009
+ disableGeoip: data.disableGeoip
3010
+ });
3011
+ }
3012
+ isLocalEvaluationReady() {
3013
+ return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
3014
+ }
3015
+ async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
3016
+ if (this.isLocalEvaluationReady()) {
3017
+ return true;
3018
+ }
3019
+ if (this.featureFlagsPoller === undefined) {
3020
+ return false;
3021
+ }
3022
+ return new Promise(resolve => {
3023
+ const timeout = setTimeout(() => {
3024
+ cleanup();
3025
+ resolve(false);
3026
+ }, timeoutMs);
3027
+ const cleanup = this._events.on('localEvaluationFlagsLoaded', count => {
3028
+ clearTimeout(timeout);
3029
+ cleanup();
3030
+ resolve(count > 0);
3031
+ });
3032
+ });
3033
+ }
3034
+ async getFeatureFlag(key, distinctId, options) {
3035
+ const {
3036
+ groups,
3037
+ disableGeoip
3038
+ } = options || {};
3039
+ let {
3040
+ onlyEvaluateLocally,
3041
+ sendFeatureFlagEvents,
3042
+ personProperties,
3043
+ groupProperties
3044
+ } = options || {};
3045
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3046
+ personProperties = adjustedProperties.allPersonProperties;
3047
+ groupProperties = adjustedProperties.allGroupProperties;
3048
+ // set defaults
3049
+ if (onlyEvaluateLocally == undefined) {
3050
+ onlyEvaluateLocally = false;
3051
+ }
3052
+ if (sendFeatureFlagEvents == undefined) {
3053
+ sendFeatureFlagEvents = true;
3054
+ }
3055
+ let response = await this.featureFlagsPoller?.getFeatureFlag(key, distinctId, groups, personProperties, groupProperties);
3056
+ const flagWasLocallyEvaluated = response !== undefined;
3057
+ let requestId = undefined;
3058
+ let flagDetail = undefined;
3059
+ if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
3060
+ const remoteResponse = await super.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3061
+ if (remoteResponse === undefined) {
3062
+ return undefined;
3063
+ }
3064
+ flagDetail = remoteResponse.response;
3065
+ response = getFeatureFlagValue(flagDetail);
3066
+ requestId = remoteResponse?.requestId;
3067
+ }
3068
+ const featureFlagReportedKey = `${key}_${response}`;
3069
+ if (sendFeatureFlagEvents && (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))) {
3070
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) {
3071
+ this.distinctIdHasSentFlagCalls = {};
3072
+ }
3073
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) {
3074
+ this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
3075
+ } else {
3076
+ this.distinctIdHasSentFlagCalls[distinctId] = [featureFlagReportedKey];
3077
+ }
3078
+ this.capture({
3079
+ distinctId,
3080
+ event: '$feature_flag_called',
3081
+ properties: {
3082
+ $feature_flag: key,
3083
+ $feature_flag_response: response,
3084
+ $feature_flag_id: flagDetail?.metadata?.id,
3085
+ $feature_flag_version: flagDetail?.metadata?.version,
3086
+ $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,
3087
+ locally_evaluated: flagWasLocallyEvaluated,
3088
+ [`$feature/${key}`]: response,
3089
+ $feature_flag_request_id: requestId
3090
+ },
3091
+ groups,
3092
+ disableGeoip
3093
+ });
3094
+ }
3095
+ return response;
3096
+ }
3097
+ async getFeatureFlagPayload(key, distinctId, matchValue, options) {
3098
+ const {
3099
+ groups,
3100
+ disableGeoip
3101
+ } = options || {};
3102
+ let {
3103
+ onlyEvaluateLocally,
3104
+ sendFeatureFlagEvents,
3105
+ personProperties,
3106
+ groupProperties
3107
+ } = options || {};
3108
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3109
+ personProperties = adjustedProperties.allPersonProperties;
3110
+ groupProperties = adjustedProperties.allGroupProperties;
3111
+ let response = undefined;
3112
+ const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
3113
+ if (localEvaluationEnabled) {
3114
+ // Try to get match value locally if not provided
3115
+ if (!matchValue) {
3116
+ matchValue = await this.getFeatureFlag(key, distinctId, {
3117
+ ...options,
3118
+ onlyEvaluateLocally: true,
3119
+ sendFeatureFlagEvents: false
3120
+ });
3121
+ }
3122
+ if (matchValue) {
3123
+ response = await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(key, matchValue);
3124
+ }
3125
+ }
3126
+ //}
3127
+ // set defaults
3128
+ if (onlyEvaluateLocally == undefined) {
3129
+ onlyEvaluateLocally = false;
3130
+ }
3131
+ if (sendFeatureFlagEvents == undefined) {
3132
+ sendFeatureFlagEvents = true;
3133
+ }
3134
+ // set defaults
3135
+ if (onlyEvaluateLocally == undefined) {
3136
+ onlyEvaluateLocally = false;
3137
+ }
3138
+ const payloadWasLocallyEvaluated = response !== undefined;
3139
+ if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) {
3140
+ response = await super.getFeatureFlagPayloadStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3141
+ }
3142
+ return response;
3143
+ }
3144
+ async getRemoteConfigPayload(flagKey) {
3145
+ return (await this.featureFlagsPoller?._requestRemoteConfigPayload(flagKey))?.json();
3146
+ }
3147
+ async isFeatureEnabled(key, distinctId, options) {
3148
+ const feat = await this.getFeatureFlag(key, distinctId, options);
3149
+ if (feat === undefined) {
3150
+ return undefined;
3151
+ }
3152
+ return !!feat || false;
3153
+ }
3154
+ async getAllFlags(distinctId, options) {
3155
+ const response = await this.getAllFlagsAndPayloads(distinctId, options);
3156
+ return response.featureFlags || {};
3157
+ }
3158
+ async getAllFlagsAndPayloads(distinctId, options) {
3159
+ const {
3160
+ groups,
3161
+ disableGeoip
3162
+ } = options || {};
3163
+ let {
3164
+ onlyEvaluateLocally,
3165
+ personProperties,
3166
+ groupProperties
3167
+ } = options || {};
3168
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3169
+ personProperties = adjustedProperties.allPersonProperties;
3170
+ groupProperties = adjustedProperties.allGroupProperties;
3171
+ // set defaults
3172
+ if (onlyEvaluateLocally == undefined) {
3173
+ onlyEvaluateLocally = false;
3174
+ }
3175
+ const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(distinctId, groups, personProperties, groupProperties);
3176
+ let featureFlags = {};
3177
+ let featureFlagPayloads = {};
3178
+ let fallbackToFlags = true;
3179
+ if (localEvaluationResult) {
3180
+ featureFlags = localEvaluationResult.response;
3181
+ featureFlagPayloads = localEvaluationResult.payloads;
3182
+ fallbackToFlags = localEvaluationResult.fallbackToFlags;
3183
+ }
3184
+ if (fallbackToFlags && !onlyEvaluateLocally) {
3185
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
3186
+ featureFlags = {
3187
+ ...featureFlags,
3188
+ ...(remoteEvaluationResult.flags || {})
3189
+ };
3190
+ featureFlagPayloads = {
3191
+ ...featureFlagPayloads,
3192
+ ...(remoteEvaluationResult.payloads || {})
3193
+ };
3194
+ }
3195
+ return {
3196
+ featureFlags,
3197
+ featureFlagPayloads
3198
+ };
3199
+ }
3200
+ groupIdentify({
3201
+ groupType,
3202
+ groupKey,
3203
+ properties,
3204
+ distinctId,
3205
+ disableGeoip
3206
+ }) {
3207
+ super.groupIdentifyStateless(groupType, groupKey, properties, {
3208
+ disableGeoip
3209
+ }, distinctId);
3210
+ }
3211
+ /**
3212
+ * Reloads the feature flag definitions from the server for local evaluation.
3213
+ * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
3214
+ */
3215
+ async reloadFeatureFlags() {
3216
+ await this.featureFlagsPoller?.loadFeatureFlags(true);
3217
+ }
3218
+ async _shutdown(shutdownTimeoutMs) {
3219
+ this.featureFlagsPoller?.stopPoller();
3220
+ return super._shutdown(shutdownTimeoutMs);
3221
+ }
3222
+ addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3223
+ const allPersonProperties = {
3224
+ distinct_id: distinctId,
3225
+ ...(personProperties || {})
3226
+ };
3227
+ const allGroupProperties = {};
3228
+ if (groups) {
3229
+ for (const groupName of Object.keys(groups)) {
3230
+ allGroupProperties[groupName] = {
3231
+ $group_key: groups[groupName],
3232
+ ...(groupProperties?.[groupName] || {})
3233
+ };
3234
+ }
3235
+ }
3236
+ return {
3237
+ allPersonProperties,
3238
+ allGroupProperties
3239
+ };
3240
+ }
3241
+ captureException(error, distinctId, additionalProperties) {
3242
+ const syntheticException = new Error('PostHog syntheticException');
3243
+ ErrorTracking.captureException(this, error, {
3244
+ syntheticException
3245
+ }, distinctId, additionalProperties);
3246
+ }
3247
+ }
3248
+
3249
+ // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
3250
+ // Licensed under the MIT License
3251
+ // This was originally forked from https://github.com/csnover/TraceKit, and was largely
3252
+ // re-written as part of raven - js.
3253
+ //
3254
+ // This code was later copied to the JavaScript mono - repo and further modified and
3255
+ // refactored over the years.
3256
+ // Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.
3257
+ //
3258
+ // Permission is hereby granted, free of charge, to any person obtaining a copy of this
3259
+ // software and associated documentation files(the 'Software'), to deal in the Software
3260
+ // without restriction, including without limitation the rights to use, copy, modify,
3261
+ // merge, publish, distribute, sublicense, and / or sell copies of the Software, and to
3262
+ // permit persons to whom the Software is furnished to do so, subject to the following
3263
+ // conditions:
3264
+ //
3265
+ // The above copyright notice and this permission notice shall be included in all copies
3266
+ // or substantial portions of the Software.
3267
+ //
3268
+ // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
3269
+ // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
3270
+ // PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
3271
+ // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
3272
+ // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
3273
+ // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
3274
+ const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
3275
+ const STACKTRACE_FRAME_LIMIT = 50;
3276
+ const UNKNOWN_FUNCTION = '?';
3277
+ /** Node Stack line parser */
3278
+ function node(getModule) {
3279
+ const FILENAME_MATCH = /^\s*[-]{4,}$/;
3280
+ const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
3281
+ return line => {
3282
+ const lineMatch = line.match(FULL_MATCH);
3283
+ if (lineMatch) {
3284
+ let object;
3285
+ let method;
3286
+ let functionName;
3287
+ let typeName;
3288
+ let methodName;
3289
+ if (lineMatch[1]) {
3290
+ functionName = lineMatch[1];
3291
+ let methodStart = functionName.lastIndexOf('.');
3292
+ if (functionName[methodStart - 1] === '.') {
3293
+ methodStart--;
3294
+ }
3295
+ if (methodStart > 0) {
3296
+ object = functionName.slice(0, methodStart);
3297
+ method = functionName.slice(methodStart + 1);
3298
+ const objectEnd = object.indexOf('.Module');
3299
+ if (objectEnd > 0) {
3300
+ functionName = functionName.slice(objectEnd + 1);
3301
+ object = object.slice(0, objectEnd);
3302
+ }
3303
+ }
3304
+ typeName = undefined;
3305
+ }
3306
+ if (method) {
3307
+ typeName = object;
3308
+ methodName = method;
3309
+ }
3310
+ if (method === '<anonymous>') {
3311
+ methodName = undefined;
3312
+ functionName = undefined;
3313
+ }
3314
+ if (functionName === undefined) {
3315
+ methodName = methodName || UNKNOWN_FUNCTION;
3316
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
3317
+ }
3318
+ let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];
3319
+ const isNative = lineMatch[5] === 'native';
3320
+ // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`
3321
+ if (filename?.match(/\/[A-Z]:/)) {
3322
+ filename = filename.slice(1);
3323
+ }
3324
+ if (!filename && lineMatch[5] && !isNative) {
3325
+ filename = lineMatch[5];
3326
+ }
3327
+ return {
3328
+ filename: filename ? decodeURI(filename) : undefined,
3329
+ module: getModule ? getModule(filename) : undefined,
3330
+ function: functionName,
3331
+ lineno: _parseIntOrUndefined(lineMatch[3]),
3332
+ colno: _parseIntOrUndefined(lineMatch[4]),
3333
+ in_app: filenameIsInApp(filename || '', isNative),
3334
+ platform: 'node:javascript'
3335
+ };
3336
+ }
3337
+ if (line.match(FILENAME_MATCH)) {
3338
+ return {
3339
+ filename: line,
3340
+ platform: 'node:javascript'
3341
+ };
3342
+ }
3343
+ return undefined;
3344
+ };
3345
+ }
3346
+ /**
3347
+ * Does this filename look like it's part of the app code?
3348
+ */
3349
+ function filenameIsInApp(filename, isNative = false) {
3350
+ const isInternal = isNative || filename &&
3351
+ // It's not internal if it's an absolute linux path
3352
+ !filename.startsWith('/') &&
3353
+ // It's not internal if it's an absolute windows path
3354
+ !filename.match(/^[A-Z]:/) &&
3355
+ // It's not internal if the path is starting with a dot
3356
+ !filename.startsWith('.') &&
3357
+ // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
3358
+ !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); // Schema from: https://stackoverflow.com/a/3641782
3359
+ // in_app is all that's not an internal Node function or a module within node_modules
3360
+ // note that isNative appears to return true even for node core libraries
3361
+ // see https://github.com/getsentry/raven-node/issues/176
3362
+ return !isInternal && filename !== undefined && !filename.includes('node_modules/');
3363
+ }
3364
+ function _parseIntOrUndefined(input) {
3365
+ return parseInt(input || '', 10) || undefined;
3366
+ }
3367
+ function nodeStackLineParser(getModule) {
3368
+ return [90, node(getModule)];
3369
+ }
3370
+ function createStackParser(getModule) {
3371
+ const parsers = [nodeStackLineParser(getModule)];
3372
+ const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
3373
+ return (stack, skipFirstLines = 0) => {
3374
+ const frames = [];
3375
+ const lines = stack.split('\n');
3376
+ for (let i = skipFirstLines; i < lines.length; i++) {
3377
+ const line = lines[i];
3378
+ // Ignore lines over 1kb as they are unlikely to be stack frames.
3379
+ if (line.length > 1024) {
3380
+ continue;
3381
+ }
3382
+ // https://github.com/getsentry/sentry-javascript/issues/5459
3383
+ // Remove webpack (error: *) wrappers
3384
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
3385
+ // https://github.com/getsentry/sentry-javascript/issues/7813
3386
+ // Skip Error: lines
3387
+ if (cleanedLine.match(/\S*Error: /)) {
3388
+ continue;
3389
+ }
3390
+ for (const parser of sortedParsers) {
3391
+ const frame = parser(cleanedLine);
3392
+ if (frame) {
3393
+ frames.push(frame);
3394
+ break;
3395
+ }
3396
+ }
3397
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) {
3398
+ break;
3399
+ }
3400
+ }
3401
+ return reverseAndStripFrames(frames);
3402
+ };
3403
+ }
3404
+ function reverseAndStripFrames(stack) {
3405
+ if (!stack.length) {
3406
+ return [];
3407
+ }
3408
+ const localStack = Array.from(stack);
3409
+ localStack.reverse();
3410
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
3411
+ ...frame,
3412
+ filename: frame.filename || getLastStackFrame(localStack).filename,
3413
+ function: frame.function || UNKNOWN_FUNCTION
3414
+ }));
3415
+ }
3416
+ function getLastStackFrame(arr) {
3417
+ return arr[arr.length - 1] || {};
3418
+ }
3419
+
3420
+ ErrorTracking.stackParser = createStackParser();
3421
+ ErrorTracking.frameModifiers = [];
3422
+ class PostHog extends PostHogBackendClient {
3423
+ getLibraryId() {
3424
+ return 'posthog-edge';
3425
+ }
3426
+ }
3427
+
3428
+ export { PostHog, PostHogSentryIntegration, createEventProcessor, sentryIntegration, setupExpressErrorHandler };
3429
+ //# sourceMappingURL=index.mjs.map