@posthog/ai 4.3.2 → 4.4.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.
@@ -1,6 +1,4 @@
1
- import { posix, dirname, sep } from 'path';
2
- import { createReadStream } from 'node:fs';
3
- import { createInterface } from 'node:readline';
1
+ import { PostHog } from 'posthog-node';
4
2
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
5
3
  import { Serialized } from '@langchain/core/load/serializable';
6
4
  import { ChainValues } from '@langchain/core/utils/types';
@@ -9,4166 +7,6 @@ import { LLMResult } from '@langchain/core/outputs';
9
7
  import { AgentAction, AgentFinish } from '@langchain/core/agents';
10
8
  import { DocumentInterface } from '@langchain/core/documents';
11
9
 
12
- // vendor from: https://github.com/LiosK/uuidv7/blob/f30b7a7faff73afbce0b27a46c638310f96912ba/src/index.ts
13
- // https://github.com/LiosK/uuidv7#license
14
- /**
15
- * uuidv7: An experimental implementation of the proposed UUID Version 7
16
- *
17
- * @license Apache-2.0
18
- * @copyright 2021-2023 LiosK
19
- * @packageDocumentation
20
- */
21
- const DIGITS = "0123456789abcdef";
22
- /** Represents a UUID as a 16-byte byte array. */
23
- class UUID {
24
- /** @param bytes - The 16-byte byte array representation. */
25
- constructor(bytes) {
26
- this.bytes = bytes;
27
- }
28
- /**
29
- * Creates an object from the internal representation, a 16-byte byte array
30
- * containing the binary UUID representation in the big-endian byte order.
31
- *
32
- * This method does NOT shallow-copy the argument, and thus the created object
33
- * holds the reference to the underlying buffer.
34
- *
35
- * @throws TypeError if the length of the argument is not 16.
36
- */
37
- static ofInner(bytes) {
38
- if (bytes.length !== 16) {
39
- throw new TypeError("not 128-bit length");
40
- }
41
- else {
42
- return new UUID(bytes);
43
- }
44
- }
45
- /**
46
- * Builds a byte array from UUIDv7 field values.
47
- *
48
- * @param unixTsMs - A 48-bit `unix_ts_ms` field value.
49
- * @param randA - A 12-bit `rand_a` field value.
50
- * @param randBHi - The higher 30 bits of 62-bit `rand_b` field value.
51
- * @param randBLo - The lower 32 bits of 62-bit `rand_b` field value.
52
- * @throws RangeError if any field value is out of the specified range.
53
- */
54
- static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
55
- if (!Number.isInteger(unixTsMs) ||
56
- !Number.isInteger(randA) ||
57
- !Number.isInteger(randBHi) ||
58
- !Number.isInteger(randBLo) ||
59
- unixTsMs < 0 ||
60
- randA < 0 ||
61
- randBHi < 0 ||
62
- randBLo < 0 ||
63
- unixTsMs > 281474976710655 ||
64
- randA > 0xfff ||
65
- randBHi > 1073741823 ||
66
- randBLo > 4294967295) {
67
- throw new RangeError("invalid field value");
68
- }
69
- const bytes = new Uint8Array(16);
70
- bytes[0] = unixTsMs / 2 ** 40;
71
- bytes[1] = unixTsMs / 2 ** 32;
72
- bytes[2] = unixTsMs / 2 ** 24;
73
- bytes[3] = unixTsMs / 2 ** 16;
74
- bytes[4] = unixTsMs / 2 ** 8;
75
- bytes[5] = unixTsMs;
76
- bytes[6] = 0x70 | (randA >>> 8);
77
- bytes[7] = randA;
78
- bytes[8] = 0x80 | (randBHi >>> 24);
79
- bytes[9] = randBHi >>> 16;
80
- bytes[10] = randBHi >>> 8;
81
- bytes[11] = randBHi;
82
- bytes[12] = randBLo >>> 24;
83
- bytes[13] = randBLo >>> 16;
84
- bytes[14] = randBLo >>> 8;
85
- bytes[15] = randBLo;
86
- return new UUID(bytes);
87
- }
88
- /**
89
- * Builds a byte array from a string representation.
90
- *
91
- * This method accepts the following formats:
92
- *
93
- * - 32-digit hexadecimal format without hyphens: `0189dcd553117d408db09496a2eef37b`
94
- * - 8-4-4-4-12 hyphenated format: `0189dcd5-5311-7d40-8db0-9496a2eef37b`
95
- * - Hyphenated format with surrounding braces: `{0189dcd5-5311-7d40-8db0-9496a2eef37b}`
96
- * - RFC 4122 URN format: `urn:uuid:0189dcd5-5311-7d40-8db0-9496a2eef37b`
97
- *
98
- * Leading and trailing whitespaces represents an error.
99
- *
100
- * @throws SyntaxError if the argument could not parse as a valid UUID string.
101
- */
102
- static parse(uuid) {
103
- let hex = undefined;
104
- switch (uuid.length) {
105
- case 32:
106
- hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
107
- break;
108
- case 36:
109
- hex =
110
- /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
111
- .exec(uuid)
112
- ?.slice(1, 6)
113
- .join("");
114
- break;
115
- case 38:
116
- hex =
117
- /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i
118
- .exec(uuid)
119
- ?.slice(1, 6)
120
- .join("");
121
- break;
122
- case 45:
123
- hex =
124
- /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i
125
- .exec(uuid)
126
- ?.slice(1, 6)
127
- .join("");
128
- break;
129
- }
130
- if (hex) {
131
- const inner = new Uint8Array(16);
132
- for (let i = 0; i < 16; i += 4) {
133
- const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
134
- inner[i + 0] = n >>> 24;
135
- inner[i + 1] = n >>> 16;
136
- inner[i + 2] = n >>> 8;
137
- inner[i + 3] = n;
138
- }
139
- return new UUID(inner);
140
- }
141
- else {
142
- throw new SyntaxError("could not parse UUID string");
143
- }
144
- }
145
- /**
146
- * @returns The 8-4-4-4-12 canonical hexadecimal string representation
147
- * (`0189dcd5-5311-7d40-8db0-9496a2eef37b`).
148
- */
149
- toString() {
150
- let text = "";
151
- for (let i = 0; i < this.bytes.length; i++) {
152
- text += DIGITS.charAt(this.bytes[i] >>> 4);
153
- text += DIGITS.charAt(this.bytes[i] & 0xf);
154
- if (i === 3 || i === 5 || i === 7 || i === 9) {
155
- text += "-";
156
- }
157
- }
158
- return text;
159
- }
160
- /**
161
- * @returns The 32-digit hexadecimal representation without hyphens
162
- * (`0189dcd553117d408db09496a2eef37b`).
163
- */
164
- toHex() {
165
- let text = "";
166
- for (let i = 0; i < this.bytes.length; i++) {
167
- text += DIGITS.charAt(this.bytes[i] >>> 4);
168
- text += DIGITS.charAt(this.bytes[i] & 0xf);
169
- }
170
- return text;
171
- }
172
- /** @returns The 8-4-4-4-12 canonical hexadecimal string representation. */
173
- toJSON() {
174
- return this.toString();
175
- }
176
- /**
177
- * Reports the variant field value of the UUID or, if appropriate, "NIL" or
178
- * "MAX".
179
- *
180
- * For convenience, this method reports "NIL" or "MAX" if `this` represents
181
- * the Nil or Max UUID, although the Nil and Max UUIDs are technically
182
- * subsumed under the variants `0b0` and `0b111`, respectively.
183
- */
184
- getVariant() {
185
- const n = this.bytes[8] >>> 4;
186
- if (n < 0) {
187
- throw new Error("unreachable");
188
- }
189
- else if (n <= 0b0111) {
190
- return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
191
- }
192
- else if (n <= 0b1011) {
193
- return "VAR_10";
194
- }
195
- else if (n <= 0b1101) {
196
- return "VAR_110";
197
- }
198
- else if (n <= 0b1111) {
199
- return this.bytes.every((e) => e === 0xff) ? "MAX" : "VAR_RESERVED";
200
- }
201
- else {
202
- throw new Error("unreachable");
203
- }
204
- }
205
- /**
206
- * Returns the version field value of the UUID or `undefined` if the UUID does
207
- * not have the variant field value of `0b10`.
208
- */
209
- getVersion() {
210
- return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
211
- }
212
- /** Creates an object from `this`. */
213
- clone() {
214
- return new UUID(this.bytes.slice(0));
215
- }
216
- /** Returns true if `this` is equivalent to `other`. */
217
- equals(other) {
218
- return this.compareTo(other) === 0;
219
- }
220
- /**
221
- * Returns a negative integer, zero, or positive integer if `this` is less
222
- * than, equal to, or greater than `other`, respectively.
223
- */
224
- compareTo(other) {
225
- for (let i = 0; i < 16; i++) {
226
- const diff = this.bytes[i] - other.bytes[i];
227
- if (diff !== 0) {
228
- return Math.sign(diff);
229
- }
230
- }
231
- return 0;
232
- }
233
- }
234
- /**
235
- * Encapsulates the monotonic counter state.
236
- *
237
- * This class provides APIs to utilize a separate counter state from that of the
238
- * global generator used by {@link uuidv7} and {@link uuidv7obj}. In addition to
239
- * the default {@link generate} method, this class has {@link generateOrAbort}
240
- * that is useful to absolutely guarantee the monotonically increasing order of
241
- * generated UUIDs. See their respective documentation for details.
242
- */
243
- class V7Generator {
244
- /**
245
- * Creates a generator object with the default random number generator, or
246
- * with the specified one if passed as an argument. The specified random
247
- * number generator should be cryptographically strong and securely seeded.
248
- */
249
- constructor(randomNumberGenerator) {
250
- this.timestamp = 0;
251
- this.counter = 0;
252
- this.random = randomNumberGenerator ?? getDefaultRandom();
253
- }
254
- /**
255
- * Generates a new UUIDv7 object from the current timestamp, or resets the
256
- * generator upon significant timestamp rollback.
257
- *
258
- * This method returns a monotonically increasing UUID by reusing the previous
259
- * timestamp even if the up-to-date timestamp is smaller than the immediately
260
- * preceding UUID's. However, when such a clock rollback is considered
261
- * significant (i.e., by more than ten seconds), this method resets the
262
- * generator and returns a new UUID based on the given timestamp, breaking the
263
- * increasing order of UUIDs.
264
- *
265
- * See {@link generateOrAbort} for the other mode of generation and
266
- * {@link generateOrResetCore} for the low-level primitive.
267
- */
268
- generate() {
269
- return this.generateOrResetCore(Date.now(), 10000);
270
- }
271
- /**
272
- * Generates a new UUIDv7 object from the current timestamp, or returns
273
- * `undefined` upon significant timestamp rollback.
274
- *
275
- * This method returns a monotonically increasing UUID by reusing the previous
276
- * timestamp even if the up-to-date timestamp is smaller than the immediately
277
- * preceding UUID's. However, when such a clock rollback is considered
278
- * significant (i.e., by more than ten seconds), this method aborts and
279
- * returns `undefined` immediately.
280
- *
281
- * See {@link generate} for the other mode of generation and
282
- * {@link generateOrAbortCore} for the low-level primitive.
283
- */
284
- generateOrAbort() {
285
- return this.generateOrAbortCore(Date.now(), 10000);
286
- }
287
- /**
288
- * Generates a new UUIDv7 object from the `unixTsMs` passed, or resets the
289
- * generator upon significant timestamp rollback.
290
- *
291
- * This method is equivalent to {@link generate} except that it takes a custom
292
- * timestamp and clock rollback allowance.
293
- *
294
- * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
295
- * considered significant. A suggested value is `10_000` (milliseconds).
296
- * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
297
- */
298
- generateOrResetCore(unixTsMs, rollbackAllowance) {
299
- let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
300
- if (value === undefined) {
301
- // reset state and resume
302
- this.timestamp = 0;
303
- value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
304
- }
305
- return value;
306
- }
307
- /**
308
- * Generates a new UUIDv7 object from the `unixTsMs` passed, or returns
309
- * `undefined` upon significant timestamp rollback.
310
- *
311
- * This method is equivalent to {@link generateOrAbort} except that it takes a
312
- * custom timestamp and clock rollback allowance.
313
- *
314
- * @param rollbackAllowance - The amount of `unixTsMs` rollback that is
315
- * considered significant. A suggested value is `10_000` (milliseconds).
316
- * @throws RangeError if `unixTsMs` is not a 48-bit positive integer.
317
- */
318
- generateOrAbortCore(unixTsMs, rollbackAllowance) {
319
- const MAX_COUNTER = 4398046511103;
320
- if (!Number.isInteger(unixTsMs) ||
321
- unixTsMs < 1 ||
322
- unixTsMs > 281474976710655) {
323
- throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
324
- }
325
- else if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) {
326
- throw new RangeError("`rollbackAllowance` out of reasonable range");
327
- }
328
- if (unixTsMs > this.timestamp) {
329
- this.timestamp = unixTsMs;
330
- this.resetCounter();
331
- }
332
- else if (unixTsMs + rollbackAllowance >= this.timestamp) {
333
- // go on with previous timestamp if new one is not much smaller
334
- this.counter++;
335
- if (this.counter > MAX_COUNTER) {
336
- // increment timestamp at counter overflow
337
- this.timestamp++;
338
- this.resetCounter();
339
- }
340
- }
341
- else {
342
- // abort if clock went backwards to unbearable extent
343
- return undefined;
344
- }
345
- return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & (2 ** 30 - 1), this.random.nextUint32());
346
- }
347
- /** Initializes the counter at a 42-bit random integer. */
348
- resetCounter() {
349
- this.counter =
350
- this.random.nextUint32() * 0x400 + (this.random.nextUint32() & 0x3ff);
351
- }
352
- /**
353
- * Generates a new UUIDv4 object utilizing the random number generator inside.
354
- *
355
- * @internal
356
- */
357
- generateV4() {
358
- const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
359
- bytes[6] = 0x40 | (bytes[6] >>> 4);
360
- bytes[8] = 0x80 | (bytes[8] >>> 2);
361
- return UUID.ofInner(bytes);
362
- }
363
- }
364
- /** A global flag to force use of cryptographically strong RNG. */
365
- // declare const UUIDV7_DENY_WEAK_RNG: boolean;
366
- /** Returns the default random number generator available in the environment. */
367
- const getDefaultRandom = () => {
368
- // fix: crypto isn't available in react-native, always use Math.random
369
- // // detect Web Crypto API
370
- // if (
371
- // typeof crypto !== "undefined" &&
372
- // typeof crypto.getRandomValues !== "undefined"
373
- // ) {
374
- // return new BufferedCryptoRandom();
375
- // } else {
376
- // // fall back on Math.random() unless the flag is set to true
377
- // if (typeof UUIDV7_DENY_WEAK_RNG !== "undefined" && UUIDV7_DENY_WEAK_RNG) {
378
- // throw new Error("no cryptographically strong RNG available");
379
- // }
380
- // return {
381
- // nextUint32: (): number =>
382
- // Math.trunc(Math.random() * 0x1_0000) * 0x1_0000 +
383
- // Math.trunc(Math.random() * 0x1_0000),
384
- // };
385
- // }
386
- return {
387
- nextUint32: () => Math.trunc(Math.random() * 65536) * 65536 +
388
- Math.trunc(Math.random() * 65536),
389
- };
390
- };
391
- // /**
392
- // * Wraps `crypto.getRandomValues()` to enable buffering; this uses a small
393
- // * buffer by default to avoid both unbearable throughput decline in some
394
- // * environments and the waste of time and space for unused values.
395
- // */
396
- // class BufferedCryptoRandom {
397
- // private readonly buffer = new Uint32Array(8);
398
- // private cursor = 0xffff;
399
- // nextUint32(): number {
400
- // if (this.cursor >= this.buffer.length) {
401
- // crypto.getRandomValues(this.buffer);
402
- // this.cursor = 0;
403
- // }
404
- // return this.buffer[this.cursor++];
405
- // }
406
- // }
407
- let defaultGenerator;
408
- /**
409
- * Generates a UUIDv7 string.
410
- *
411
- * @returns The 8-4-4-4-12 canonical hexadecimal string representation
412
- * ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").
413
- */
414
- const uuidv7 = () => uuidv7obj().toString();
415
- /** Generates a UUIDv7 object. */
416
- const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
417
-
418
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
419
- // Licensed under the MIT License
420
- function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
421
- let calledFatalError = false;
422
- return Object.assign(error => {
423
- // Attaching a listener to `uncaughtException` will prevent the node process from exiting. We generally do not
424
- // want to alter this behaviour so we check for other listeners that users may have attached themselves and adjust
425
- // exit behaviour of the SDK accordingly:
426
- // - If other listeners are attached, do not exit.
427
- // - If the only listener attached is ours, exit.
428
- const userProvidedListenersCount = global.process.listeners('uncaughtException').filter(listener => {
429
- // There are 2 listeners we ignore:
430
- return (
431
- // as soon as we're using domains this listener is attached by node itself
432
- listener.name !== 'domainUncaughtExceptionClear' &&
433
- // the handler we register in this integration
434
- listener._posthogErrorHandler !== true
435
- );
436
- }).length;
437
- const processWouldExit = userProvidedListenersCount === 0;
438
- captureFn(error, {
439
- mechanism: {
440
- type: 'onuncaughtexception',
441
- handled: false
442
- }
443
- });
444
- if (!calledFatalError && processWouldExit) {
445
- calledFatalError = true;
446
- onFatalFn();
447
- }
448
- }, {
449
- _posthogErrorHandler: true
450
- });
451
- }
452
- function addUncaughtExceptionListener(captureFn, onFatalFn) {
453
- global.process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));
454
- }
455
- function addUnhandledRejectionListener(captureFn) {
456
- global.process.on('unhandledRejection', reason => {
457
- captureFn(reason, {
458
- mechanism: {
459
- type: 'onunhandledrejection',
460
- handled: false
461
- }
462
- });
463
- });
464
- }
465
-
466
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
467
- // Licensed under the MIT License
468
- function isEvent(candidate) {
469
- return typeof Event !== 'undefined' && isInstanceOf(candidate, Event);
470
- }
471
- function isPlainObject(candidate) {
472
- return isBuiltin(candidate, 'Object');
473
- }
474
- function isError(candidate) {
475
- switch (Object.prototype.toString.call(candidate)) {
476
- case '[object Error]':
477
- case '[object Exception]':
478
- case '[object DOMException]':
479
- case '[object WebAssembly.Exception]':
480
- return true;
481
- default:
482
- return isInstanceOf(candidate, Error);
483
- }
484
- }
485
- function isInstanceOf(candidate, base) {
486
- try {
487
- return candidate instanceof base;
488
- } catch {
489
- return false;
490
- }
491
- }
492
- function isErrorEvent(event) {
493
- return isBuiltin(event, 'ErrorEvent');
494
- }
495
- function isBuiltin(candidate, className) {
496
- return Object.prototype.toString.call(candidate) === `[object ${className}]`;
497
- }
498
-
499
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
500
- async function propertiesFromUnknownInput(stackParser, frameModifiers, input, hint) {
501
- const providedMechanism = hint && hint.mechanism;
502
- const mechanism = providedMechanism || {
503
- handled: true,
504
- type: 'generic'
505
- };
506
- const errorList = getErrorList(mechanism, input, hint);
507
- const exceptionList = await Promise.all(errorList.map(async error => {
508
- const exception = await exceptionFromError(stackParser, frameModifiers, error);
509
- exception.value = exception.value || '';
510
- exception.type = exception.type || 'Error';
511
- exception.mechanism = mechanism;
512
- return exception;
513
- }));
514
- const properties = {
515
- $exception_list: exceptionList
516
- };
517
- return properties;
518
- }
519
- // Flatten error causes into a list of errors
520
- // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
521
- function getErrorList(mechanism, input, hint) {
522
- const error = getError(mechanism, input, hint);
523
- if (error.cause) {
524
- return [error, ...getErrorList(mechanism, error.cause, hint)];
525
- }
526
- return [error];
527
- }
528
- function getError(mechanism, exception, hint) {
529
- if (isError(exception)) {
530
- return exception;
531
- }
532
- mechanism.synthetic = true;
533
- if (isPlainObject(exception)) {
534
- const errorFromProp = getErrorPropertyFromObject(exception);
535
- if (errorFromProp) {
536
- return errorFromProp;
537
- }
538
- const message = getMessageForObject(exception);
539
- const ex = hint?.syntheticException || new Error(message);
540
- ex.message = message;
541
- return ex;
542
- }
543
- // This handles when someone does: `throw "something awesome";`
544
- // We use synthesized Error here so we can extract a (rough) stack trace.
545
- const ex = hint?.syntheticException || new Error(exception);
546
- ex.message = `${exception}`;
547
- return ex;
548
- }
549
- /** If a plain object has a property that is an `Error`, return this error. */
550
- function getErrorPropertyFromObject(obj) {
551
- for (const prop in obj) {
552
- if (Object.prototype.hasOwnProperty.call(obj, prop)) {
553
- const value = obj[prop];
554
- if (isError(value)) {
555
- return value;
556
- }
557
- }
558
- }
559
- return undefined;
560
- }
561
- function getMessageForObject(exception) {
562
- if ('name' in exception && typeof exception.name === 'string') {
563
- let message = `'${exception.name}' captured as exception`;
564
- if ('message' in exception && typeof exception.message === 'string') {
565
- message += ` with message '${exception.message}'`;
566
- }
567
- return message;
568
- } else if ('message' in exception && typeof exception.message === 'string') {
569
- return exception.message;
570
- }
571
- const keys = extractExceptionKeysForMessage(exception);
572
- // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before
573
- // We still want to try to get a decent message for these cases
574
- if (isErrorEvent(exception)) {
575
- return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
576
- }
577
- const className = getObjectClassName(exception);
578
- return `${className && className !== 'Object' ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;
579
- }
580
- function getObjectClassName(obj) {
581
- try {
582
- const prototype = Object.getPrototypeOf(obj);
583
- return prototype ? prototype.constructor.name : undefined;
584
- } catch (e) {
585
- // ignore errors here
586
- }
587
- }
588
- /**
589
- * Given any captured exception, extract its keys and create a sorted
590
- * and truncated list that will be used inside the event message.
591
- * eg. `Non-error exception captured with keys: foo, bar, baz`
592
- */
593
- function extractExceptionKeysForMessage(exception, maxLength = 40) {
594
- const keys = Object.keys(convertToPlainObject(exception));
595
- keys.sort();
596
- const firstKey = keys[0];
597
- if (!firstKey) {
598
- return '[object has no keys]';
599
- }
600
- if (firstKey.length >= maxLength) {
601
- return truncate(firstKey, maxLength);
602
- }
603
- for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
604
- const serialized = keys.slice(0, includedKeys).join(', ');
605
- if (serialized.length > maxLength) {
606
- continue;
607
- }
608
- if (includedKeys === keys.length) {
609
- return serialized;
610
- }
611
- return truncate(serialized, maxLength);
612
- }
613
- return '';
614
- }
615
- function truncate(str, max = 0) {
616
- if (typeof str !== 'string' || max === 0) {
617
- return str;
618
- }
619
- return str.length <= max ? str : `${str.slice(0, max)}...`;
620
- }
621
- /**
622
- * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their
623
- * non-enumerable properties attached.
624
- *
625
- * @param value Initial source that we have to transform in order for it to be usable by the serializer
626
- * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor
627
- * an Error.
628
- */
629
- function convertToPlainObject(value) {
630
- if (isError(value)) {
631
- return {
632
- message: value.message,
633
- name: value.name,
634
- stack: value.stack,
635
- ...getOwnProperties(value)
636
- };
637
- } else if (isEvent(value)) {
638
- const newObj = {
639
- type: value.type,
640
- target: serializeEventTarget(value.target),
641
- currentTarget: serializeEventTarget(value.currentTarget),
642
- ...getOwnProperties(value)
643
- };
644
- // TODO: figure out why this fails typing (I think CustomEvent is only supported in Node 19 onwards)
645
- // if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {
646
- // newObj.detail = (value as unknown as CustomEvent).detail
647
- // }
648
- return newObj;
649
- } else {
650
- return value;
651
- }
652
- }
653
- /** Filters out all but an object's own properties */
654
- function getOwnProperties(obj) {
655
- if (typeof obj === 'object' && obj !== null) {
656
- const extractedProps = {};
657
- for (const property in obj) {
658
- if (Object.prototype.hasOwnProperty.call(obj, property)) {
659
- extractedProps[property] = obj[property];
660
- }
661
- }
662
- return extractedProps;
663
- } else {
664
- return {};
665
- }
666
- }
667
- /** Creates a string representation of the target of an `Event` object */
668
- function serializeEventTarget(target) {
669
- try {
670
- return Object.prototype.toString.call(target);
671
- } catch (_oO) {
672
- return '<unknown>';
673
- }
674
- }
675
- /**
676
- * Extracts stack frames from the error and builds an Exception
677
- */
678
- async function exceptionFromError(stackParser, frameModifiers, error) {
679
- const exception = {
680
- type: error.name || error.constructor.name,
681
- value: error.message
682
- };
683
- let frames = parseStackFrames(stackParser, error);
684
- for (const modifier of frameModifiers) {
685
- frames = await modifier(frames);
686
- }
687
- if (frames.length) {
688
- exception.stacktrace = {
689
- frames,
690
- type: 'raw'
691
- };
692
- }
693
- return exception;
694
- }
695
- /**
696
- * Extracts stack frames from the error.stack string
697
- */
698
- function parseStackFrames(stackParser, error) {
699
- return stackParser(error.stack || '', 1);
700
- }
701
-
702
- const SHUTDOWN_TIMEOUT = 2000;
703
- class ErrorTracking {
704
- static async captureException(client, error, hint, distinctId, additionalProperties) {
705
- const properties = {
706
- ...additionalProperties
707
- };
708
- // Given stateless nature of Node SDK we capture exceptions using personless processing when no
709
- // user can be determined because a distinct_id is not provided e.g. exception autocapture
710
- if (!distinctId) {
711
- properties.$process_person_profile = false;
712
- }
713
- const exceptionProperties = await propertiesFromUnknownInput(this.stackParser, this.frameModifiers, error, hint);
714
- client.capture({
715
- event: '$exception',
716
- distinctId: distinctId || uuidv7(),
717
- properties: {
718
- ...exceptionProperties,
719
- ...properties
720
- }
721
- });
722
- }
723
- constructor(client, options) {
724
- this.client = client;
725
- this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
726
- this.startAutocaptureIfEnabled();
727
- }
728
- startAutocaptureIfEnabled() {
729
- if (this.isEnabled()) {
730
- addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
731
- addUnhandledRejectionListener(this.onException.bind(this));
732
- }
733
- }
734
- onException(exception, hint) {
735
- ErrorTracking.captureException(this.client, exception, hint);
736
- }
737
- async onFatalError() {
738
- await this.client.shutdown(SHUTDOWN_TIMEOUT);
739
- }
740
- isEnabled() {
741
- return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
742
- }
743
- }
744
-
745
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
746
- /** Creates a function that gets the module name from a filename */
747
- function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === '\\') {
748
- const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
749
- return filename => {
750
- if (!filename) {
751
- return;
752
- }
753
- const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
754
- // eslint-disable-next-line prefer-const
755
- let {
756
- dir,
757
- base: file,
758
- ext
759
- } = posix.parse(normalizedFilename);
760
- if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
761
- file = file.slice(0, ext.length * -1);
762
- }
763
- // The file name might be URI-encoded which we want to decode to
764
- // the original file name.
765
- const decodedFile = decodeURIComponent(file);
766
- if (!dir) {
767
- // No dirname whatsoever
768
- dir = '.';
769
- }
770
- const n = dir.lastIndexOf('/node_modules');
771
- if (n > -1) {
772
- return `${dir.slice(n + 14).replace(/\//g, '.')}:${decodedFile}`;
773
- }
774
- // Let's see if it's a part of the main module
775
- // To be a part of main module, it has to share the same base
776
- if (dir.startsWith(normalizedBase)) {
777
- const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, '.');
778
- return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
779
- }
780
- return decodedFile;
781
- };
782
- }
783
- /** normalizes Windows paths */
784
- function normalizeWindowsPath(path) {
785
- return path.replace(/^[A-Z]:/, '') // remove Windows-style prefix
786
- .replace(/\\/g, '/'); // replace all `\` instances with `/`
787
- }
788
-
789
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
790
- // Licensed under the MIT License
791
- /** A simple Least Recently Used map */
792
- class ReduceableCache {
793
- constructor(_maxSize) {
794
- this._maxSize = _maxSize;
795
- this._cache = new Map();
796
- }
797
- /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
798
- get(key) {
799
- const value = this._cache.get(key);
800
- if (value === undefined) {
801
- return undefined;
802
- }
803
- // Remove and re-insert to update the order
804
- this._cache.delete(key);
805
- this._cache.set(key, value);
806
- return value;
807
- }
808
- /** Insert an entry and evict an older entry if we've reached maxSize */
809
- set(key, value) {
810
- this._cache.set(key, value);
811
- }
812
- /** Remove an entry and return the entry if it was in the cache */
813
- reduce() {
814
- while (this._cache.size >= this._maxSize) {
815
- const value = this._cache.keys().next().value;
816
- if (value) {
817
- // keys() returns an iterator in insertion order so keys().next() gives us the oldest key
818
- this._cache.delete(value);
819
- }
820
- }
821
- }
822
- }
823
-
824
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
825
- const LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
826
- const LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
827
- const DEFAULT_LINES_OF_CONTEXT = 7;
828
- // Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be
829
- // minified code while large lineno values are likely to be bundled code.
830
- // Exported for testing purposes.
831
- const MAX_CONTEXTLINES_COLNO = 1000;
832
- const MAX_CONTEXTLINES_LINENO = 10000;
833
- async function addSourceContext(frames) {
834
- // keep a lookup map of which files we've already enqueued to read,
835
- // so we don't enqueue the same file multiple times which would cause multiple i/o reads
836
- const filesToLines = {};
837
- // Maps preserve insertion order, so we iterate in reverse, starting at the
838
- // outermost frame and closer to where the exception has occurred (poor mans priority)
839
- for (let i = frames.length - 1; i >= 0; i--) {
840
- const frame = frames[i];
841
- const filename = frame?.filename;
842
- if (!frame || typeof filename !== 'string' || typeof frame.lineno !== 'number' || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) {
843
- continue;
844
- }
845
- const filesToLinesOutput = filesToLines[filename];
846
- if (!filesToLinesOutput) {
847
- filesToLines[filename] = [];
848
- }
849
- filesToLines[filename].push(frame.lineno);
850
- }
851
- const files = Object.keys(filesToLines);
852
- if (files.length == 0) {
853
- return frames;
854
- }
855
- const readlinePromises = [];
856
- for (const file of files) {
857
- // If we failed to read this before, dont try reading it again.
858
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {
859
- continue;
860
- }
861
- const filesToLineRanges = filesToLines[file];
862
- if (!filesToLineRanges) {
863
- continue;
864
- }
865
- // Sort ranges so that they are sorted by line increasing order and match how the file is read.
866
- filesToLineRanges.sort((a, b) => a - b);
867
- // Check if the contents are already in the cache and if we can avoid reading the file again.
868
- const ranges = makeLineReaderRanges(filesToLineRanges);
869
- if (ranges.every(r => rangeExistsInContentCache(file, r))) {
870
- continue;
871
- }
872
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
873
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
874
- }
875
- // The promise rejections are caught in order to prevent them from short circuiting Promise.all
876
- await Promise.all(readlinePromises).catch(() => {});
877
- // Perform the same loop as above, but this time we can assume all files are in the cache
878
- // and attempt to add source context to frames.
879
- if (frames && frames.length > 0) {
880
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
881
- }
882
- // Once we're finished processing an exception reduce the files held in the cache
883
- // so that we don't indefinetly increase the size of this map
884
- LRU_FILE_CONTENTS_CACHE.reduce();
885
- return frames;
886
- }
887
- /**
888
- * Extracts lines from a file and stores them in a cache.
889
- */
890
- function getContextLinesFromFile(path, ranges, output) {
891
- return new Promise(resolve => {
892
- // It is important *not* to have any async code between createInterface and the 'line' event listener
893
- // as it will cause the 'line' event to
894
- // be emitted before the listener is attached.
895
- const stream = createReadStream(path);
896
- const lineReaded = createInterface({
897
- input: stream
898
- });
899
- // We need to explicitly destroy the stream to prevent memory leaks,
900
- // removing the listeners on the readline interface is not enough.
901
- // See: https://github.com/nodejs/node/issues/9002 and https://github.com/getsentry/sentry-javascript/issues/14892
902
- function destroyStreamAndResolve() {
903
- stream.destroy();
904
- resolve();
905
- }
906
- // Init at zero and increment at the start of the loop because lines are 1 indexed.
907
- let lineNumber = 0;
908
- let currentRangeIndex = 0;
909
- const range = ranges[currentRangeIndex];
910
- if (range === undefined) {
911
- // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.
912
- destroyStreamAndResolve();
913
- return;
914
- }
915
- let rangeStart = range[0];
916
- let rangeEnd = range[1];
917
- // We use this inside Promise.all, so we need to resolve the promise even if there is an error
918
- // to prevent Promise.all from short circuiting the rest.
919
- function onStreamError() {
920
- // Mark file path as failed to read and prevent multiple read attempts.
921
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
922
- lineReaded.close();
923
- lineReaded.removeAllListeners();
924
- destroyStreamAndResolve();
925
- }
926
- // We need to handle the error event to prevent the process from crashing in < Node 16
927
- // https://github.com/nodejs/node/pull/31603
928
- stream.on('error', onStreamError);
929
- lineReaded.on('error', onStreamError);
930
- lineReaded.on('close', destroyStreamAndResolve);
931
- lineReaded.on('line', line => {
932
- lineNumber++;
933
- if (lineNumber < rangeStart) {
934
- return;
935
- }
936
- // !Warning: This mutates the cache by storing the snipped line into the cache.
937
- output[lineNumber] = snipLine(line, 0);
938
- if (lineNumber >= rangeEnd) {
939
- if (currentRangeIndex === ranges.length - 1) {
940
- // We need to close the file stream and remove listeners, else the reader will continue to run our listener;
941
- lineReaded.close();
942
- lineReaded.removeAllListeners();
943
- return;
944
- }
945
- currentRangeIndex++;
946
- const range = ranges[currentRangeIndex];
947
- if (range === undefined) {
948
- // This should never happen as it means we have a bug in the context.
949
- lineReaded.close();
950
- lineReaded.removeAllListeners();
951
- return;
952
- }
953
- rangeStart = range[0];
954
- rangeEnd = range[1];
955
- }
956
- });
957
- });
958
- }
959
- /** Adds context lines to frames */
960
- function addSourceContextToFrames(frames, cache) {
961
- for (const frame of frames) {
962
- // Only add context if we have a filename and it hasn't already been added
963
- if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {
964
- const contents = cache.get(frame.filename);
965
- if (contents === undefined) {
966
- continue;
967
- }
968
- addContextToFrame(frame.lineno, frame, contents);
969
- }
970
- }
971
- }
972
- /**
973
- * Resolves context lines before and after the given line number and appends them to the frame;
974
- */
975
- function addContextToFrame(lineno, frame, contents) {
976
- // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.
977
- // We already check for lineno before calling this, but since StackFrame lineno is optional, we check it again.
978
- if (frame.lineno === undefined || contents === undefined) {
979
- return;
980
- }
981
- frame.pre_context = [];
982
- for (let i = makeRangeStart(lineno); i < lineno; i++) {
983
- // We always expect the start context as line numbers cannot be negative. If we dont find a line, then
984
- // something went wrong somewhere. Clear the context and return without adding any linecontext.
985
- const line = contents[i];
986
- if (line === undefined) {
987
- clearLineContext(frame);
988
- return;
989
- }
990
- frame.pre_context.push(line);
991
- }
992
- // We should always have the context line. If we dont, something went wrong, so we clear the context and return
993
- // without adding any linecontext.
994
- if (contents[lineno] === undefined) {
995
- clearLineContext(frame);
996
- return;
997
- }
998
- frame.context_line = contents[lineno];
999
- const end = makeRangeEnd(lineno);
1000
- frame.post_context = [];
1001
- for (let i = lineno + 1; i <= end; i++) {
1002
- // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could
1003
- // just be that we reached the end of the file.
1004
- const line = contents[i];
1005
- if (line === undefined) {
1006
- break;
1007
- }
1008
- frame.post_context.push(line);
1009
- }
1010
- }
1011
- /**
1012
- * Clears the context lines from a frame, used to reset a frame to its original state
1013
- * if we fail to resolve all context lines for it.
1014
- */
1015
- function clearLineContext(frame) {
1016
- delete frame.pre_context;
1017
- delete frame.context_line;
1018
- delete frame.post_context;
1019
- }
1020
- /**
1021
- * Determines if context lines should be skipped for a file.
1022
- * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source
1023
- * - node: prefixed modules are part of the runtime and cannot be resolved to a file
1024
- * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports
1025
- */
1026
- function shouldSkipContextLinesForFile(path) {
1027
- // Test the most common prefix and extension first. These are the ones we
1028
- // are most likely to see in user applications and are the ones we can break out of first.
1029
- return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');
1030
- }
1031
- /**
1032
- * Determines if we should skip contextlines based off the max lineno and colno values.
1033
- */
1034
- function shouldSkipContextLinesForFrame(frame) {
1035
- if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) {
1036
- return true;
1037
- }
1038
- if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) {
1039
- return true;
1040
- }
1041
- return false;
1042
- }
1043
- /**
1044
- * Checks if we have all the contents that we need in the cache.
1045
- */
1046
- function rangeExistsInContentCache(file, range) {
1047
- const contents = LRU_FILE_CONTENTS_CACHE.get(file);
1048
- if (contents === undefined) {
1049
- return false;
1050
- }
1051
- for (let i = range[0]; i <= range[1]; i++) {
1052
- if (contents[i] === undefined) {
1053
- return false;
1054
- }
1055
- }
1056
- return true;
1057
- }
1058
- /**
1059
- * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,
1060
- * the ranges are merged to create a single range.
1061
- */
1062
- function makeLineReaderRanges(lines) {
1063
- if (!lines.length) {
1064
- return [];
1065
- }
1066
- let i = 0;
1067
- const line = lines[0];
1068
- if (typeof line !== 'number') {
1069
- return [];
1070
- }
1071
- let current = makeContextRange(line);
1072
- const out = [];
1073
- while (true) {
1074
- if (i === lines.length - 1) {
1075
- out.push(current);
1076
- break;
1077
- }
1078
- // If the next line falls into the current range, extend the current range to lineno + linecontext.
1079
- const next = lines[i + 1];
1080
- if (typeof next !== 'number') {
1081
- break;
1082
- }
1083
- if (next <= current[1]) {
1084
- current[1] = next + DEFAULT_LINES_OF_CONTEXT;
1085
- } else {
1086
- out.push(current);
1087
- current = makeContextRange(next);
1088
- }
1089
- i++;
1090
- }
1091
- return out;
1092
- }
1093
- // Determine start and end indices for context range (inclusive);
1094
- function makeContextRange(line) {
1095
- return [makeRangeStart(line), makeRangeEnd(line)];
1096
- }
1097
- // Compute inclusive end context range
1098
- function makeRangeStart(line) {
1099
- return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);
1100
- }
1101
- // Compute inclusive start context range
1102
- function makeRangeEnd(line) {
1103
- return line + DEFAULT_LINES_OF_CONTEXT;
1104
- }
1105
- /**
1106
- * Get or init map value
1107
- */
1108
- function emplace(map, key, contents) {
1109
- const value = map.get(key);
1110
- if (value === undefined) {
1111
- map.set(key, contents);
1112
- return contents;
1113
- }
1114
- return value;
1115
- }
1116
- function snipLine(line, colno) {
1117
- let newLine = line;
1118
- const lineLength = newLine.length;
1119
- if (lineLength <= 150) {
1120
- return newLine;
1121
- }
1122
- if (colno > lineLength) {
1123
- colno = lineLength;
1124
- }
1125
- let start = Math.max(colno - 60, 0);
1126
- if (start < 5) {
1127
- start = 0;
1128
- }
1129
- let end = Math.min(start + 140, lineLength);
1130
- if (end > lineLength - 5) {
1131
- end = lineLength;
1132
- }
1133
- if (end === lineLength) {
1134
- start = Math.max(end - 140, 0);
1135
- }
1136
- newLine = newLine.slice(start, end);
1137
- if (start > 0) {
1138
- newLine = `...${newLine}`;
1139
- }
1140
- if (end < lineLength) {
1141
- newLine += '...';
1142
- }
1143
- return newLine;
1144
- }
1145
-
1146
- var version = "4.17.1";
1147
-
1148
- var PostHogPersistedProperty;
1149
- (function (PostHogPersistedProperty) {
1150
- PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
1151
- PostHogPersistedProperty["DistinctId"] = "distinct_id";
1152
- PostHogPersistedProperty["Props"] = "props";
1153
- PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
1154
- PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
1155
- PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
1156
- PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
1157
- PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
1158
- PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
1159
- PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
1160
- PostHogPersistedProperty["Queue"] = "queue";
1161
- PostHogPersistedProperty["OptedOut"] = "opted_out";
1162
- PostHogPersistedProperty["SessionId"] = "session_id";
1163
- PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
1164
- PostHogPersistedProperty["PersonProperties"] = "person_properties";
1165
- PostHogPersistedProperty["GroupProperties"] = "group_properties";
1166
- PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
1167
- PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
1168
- PostHogPersistedProperty["SessionReplay"] = "session_replay";
1169
- PostHogPersistedProperty["DecideEndpointWasHit"] = "decide_endpoint_was_hit";
1170
- PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
1171
- PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
1172
- PostHogPersistedProperty["Surveys"] = "surveys";
1173
- PostHogPersistedProperty["RemoteConfig"] = "remote_config";
1174
- })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
1175
- var SurveyPosition;
1176
- (function (SurveyPosition) {
1177
- SurveyPosition["Left"] = "left";
1178
- SurveyPosition["Right"] = "right";
1179
- SurveyPosition["Center"] = "center";
1180
- })(SurveyPosition || (SurveyPosition = {}));
1181
- var SurveyWidgetType;
1182
- (function (SurveyWidgetType) {
1183
- SurveyWidgetType["Button"] = "button";
1184
- SurveyWidgetType["Tab"] = "tab";
1185
- SurveyWidgetType["Selector"] = "selector";
1186
- })(SurveyWidgetType || (SurveyWidgetType = {}));
1187
- var SurveyType;
1188
- (function (SurveyType) {
1189
- SurveyType["Popover"] = "popover";
1190
- SurveyType["API"] = "api";
1191
- SurveyType["Widget"] = "widget";
1192
- })(SurveyType || (SurveyType = {}));
1193
- var SurveyQuestionDescriptionContentType;
1194
- (function (SurveyQuestionDescriptionContentType) {
1195
- SurveyQuestionDescriptionContentType["Html"] = "html";
1196
- SurveyQuestionDescriptionContentType["Text"] = "text";
1197
- })(SurveyQuestionDescriptionContentType || (SurveyQuestionDescriptionContentType = {}));
1198
- var SurveyRatingDisplay;
1199
- (function (SurveyRatingDisplay) {
1200
- SurveyRatingDisplay["Number"] = "number";
1201
- SurveyRatingDisplay["Emoji"] = "emoji";
1202
- })(SurveyRatingDisplay || (SurveyRatingDisplay = {}));
1203
- var SurveyQuestionType;
1204
- (function (SurveyQuestionType) {
1205
- SurveyQuestionType["Open"] = "open";
1206
- SurveyQuestionType["MultipleChoice"] = "multiple_choice";
1207
- SurveyQuestionType["SingleChoice"] = "single_choice";
1208
- SurveyQuestionType["Rating"] = "rating";
1209
- SurveyQuestionType["Link"] = "link";
1210
- })(SurveyQuestionType || (SurveyQuestionType = {}));
1211
- var SurveyQuestionBranchingType;
1212
- (function (SurveyQuestionBranchingType) {
1213
- SurveyQuestionBranchingType["NextQuestion"] = "next_question";
1214
- SurveyQuestionBranchingType["End"] = "end";
1215
- SurveyQuestionBranchingType["ResponseBased"] = "response_based";
1216
- SurveyQuestionBranchingType["SpecificQuestion"] = "specific_question";
1217
- })(SurveyQuestionBranchingType || (SurveyQuestionBranchingType = {}));
1218
- var SurveyMatchType;
1219
- (function (SurveyMatchType) {
1220
- SurveyMatchType["Regex"] = "regex";
1221
- SurveyMatchType["NotRegex"] = "not_regex";
1222
- SurveyMatchType["Exact"] = "exact";
1223
- SurveyMatchType["IsNot"] = "is_not";
1224
- SurveyMatchType["Icontains"] = "icontains";
1225
- SurveyMatchType["NotIcontains"] = "not_icontains";
1226
- })(SurveyMatchType || (SurveyMatchType = {}));
1227
- /** Sync with plugin-server/src/types.ts */
1228
- var ActionStepStringMatching;
1229
- (function (ActionStepStringMatching) {
1230
- ActionStepStringMatching["Contains"] = "contains";
1231
- ActionStepStringMatching["Exact"] = "exact";
1232
- ActionStepStringMatching["Regex"] = "regex";
1233
- })(ActionStepStringMatching || (ActionStepStringMatching = {}));
1234
-
1235
- const normalizeDecideResponse = (decideResponse) => {
1236
- if ('flags' in decideResponse) {
1237
- // Convert v4 format to v3 format
1238
- const featureFlags = getFlagValuesFromFlags(decideResponse.flags);
1239
- const featureFlagPayloads = getPayloadsFromFlags(decideResponse.flags);
1240
- return {
1241
- ...decideResponse,
1242
- featureFlags,
1243
- featureFlagPayloads,
1244
- };
1245
- }
1246
- else {
1247
- // Convert v3 format to v4 format
1248
- const featureFlags = decideResponse.featureFlags ?? {};
1249
- const featureFlagPayloads = Object.fromEntries(Object.entries(decideResponse.featureFlagPayloads || {}).map(([k, v]) => [k, parsePayload(v)]));
1250
- const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
1251
- key,
1252
- getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key]),
1253
- ]));
1254
- return {
1255
- ...decideResponse,
1256
- featureFlags,
1257
- featureFlagPayloads,
1258
- flags,
1259
- };
1260
- }
1261
- };
1262
- function getFlagDetailFromFlagAndPayload(key, value, payload) {
1263
- return {
1264
- key: key,
1265
- enabled: typeof value === 'string' ? true : value,
1266
- variant: typeof value === 'string' ? value : undefined,
1267
- reason: undefined,
1268
- metadata: {
1269
- id: undefined,
1270
- version: undefined,
1271
- payload: payload ? JSON.stringify(payload) : undefined,
1272
- description: undefined,
1273
- },
1274
- };
1275
- }
1276
- /**
1277
- * Get the flag values from the flags v4 response.
1278
- * @param flags - The flags
1279
- * @returns The flag values
1280
- */
1281
- const getFlagValuesFromFlags = (flags) => {
1282
- return Object.fromEntries(Object.entries(flags ?? {})
1283
- .map(([key, detail]) => [key, getFeatureFlagValue(detail)])
1284
- .filter(([, value]) => value !== undefined));
1285
- };
1286
- /**
1287
- * Get the payloads from the flags v4 response.
1288
- * @param flags - The flags
1289
- * @returns The payloads
1290
- */
1291
- const getPayloadsFromFlags = (flags) => {
1292
- const safeFlags = flags ?? {};
1293
- return Object.fromEntries(Object.keys(safeFlags)
1294
- .filter((flag) => {
1295
- const details = safeFlags[flag];
1296
- return details.enabled && details.metadata && details.metadata.payload !== undefined;
1297
- })
1298
- .map((flag) => {
1299
- const payload = safeFlags[flag].metadata?.payload;
1300
- return [flag, payload ? parsePayload(payload) : undefined];
1301
- }));
1302
- };
1303
- const getFeatureFlagValue = (detail) => {
1304
- return detail === undefined ? undefined : detail.variant ?? detail.enabled;
1305
- };
1306
- const parsePayload = (response) => {
1307
- if (typeof response !== 'string') {
1308
- return response;
1309
- }
1310
- try {
1311
- return JSON.parse(response);
1312
- }
1313
- catch {
1314
- return response;
1315
- }
1316
- };
1317
-
1318
- // Rollout constants
1319
- const NEW_FLAGS_ROLLOUT_PERCENTAGE = 1;
1320
- // The fnv1a hashes of the tokens that are explicitly excluded from the rollout
1321
- // see https://github.com/PostHog/posthog-js-lite/blob/main/posthog-core/src/utils.ts#L84
1322
- // are hashed API tokens from our top 10 for each category supported by this SDK.
1323
- const NEW_FLAGS_EXCLUDED_HASHES = new Set([
1324
- // Node
1325
- '61be3dd8',
1326
- '96f6df5f',
1327
- '8cfdba9b',
1328
- 'bf027177',
1329
- 'e59430a8',
1330
- '7fa5500b',
1331
- '569798e9',
1332
- '04809ff7',
1333
- '0ebc61a5',
1334
- '32de7f98',
1335
- '3beeb69a',
1336
- '12d34ad9',
1337
- '733853ec',
1338
- '0645bb64',
1339
- '5dcbee21',
1340
- 'b1f95fa3',
1341
- '2189e408',
1342
- '82b460c2',
1343
- '3a8cc979',
1344
- '29ef8843',
1345
- '2cdbf767',
1346
- '38084b54',
1347
- // React Native
1348
- '50f9f8de',
1349
- '41d0df91',
1350
- '5c236689',
1351
- 'c11aedd3',
1352
- 'ada46672',
1353
- 'f4331ee1',
1354
- '42fed62a',
1355
- 'c957462c',
1356
- 'd62f705a',
1357
- // Web (lots of teams per org, hence lots of API tokens)
1358
- 'e0162666',
1359
- '01b3e5cf',
1360
- '441cef7f',
1361
- 'bb9cafee',
1362
- '8f348eb0',
1363
- 'b2553f3a',
1364
- '97469d7d',
1365
- '39f21a76',
1366
- '03706dcc',
1367
- '27d50569',
1368
- '307584a7',
1369
- '6433e92e',
1370
- '150c7fbb',
1371
- '49f57f22',
1372
- '3772f65b',
1373
- '01eb8256',
1374
- '3c9e9234',
1375
- 'f853c7f7',
1376
- 'c0ac4b67',
1377
- 'cd609d40',
1378
- '10ca9b1a',
1379
- '8a87f11b',
1380
- '8e8e5216',
1381
- '1f6b63b3',
1382
- 'db7943dd',
1383
- '79b7164c',
1384
- '07f78e33',
1385
- '2d21b6fd',
1386
- '952db5ee',
1387
- 'a7d3b43f',
1388
- '1924dd9c',
1389
- '84e1b8f6',
1390
- 'dff631b6',
1391
- 'c5aa8a79',
1392
- 'fa133a95',
1393
- '498a4508',
1394
- '24748755',
1395
- '98f3d658',
1396
- '21bbda67',
1397
- '7dbfed69',
1398
- 'be3ec24c',
1399
- 'fc80b8e2',
1400
- '75cc0998',
1401
- ]);
1402
- const STRING_FORMAT = 'utf8';
1403
- function assert(truthyValue, message) {
1404
- if (!truthyValue || typeof truthyValue !== 'string' || isEmpty(truthyValue)) {
1405
- throw new Error(message);
1406
- }
1407
- }
1408
- function isEmpty(truthyValue) {
1409
- if (truthyValue.trim().length === 0) {
1410
- return true;
1411
- }
1412
- return false;
1413
- }
1414
- function removeTrailingSlash(url) {
1415
- return url?.replace(/\/+$/, '');
1416
- }
1417
- async function retriable(fn, props) {
1418
- let lastError = null;
1419
- for (let i = 0; i < props.retryCount + 1; i++) {
1420
- if (i > 0) {
1421
- // don't wait when it's the last try
1422
- await new Promise((r) => setTimeout(r, props.retryDelay));
1423
- }
1424
- try {
1425
- const res = await fn();
1426
- return res;
1427
- }
1428
- catch (e) {
1429
- lastError = e;
1430
- if (!props.retryCheck(e)) {
1431
- throw e;
1432
- }
1433
- }
1434
- }
1435
- throw lastError;
1436
- }
1437
- function currentTimestamp() {
1438
- return new Date().getTime();
1439
- }
1440
- function currentISOTime() {
1441
- return new Date().toISOString();
1442
- }
1443
- function safeSetTimeout(fn, timeout) {
1444
- // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
1445
- // rather than setImmediate.
1446
- const t = setTimeout(fn, timeout);
1447
- // We unref if available to prevent Node.js hanging on exit
1448
- t?.unref && t?.unref();
1449
- return t;
1450
- }
1451
- function getFetch() {
1452
- return typeof fetch !== 'undefined' ? fetch : typeof globalThis.fetch !== 'undefined' ? globalThis.fetch : undefined;
1453
- }
1454
- // FNV-1a hash function
1455
- // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
1456
- // I know, I know, I'm rolling my own hash function, but I didn't want to take on
1457
- // a crypto dependency and this is just temporary anyway
1458
- function fnv1a(str) {
1459
- let hash = 0x811c9dc5; // FNV offset basis
1460
- for (let i = 0; i < str.length; i++) {
1461
- hash ^= str.charCodeAt(i);
1462
- hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
1463
- }
1464
- // Convert to hex string, padding to 8 chars
1465
- return (hash >>> 0).toString(16).padStart(8, '0');
1466
- }
1467
- function isTokenInRollout(token, percentage = 0, excludedHashes) {
1468
- const tokenHash = fnv1a(token);
1469
- // Check excluded hashes (we're explicitly including these tokens from the rollout)
1470
- if (excludedHashes?.has(tokenHash)) {
1471
- return false;
1472
- }
1473
- // Convert hash to int and divide by max value to get number between 0-1
1474
- const hashInt = parseInt(tokenHash, 16);
1475
- const hashFloat = hashInt / 0xffffffff;
1476
- return hashFloat < percentage;
1477
- }
1478
-
1479
- // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
1480
- // This work is free. You can redistribute it and/or modify it
1481
- // under the terms of the WTFPL, Version 2
1482
- // For more information see LICENSE.txt or http://www.wtfpl.net/
1483
- //
1484
- // For more information, the home page:
1485
- // http://pieroxy.net/blog/pages/lz-string/testing.html
1486
- //
1487
- // LZ-based compression algorithm, version 1.4.4
1488
- // private property
1489
- const f = String.fromCharCode;
1490
- const keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1491
- const baseReverseDic = {};
1492
- function getBaseValue(alphabet, character) {
1493
- if (!baseReverseDic[alphabet]) {
1494
- baseReverseDic[alphabet] = {};
1495
- for (let i = 0; i < alphabet.length; i++) {
1496
- baseReverseDic[alphabet][alphabet.charAt(i)] = i;
1497
- }
1498
- }
1499
- return baseReverseDic[alphabet][character];
1500
- }
1501
- const LZString = {
1502
- compressToBase64: function (input) {
1503
- if (input == null) {
1504
- return '';
1505
- }
1506
- const res = LZString._compress(input, 6, function (a) {
1507
- return keyStrBase64.charAt(a);
1508
- });
1509
- switch (res.length % 4 // To produce valid Base64
1510
- ) {
1511
- default: // When could this happen ?
1512
- case 0:
1513
- return res;
1514
- case 1:
1515
- return res + '===';
1516
- case 2:
1517
- return res + '==';
1518
- case 3:
1519
- return res + '=';
1520
- }
1521
- },
1522
- decompressFromBase64: function (input) {
1523
- if (input == null) {
1524
- return '';
1525
- }
1526
- if (input == '') {
1527
- return null;
1528
- }
1529
- return LZString._decompress(input.length, 32, function (index) {
1530
- return getBaseValue(keyStrBase64, input.charAt(index));
1531
- });
1532
- },
1533
- compress: function (uncompressed) {
1534
- return LZString._compress(uncompressed, 16, function (a) {
1535
- return f(a);
1536
- });
1537
- },
1538
- _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
1539
- if (uncompressed == null) {
1540
- return '';
1541
- }
1542
- const context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
1543
- let i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
1544
- context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
1545
- for (ii = 0; ii < uncompressed.length; ii += 1) {
1546
- context_c = uncompressed.charAt(ii);
1547
- if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
1548
- context_dictionary[context_c] = context_dictSize++;
1549
- context_dictionaryToCreate[context_c] = true;
1550
- }
1551
- context_wc = context_w + context_c;
1552
- if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
1553
- context_w = context_wc;
1554
- }
1555
- else {
1556
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
1557
- if (context_w.charCodeAt(0) < 256) {
1558
- for (i = 0; i < context_numBits; i++) {
1559
- context_data_val = context_data_val << 1;
1560
- if (context_data_position == bitsPerChar - 1) {
1561
- context_data_position = 0;
1562
- context_data.push(getCharFromInt(context_data_val));
1563
- context_data_val = 0;
1564
- }
1565
- else {
1566
- context_data_position++;
1567
- }
1568
- }
1569
- value = context_w.charCodeAt(0);
1570
- for (i = 0; i < 8; i++) {
1571
- context_data_val = (context_data_val << 1) | (value & 1);
1572
- if (context_data_position == bitsPerChar - 1) {
1573
- context_data_position = 0;
1574
- context_data.push(getCharFromInt(context_data_val));
1575
- context_data_val = 0;
1576
- }
1577
- else {
1578
- context_data_position++;
1579
- }
1580
- value = value >> 1;
1581
- }
1582
- }
1583
- else {
1584
- value = 1;
1585
- for (i = 0; i < context_numBits; i++) {
1586
- context_data_val = (context_data_val << 1) | value;
1587
- if (context_data_position == bitsPerChar - 1) {
1588
- context_data_position = 0;
1589
- context_data.push(getCharFromInt(context_data_val));
1590
- context_data_val = 0;
1591
- }
1592
- else {
1593
- context_data_position++;
1594
- }
1595
- value = 0;
1596
- }
1597
- value = context_w.charCodeAt(0);
1598
- for (i = 0; i < 16; i++) {
1599
- context_data_val = (context_data_val << 1) | (value & 1);
1600
- if (context_data_position == bitsPerChar - 1) {
1601
- context_data_position = 0;
1602
- context_data.push(getCharFromInt(context_data_val));
1603
- context_data_val = 0;
1604
- }
1605
- else {
1606
- context_data_position++;
1607
- }
1608
- value = value >> 1;
1609
- }
1610
- }
1611
- context_enlargeIn--;
1612
- if (context_enlargeIn == 0) {
1613
- context_enlargeIn = Math.pow(2, context_numBits);
1614
- context_numBits++;
1615
- }
1616
- delete context_dictionaryToCreate[context_w];
1617
- }
1618
- else {
1619
- value = context_dictionary[context_w];
1620
- for (i = 0; i < context_numBits; i++) {
1621
- context_data_val = (context_data_val << 1) | (value & 1);
1622
- if (context_data_position == bitsPerChar - 1) {
1623
- context_data_position = 0;
1624
- context_data.push(getCharFromInt(context_data_val));
1625
- context_data_val = 0;
1626
- }
1627
- else {
1628
- context_data_position++;
1629
- }
1630
- value = value >> 1;
1631
- }
1632
- }
1633
- context_enlargeIn--;
1634
- if (context_enlargeIn == 0) {
1635
- context_enlargeIn = Math.pow(2, context_numBits);
1636
- context_numBits++;
1637
- }
1638
- // Add wc to the dictionary.
1639
- context_dictionary[context_wc] = context_dictSize++;
1640
- context_w = String(context_c);
1641
- }
1642
- }
1643
- // Output the code for w.
1644
- if (context_w !== '') {
1645
- if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
1646
- if (context_w.charCodeAt(0) < 256) {
1647
- for (i = 0; i < context_numBits; i++) {
1648
- context_data_val = context_data_val << 1;
1649
- if (context_data_position == bitsPerChar - 1) {
1650
- context_data_position = 0;
1651
- context_data.push(getCharFromInt(context_data_val));
1652
- context_data_val = 0;
1653
- }
1654
- else {
1655
- context_data_position++;
1656
- }
1657
- }
1658
- value = context_w.charCodeAt(0);
1659
- for (i = 0; i < 8; i++) {
1660
- context_data_val = (context_data_val << 1) | (value & 1);
1661
- if (context_data_position == bitsPerChar - 1) {
1662
- context_data_position = 0;
1663
- context_data.push(getCharFromInt(context_data_val));
1664
- context_data_val = 0;
1665
- }
1666
- else {
1667
- context_data_position++;
1668
- }
1669
- value = value >> 1;
1670
- }
1671
- }
1672
- else {
1673
- value = 1;
1674
- for (i = 0; i < context_numBits; i++) {
1675
- context_data_val = (context_data_val << 1) | value;
1676
- if (context_data_position == bitsPerChar - 1) {
1677
- context_data_position = 0;
1678
- context_data.push(getCharFromInt(context_data_val));
1679
- context_data_val = 0;
1680
- }
1681
- else {
1682
- context_data_position++;
1683
- }
1684
- value = 0;
1685
- }
1686
- value = context_w.charCodeAt(0);
1687
- for (i = 0; i < 16; i++) {
1688
- context_data_val = (context_data_val << 1) | (value & 1);
1689
- if (context_data_position == bitsPerChar - 1) {
1690
- context_data_position = 0;
1691
- context_data.push(getCharFromInt(context_data_val));
1692
- context_data_val = 0;
1693
- }
1694
- else {
1695
- context_data_position++;
1696
- }
1697
- value = value >> 1;
1698
- }
1699
- }
1700
- context_enlargeIn--;
1701
- if (context_enlargeIn == 0) {
1702
- context_enlargeIn = Math.pow(2, context_numBits);
1703
- context_numBits++;
1704
- }
1705
- delete context_dictionaryToCreate[context_w];
1706
- }
1707
- else {
1708
- value = context_dictionary[context_w];
1709
- for (i = 0; i < context_numBits; i++) {
1710
- context_data_val = (context_data_val << 1) | (value & 1);
1711
- if (context_data_position == bitsPerChar - 1) {
1712
- context_data_position = 0;
1713
- context_data.push(getCharFromInt(context_data_val));
1714
- context_data_val = 0;
1715
- }
1716
- else {
1717
- context_data_position++;
1718
- }
1719
- value = value >> 1;
1720
- }
1721
- }
1722
- context_enlargeIn--;
1723
- if (context_enlargeIn == 0) {
1724
- context_enlargeIn = Math.pow(2, context_numBits);
1725
- context_numBits++;
1726
- }
1727
- }
1728
- // Mark the end of the stream
1729
- value = 2;
1730
- for (i = 0; i < context_numBits; i++) {
1731
- context_data_val = (context_data_val << 1) | (value & 1);
1732
- if (context_data_position == bitsPerChar - 1) {
1733
- context_data_position = 0;
1734
- context_data.push(getCharFromInt(context_data_val));
1735
- context_data_val = 0;
1736
- }
1737
- else {
1738
- context_data_position++;
1739
- }
1740
- value = value >> 1;
1741
- }
1742
- // Flush the last char
1743
- while (true) {
1744
- context_data_val = context_data_val << 1;
1745
- if (context_data_position == bitsPerChar - 1) {
1746
- context_data.push(getCharFromInt(context_data_val));
1747
- break;
1748
- }
1749
- else {
1750
- context_data_position++;
1751
- }
1752
- }
1753
- return context_data.join('');
1754
- },
1755
- decompress: function (compressed) {
1756
- if (compressed == null) {
1757
- return '';
1758
- }
1759
- if (compressed == '') {
1760
- return null;
1761
- }
1762
- return LZString._decompress(compressed.length, 32768, function (index) {
1763
- return compressed.charCodeAt(index);
1764
- });
1765
- },
1766
- _decompress: function (length, resetValue, getNextValue) {
1767
- const dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
1768
- let enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
1769
- for (i = 0; i < 3; i += 1) {
1770
- dictionary[i] = i;
1771
- }
1772
- bits = 0;
1773
- maxpower = Math.pow(2, 2);
1774
- power = 1;
1775
- while (power != maxpower) {
1776
- resb = data.val & data.position;
1777
- data.position >>= 1;
1778
- if (data.position == 0) {
1779
- data.position = resetValue;
1780
- data.val = getNextValue(data.index++);
1781
- }
1782
- bits |= (resb > 0 ? 1 : 0) * power;
1783
- power <<= 1;
1784
- }
1785
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
1786
- switch ((bits)) {
1787
- case 0:
1788
- bits = 0;
1789
- maxpower = Math.pow(2, 8);
1790
- power = 1;
1791
- while (power != maxpower) {
1792
- resb = data.val & data.position;
1793
- data.position >>= 1;
1794
- if (data.position == 0) {
1795
- data.position = resetValue;
1796
- data.val = getNextValue(data.index++);
1797
- }
1798
- bits |= (resb > 0 ? 1 : 0) * power;
1799
- power <<= 1;
1800
- }
1801
- c = f(bits);
1802
- break;
1803
- case 1:
1804
- bits = 0;
1805
- maxpower = Math.pow(2, 16);
1806
- power = 1;
1807
- while (power != maxpower) {
1808
- resb = data.val & data.position;
1809
- data.position >>= 1;
1810
- if (data.position == 0) {
1811
- data.position = resetValue;
1812
- data.val = getNextValue(data.index++);
1813
- }
1814
- bits |= (resb > 0 ? 1 : 0) * power;
1815
- power <<= 1;
1816
- }
1817
- c = f(bits);
1818
- break;
1819
- case 2:
1820
- return '';
1821
- }
1822
- dictionary[3] = c;
1823
- w = c;
1824
- result.push(c);
1825
- while (true) {
1826
- if (data.index > length) {
1827
- return '';
1828
- }
1829
- bits = 0;
1830
- maxpower = Math.pow(2, numBits);
1831
- power = 1;
1832
- while (power != maxpower) {
1833
- resb = data.val & data.position;
1834
- data.position >>= 1;
1835
- if (data.position == 0) {
1836
- data.position = resetValue;
1837
- data.val = getNextValue(data.index++);
1838
- }
1839
- bits |= (resb > 0 ? 1 : 0) * power;
1840
- power <<= 1;
1841
- }
1842
- switch ((c = bits)) {
1843
- case 0:
1844
- bits = 0;
1845
- maxpower = Math.pow(2, 8);
1846
- power = 1;
1847
- while (power != maxpower) {
1848
- resb = data.val & data.position;
1849
- data.position >>= 1;
1850
- if (data.position == 0) {
1851
- data.position = resetValue;
1852
- data.val = getNextValue(data.index++);
1853
- }
1854
- bits |= (resb > 0 ? 1 : 0) * power;
1855
- power <<= 1;
1856
- }
1857
- dictionary[dictSize++] = f(bits);
1858
- c = dictSize - 1;
1859
- enlargeIn--;
1860
- break;
1861
- case 1:
1862
- bits = 0;
1863
- maxpower = Math.pow(2, 16);
1864
- power = 1;
1865
- while (power != maxpower) {
1866
- resb = data.val & data.position;
1867
- data.position >>= 1;
1868
- if (data.position == 0) {
1869
- data.position = resetValue;
1870
- data.val = getNextValue(data.index++);
1871
- }
1872
- bits |= (resb > 0 ? 1 : 0) * power;
1873
- power <<= 1;
1874
- }
1875
- dictionary[dictSize++] = f(bits);
1876
- c = dictSize - 1;
1877
- enlargeIn--;
1878
- break;
1879
- case 2:
1880
- return result.join('');
1881
- }
1882
- if (enlargeIn == 0) {
1883
- enlargeIn = Math.pow(2, numBits);
1884
- numBits++;
1885
- }
1886
- if (dictionary[c]) {
1887
- entry = dictionary[c];
1888
- }
1889
- else {
1890
- if (c === dictSize) {
1891
- entry = w + w.charAt(0);
1892
- }
1893
- else {
1894
- return null;
1895
- }
1896
- }
1897
- result.push(entry);
1898
- // Add w+entry[0] to the dictionary.
1899
- dictionary[dictSize++] = w + entry.charAt(0);
1900
- enlargeIn--;
1901
- w = entry;
1902
- if (enlargeIn == 0) {
1903
- enlargeIn = Math.pow(2, numBits);
1904
- numBits++;
1905
- }
1906
- }
1907
- },
1908
- };
1909
-
1910
- class SimpleEventEmitter {
1911
- constructor() {
1912
- this.events = {};
1913
- this.events = {};
1914
- }
1915
- on(event, listener) {
1916
- if (!this.events[event]) {
1917
- this.events[event] = [];
1918
- }
1919
- this.events[event].push(listener);
1920
- return () => {
1921
- this.events[event] = this.events[event].filter((x) => x !== listener);
1922
- };
1923
- }
1924
- emit(event, payload) {
1925
- for (const listener of this.events[event] || []) {
1926
- listener(payload);
1927
- }
1928
- for (const listener of this.events['*'] || []) {
1929
- listener(event, payload);
1930
- }
1931
- }
1932
- }
1933
-
1934
- class PostHogFetchHttpError extends Error {
1935
- constructor(response, reqByteLength) {
1936
- super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength);
1937
- this.response = response;
1938
- this.reqByteLength = reqByteLength;
1939
- this.name = 'PostHogFetchHttpError';
1940
- }
1941
- get status() {
1942
- return this.response.status;
1943
- }
1944
- get text() {
1945
- return this.response.text();
1946
- }
1947
- get json() {
1948
- return this.response.json();
1949
- }
1950
- }
1951
- class PostHogFetchNetworkError extends Error {
1952
- constructor(error) {
1953
- // TRICKY: "cause" is a newer property but is just ignored otherwise. Cast to any to ignore the type issue.
1954
- // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
1955
- // @ts-ignore
1956
- super('Network error while fetching PostHog', error instanceof Error ? { cause: error } : {});
1957
- this.error = error;
1958
- this.name = 'PostHogFetchNetworkError';
1959
- }
1960
- }
1961
- async function logFlushError(err) {
1962
- if (err instanceof PostHogFetchHttpError) {
1963
- let text = '';
1964
- try {
1965
- text = await err.text;
1966
- }
1967
- catch { }
1968
- console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
1969
- }
1970
- else {
1971
- console.error('Error while flushing PostHog', err);
1972
- }
1973
- return Promise.resolve();
1974
- }
1975
- function isPostHogFetchError(err) {
1976
- return typeof err === 'object' && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
1977
- }
1978
- function isPostHogFetchContentTooLargeError(err) {
1979
- return typeof err === 'object' && err instanceof PostHogFetchHttpError && err.status === 413;
1980
- }
1981
- var QuotaLimitedFeature;
1982
- (function (QuotaLimitedFeature) {
1983
- QuotaLimitedFeature["FeatureFlags"] = "feature_flags";
1984
- QuotaLimitedFeature["Recordings"] = "recordings";
1985
- })(QuotaLimitedFeature || (QuotaLimitedFeature = {}));
1986
- class PostHogCoreStateless {
1987
- constructor(apiKey, options) {
1988
- this.flushPromise = null;
1989
- this.shutdownPromise = null;
1990
- this.pendingPromises = {};
1991
- // internal
1992
- this._events = new SimpleEventEmitter();
1993
- this._isInitialized = false;
1994
- assert(apiKey, "You must pass your PostHog project's api key.");
1995
- this.apiKey = apiKey;
1996
- this.host = removeTrailingSlash(options?.host || 'https://us.i.posthog.com');
1997
- this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 20;
1998
- this.maxBatchSize = Math.max(this.flushAt, options?.maxBatchSize ?? 100);
1999
- this.maxQueueSize = Math.max(this.flushAt, options?.maxQueueSize ?? 1000);
2000
- this.flushInterval = options?.flushInterval ?? 10000;
2001
- this.captureMode = options?.captureMode || 'json';
2002
- this.preloadFeatureFlags = options?.preloadFeatureFlags ?? true;
2003
- // If enable is explicitly set to false we override the optout
2004
- this.defaultOptIn = options?.defaultOptIn ?? true;
2005
- this.disableSurveys = options?.disableSurveys ?? false;
2006
- this._retryOptions = {
2007
- retryCount: options?.fetchRetryCount ?? 3,
2008
- retryDelay: options?.fetchRetryDelay ?? 3000,
2009
- retryCheck: isPostHogFetchError,
2010
- };
2011
- this.requestTimeout = options?.requestTimeout ?? 10000; // 10 seconds
2012
- this.featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 3000; // 3 seconds
2013
- this.remoteConfigRequestTimeoutMs = options?.remoteConfigRequestTimeoutMs ?? 3000; // 3 seconds
2014
- this.disableGeoip = options?.disableGeoip ?? true;
2015
- this.disabled = options?.disabled ?? false;
2016
- this.historicalMigration = options?.historicalMigration ?? false;
2017
- // Init promise allows the derived class to block calls until it is ready
2018
- this._initPromise = Promise.resolve();
2019
- this._isInitialized = true;
2020
- }
2021
- logMsgIfDebug(fn) {
2022
- if (this.isDebug) {
2023
- fn();
2024
- }
2025
- }
2026
- wrap(fn) {
2027
- if (this.disabled) {
2028
- this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
2029
- return;
2030
- }
2031
- if (this._isInitialized) {
2032
- // NOTE: We could also check for the "opt in" status here...
2033
- return fn();
2034
- }
2035
- this._initPromise.then(() => fn());
2036
- }
2037
- getCommonEventProperties() {
2038
- return {
2039
- $lib: this.getLibraryId(),
2040
- $lib_version: this.getLibraryVersion(),
2041
- };
2042
- }
2043
- get optedOut() {
2044
- return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
2045
- }
2046
- async optIn() {
2047
- this.wrap(() => {
2048
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
2049
- });
2050
- }
2051
- async optOut() {
2052
- this.wrap(() => {
2053
- this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
2054
- });
2055
- }
2056
- on(event, cb) {
2057
- return this._events.on(event, cb);
2058
- }
2059
- debug(enabled = true) {
2060
- this.removeDebugCallback?.();
2061
- if (enabled) {
2062
- const removeDebugCallback = this.on('*', (event, payload) => console.log('PostHog Debug', event, payload));
2063
- this.removeDebugCallback = () => {
2064
- removeDebugCallback();
2065
- this.removeDebugCallback = undefined;
2066
- };
2067
- }
2068
- }
2069
- get isDebug() {
2070
- return !!this.removeDebugCallback;
2071
- }
2072
- get isDisabled() {
2073
- return this.disabled;
2074
- }
2075
- buildPayload(payload) {
2076
- return {
2077
- distinct_id: payload.distinct_id,
2078
- event: payload.event,
2079
- properties: {
2080
- ...(payload.properties || {}),
2081
- ...this.getCommonEventProperties(), // Common PH props
2082
- },
2083
- };
2084
- }
2085
- addPendingPromise(promise) {
2086
- const promiseUUID = uuidv7();
2087
- this.pendingPromises[promiseUUID] = promise;
2088
- promise
2089
- .catch(() => { })
2090
- .finally(() => {
2091
- delete this.pendingPromises[promiseUUID];
2092
- });
2093
- return promise;
2094
- }
2095
- /***
2096
- *** TRACKING
2097
- ***/
2098
- identifyStateless(distinctId, properties, options) {
2099
- this.wrap(() => {
2100
- // The properties passed to identifyStateless are event properties.
2101
- // To add person properties, pass in all person properties to the `$set` and `$set_once` keys.
2102
- const payload = {
2103
- ...this.buildPayload({
2104
- distinct_id: distinctId,
2105
- event: '$identify',
2106
- properties,
2107
- }),
2108
- };
2109
- this.enqueue('identify', payload, options);
2110
- });
2111
- }
2112
- async identifyStatelessImmediate(distinctId, properties, options) {
2113
- const payload = {
2114
- ...this.buildPayload({
2115
- distinct_id: distinctId,
2116
- event: '$identify',
2117
- properties,
2118
- }),
2119
- };
2120
- await this.sendImmediate('identify', payload, options);
2121
- }
2122
- captureStateless(distinctId, event, properties, options) {
2123
- this.wrap(() => {
2124
- const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
2125
- this.enqueue('capture', payload, options);
2126
- });
2127
- }
2128
- async captureStatelessImmediate(distinctId, event, properties, options) {
2129
- const payload = this.buildPayload({ distinct_id: distinctId, event, properties });
2130
- await this.sendImmediate('capture', payload, options);
2131
- }
2132
- aliasStateless(alias, distinctId, properties, options) {
2133
- this.wrap(() => {
2134
- const payload = this.buildPayload({
2135
- event: '$create_alias',
2136
- distinct_id: distinctId,
2137
- properties: {
2138
- ...(properties || {}),
2139
- distinct_id: distinctId,
2140
- alias,
2141
- },
2142
- });
2143
- this.enqueue('alias', payload, options);
2144
- });
2145
- }
2146
- async aliasStatelessImmediate(alias, distinctId, properties, options) {
2147
- const payload = this.buildPayload({
2148
- event: '$create_alias',
2149
- distinct_id: distinctId,
2150
- properties: {
2151
- ...(properties || {}),
2152
- distinct_id: distinctId,
2153
- alias,
2154
- },
2155
- });
2156
- await this.sendImmediate('alias', payload, options);
2157
- }
2158
- /***
2159
- *** GROUPS
2160
- ***/
2161
- groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
2162
- this.wrap(() => {
2163
- const payload = this.buildPayload({
2164
- distinct_id: distinctId || `$${groupType}_${groupKey}`,
2165
- event: '$groupidentify',
2166
- properties: {
2167
- $group_type: groupType,
2168
- $group_key: groupKey,
2169
- $group_set: groupProperties || {},
2170
- ...(eventProperties || {}),
2171
- },
2172
- });
2173
- this.enqueue('capture', payload, options);
2174
- });
2175
- }
2176
- async getRemoteConfig() {
2177
- await this._initPromise;
2178
- let host = this.host;
2179
- if (host === 'https://us.i.posthog.com') {
2180
- host = 'https://us-assets.i.posthog.com';
2181
- }
2182
- else if (host === 'https://eu.i.posthog.com') {
2183
- host = 'https://eu-assets.i.posthog.com';
2184
- }
2185
- const url = `${host}/array/${this.apiKey}/config`;
2186
- const fetchOptions = {
2187
- method: 'GET',
2188
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2189
- };
2190
- // Don't retry remote config API calls
2191
- return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.remoteConfigRequestTimeoutMs)
2192
- .then((response) => response.json())
2193
- .catch((error) => {
2194
- this.logMsgIfDebug(() => console.error('Remote config could not be loaded', error));
2195
- this._events.emit('error', error);
2196
- return undefined;
2197
- });
2198
- }
2199
- /***
2200
- *** FEATURE FLAGS
2201
- ***/
2202
- async getDecide(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}) {
2203
- await this._initPromise;
2204
- // Check if the API token is in the new flags rollout
2205
- // This is a temporary measure to ensure that we can still use the old flags API
2206
- // while we migrate to the new flags API
2207
- const useFlags = isTokenInRollout(this.apiKey, NEW_FLAGS_ROLLOUT_PERCENTAGE, NEW_FLAGS_EXCLUDED_HASHES);
2208
- const url = useFlags ? `${this.host}/flags/?v=2` : `${this.host}/decide/?v=4`;
2209
- const fetchOptions = {
2210
- method: 'POST',
2211
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2212
- body: JSON.stringify({
2213
- token: this.apiKey,
2214
- distinct_id: distinctId,
2215
- groups,
2216
- person_properties: personProperties,
2217
- group_properties: groupProperties,
2218
- ...extraPayload,
2219
- }),
2220
- };
2221
- // Don't retry /decide API calls
2222
- return this.fetchWithRetry(url, fetchOptions, { retryCount: 0 }, this.featureFlagsRequestTimeoutMs)
2223
- .then((response) => response.json())
2224
- .then((response) => normalizeDecideResponse(response))
2225
- .catch((error) => {
2226
- this._events.emit('error', error);
2227
- return undefined;
2228
- });
2229
- }
2230
- async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
2231
- await this._initPromise;
2232
- const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
2233
- if (flagDetailResponse === undefined) {
2234
- // If we haven't loaded flags yet, or errored out, we respond with undefined
2235
- return {
2236
- response: undefined,
2237
- requestId: undefined,
2238
- };
2239
- }
2240
- let response = getFeatureFlagValue(flagDetailResponse.response);
2241
- if (response === undefined) {
2242
- // For cases where the flag is unknown, return false
2243
- response = false;
2244
- }
2245
- // If we have flags we either return the value (true or string) or false
2246
- return {
2247
- response,
2248
- requestId: flagDetailResponse.requestId,
2249
- };
2250
- }
2251
- async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
2252
- await this._initPromise;
2253
- const decideResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
2254
- if (decideResponse === undefined) {
2255
- return undefined;
2256
- }
2257
- const featureFlags = decideResponse.flags;
2258
- const flagDetail = featureFlags[key];
2259
- return {
2260
- response: flagDetail,
2261
- requestId: decideResponse.requestId,
2262
- };
2263
- }
2264
- async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
2265
- await this._initPromise;
2266
- const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [key]);
2267
- if (!payloads) {
2268
- return undefined;
2269
- }
2270
- const response = payloads[key];
2271
- // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
2272
- if (response === undefined) {
2273
- return null;
2274
- }
2275
- return response;
2276
- }
2277
- async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2278
- await this._initPromise;
2279
- const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
2280
- return payloads;
2281
- }
2282
- async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2283
- await this._initPromise;
2284
- return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
2285
- }
2286
- async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2287
- await this._initPromise;
2288
- const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
2289
- if (!featureFlagDetails) {
2290
- return {
2291
- flags: undefined,
2292
- payloads: undefined,
2293
- requestId: undefined,
2294
- };
2295
- }
2296
- return {
2297
- flags: featureFlagDetails.featureFlags,
2298
- payloads: featureFlagDetails.featureFlagPayloads,
2299
- requestId: featureFlagDetails.requestId,
2300
- };
2301
- }
2302
- async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2303
- await this._initPromise;
2304
- const extraPayload = {};
2305
- if (disableGeoip ?? this.disableGeoip) {
2306
- extraPayload['geoip_disable'] = true;
2307
- }
2308
- if (flagKeysToEvaluate) {
2309
- extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;
2310
- }
2311
- const decideResponse = await this.getDecide(distinctId, groups, personProperties, groupProperties, extraPayload);
2312
- if (decideResponse === undefined) {
2313
- // We probably errored out, so return undefined
2314
- return undefined;
2315
- }
2316
- // if there's an error on the decideResponse, log a console error, but don't throw an error
2317
- if (decideResponse.errorsWhileComputingFlags) {
2318
- 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');
2319
- }
2320
- // Add check for quota limitation on feature flags
2321
- if (decideResponse.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {
2322
- 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');
2323
- return {
2324
- flags: {},
2325
- featureFlags: {},
2326
- featureFlagPayloads: {},
2327
- requestId: decideResponse?.requestId,
2328
- };
2329
- }
2330
- return decideResponse;
2331
- }
2332
- /***
2333
- *** SURVEYS
2334
- ***/
2335
- async getSurveysStateless() {
2336
- await this._initPromise;
2337
- if (this.disableSurveys === true) {
2338
- this.logMsgIfDebug(() => console.log('Loading surveys is disabled.'));
2339
- return [];
2340
- }
2341
- const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
2342
- const fetchOptions = {
2343
- method: 'GET',
2344
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2345
- };
2346
- const response = await this.fetchWithRetry(url, fetchOptions)
2347
- .then((response) => {
2348
- if (response.status !== 200 || !response.json) {
2349
- const msg = `Surveys API could not be loaded: ${response.status}`;
2350
- const error = new Error(msg);
2351
- this.logMsgIfDebug(() => console.error(error));
2352
- this._events.emit('error', new Error(msg));
2353
- return undefined;
2354
- }
2355
- return response.json();
2356
- })
2357
- .catch((error) => {
2358
- this.logMsgIfDebug(() => console.error('Surveys API could not be loaded', error));
2359
- this._events.emit('error', error);
2360
- return undefined;
2361
- });
2362
- const newSurveys = response?.surveys;
2363
- if (newSurveys) {
2364
- this.logMsgIfDebug(() => console.log('PostHog Debug', 'Surveys fetched from API: ', JSON.stringify(newSurveys)));
2365
- }
2366
- return newSurveys ?? [];
2367
- }
2368
- get props() {
2369
- if (!this._props) {
2370
- this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
2371
- }
2372
- return this._props || {};
2373
- }
2374
- set props(val) {
2375
- this._props = val;
2376
- }
2377
- async register(properties) {
2378
- this.wrap(() => {
2379
- this.props = {
2380
- ...this.props,
2381
- ...properties,
2382
- };
2383
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
2384
- });
2385
- }
2386
- async unregister(property) {
2387
- this.wrap(() => {
2388
- delete this.props[property];
2389
- this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
2390
- });
2391
- }
2392
- /***
2393
- *** QUEUEING AND FLUSHING
2394
- ***/
2395
- enqueue(type, _message, options) {
2396
- this.wrap(() => {
2397
- if (this.optedOut) {
2398
- this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
2399
- return;
2400
- }
2401
- const message = this.prepareMessage(type, _message, options);
2402
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2403
- if (queue.length >= this.maxQueueSize) {
2404
- queue.shift();
2405
- this.logMsgIfDebug(() => console.info('Queue is full, the oldest event is dropped.'));
2406
- }
2407
- queue.push({ message });
2408
- this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
2409
- this._events.emit(type, message);
2410
- // Flush queued events if we meet the flushAt length
2411
- if (queue.length >= this.flushAt) {
2412
- this.flushBackground();
2413
- }
2414
- if (this.flushInterval && !this._flushTimer) {
2415
- this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2416
- }
2417
- });
2418
- }
2419
- async sendImmediate(type, _message, options) {
2420
- if (this.disabled) {
2421
- this.logMsgIfDebug(() => console.warn('[PostHog] The client is disabled'));
2422
- return;
2423
- }
2424
- if (!this._isInitialized) {
2425
- await this._initPromise;
2426
- }
2427
- if (this.optedOut) {
2428
- this._events.emit(type, `Library is disabled. Not sending event. To re-enable, call posthog.optIn()`);
2429
- return;
2430
- }
2431
- const data = {
2432
- api_key: this.apiKey,
2433
- batch: [this.prepareMessage(type, _message, options)],
2434
- sent_at: currentISOTime(),
2435
- };
2436
- if (this.historicalMigration) {
2437
- data.historical_migration = true;
2438
- }
2439
- const payload = JSON.stringify(data);
2440
- const url = this.captureMode === 'form'
2441
- ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
2442
- : `${this.host}/batch/`;
2443
- const fetchOptions = this.captureMode === 'form'
2444
- ? {
2445
- method: 'POST',
2446
- mode: 'no-cors',
2447
- credentials: 'omit',
2448
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' },
2449
- body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
2450
- }
2451
- : {
2452
- method: 'POST',
2453
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2454
- body: payload,
2455
- };
2456
- try {
2457
- await this.fetchWithRetry(url, fetchOptions);
2458
- }
2459
- catch (err) {
2460
- this._events.emit('error', err);
2461
- throw err;
2462
- }
2463
- }
2464
- prepareMessage(type, _message, options) {
2465
- const message = {
2466
- ..._message,
2467
- type: type,
2468
- library: this.getLibraryId(),
2469
- library_version: this.getLibraryVersion(),
2470
- timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2471
- uuid: options?.uuid ? options.uuid : uuidv7(),
2472
- };
2473
- const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2474
- if (addGeoipDisableProperty) {
2475
- if (!message.properties) {
2476
- message.properties = {};
2477
- }
2478
- message['properties']['$geoip_disable'] = true;
2479
- }
2480
- if (message.distinctId) {
2481
- message.distinct_id = message.distinctId;
2482
- delete message.distinctId;
2483
- }
2484
- return message;
2485
- }
2486
- clearFlushTimer() {
2487
- if (this._flushTimer) {
2488
- clearTimeout(this._flushTimer);
2489
- this._flushTimer = undefined;
2490
- }
2491
- }
2492
- /**
2493
- * Helper for flushing the queue in the background
2494
- * Avoids unnecessary promise errors
2495
- */
2496
- flushBackground() {
2497
- void this.flush().catch(async (err) => {
2498
- await logFlushError(err);
2499
- });
2500
- }
2501
- async flush() {
2502
- // Wait for the current flush operation to finish (regardless of success or failure), then try to flush again.
2503
- // Use allSettled instead of finally to be defensive around flush throwing errors immediately rather than rejecting.
2504
- const nextFlushPromise = Promise.allSettled([this.flushPromise]).then(() => {
2505
- return this._flush();
2506
- });
2507
- this.flushPromise = nextFlushPromise;
2508
- void this.addPendingPromise(nextFlushPromise);
2509
- Promise.allSettled([nextFlushPromise]).then(() => {
2510
- // If there are no others waiting to flush, clear the promise.
2511
- // We don't strictly need to do this, but it could make debugging easier
2512
- if (this.flushPromise === nextFlushPromise) {
2513
- this.flushPromise = null;
2514
- }
2515
- });
2516
- return nextFlushPromise;
2517
- }
2518
- getCustomHeaders() {
2519
- // Don't set the user agent if we're not on a browser. The latest spec allows
2520
- // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
2521
- // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
2522
- // but browsers such as Chrome and Safari have not caught up.
2523
- const customUserAgent = this.getCustomUserAgent();
2524
- const headers = {};
2525
- if (customUserAgent && customUserAgent !== '') {
2526
- headers['User-Agent'] = customUserAgent;
2527
- }
2528
- return headers;
2529
- }
2530
- async _flush() {
2531
- this.clearFlushTimer();
2532
- await this._initPromise;
2533
- let queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2534
- if (!queue.length) {
2535
- return [];
2536
- }
2537
- const sentMessages = [];
2538
- const originalQueueLength = queue.length;
2539
- while (queue.length > 0 && sentMessages.length < originalQueueLength) {
2540
- const batchItems = queue.slice(0, this.maxBatchSize);
2541
- const batchMessages = batchItems.map((item) => item.message);
2542
- const persistQueueChange = () => {
2543
- const refreshedQueue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2544
- const newQueue = refreshedQueue.slice(batchItems.length);
2545
- this.setPersistedProperty(PostHogPersistedProperty.Queue, newQueue);
2546
- queue = newQueue;
2547
- };
2548
- const data = {
2549
- api_key: this.apiKey,
2550
- batch: batchMessages,
2551
- sent_at: currentISOTime(),
2552
- };
2553
- if (this.historicalMigration) {
2554
- data.historical_migration = true;
2555
- }
2556
- const payload = JSON.stringify(data);
2557
- const url = this.captureMode === 'form'
2558
- ? `${this.host}/e/?ip=1&_=${currentTimestamp()}&v=${this.getLibraryVersion()}`
2559
- : `${this.host}/batch/`;
2560
- const fetchOptions = this.captureMode === 'form'
2561
- ? {
2562
- method: 'POST',
2563
- mode: 'no-cors',
2564
- credentials: 'omit',
2565
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/x-www-form-urlencoded' },
2566
- body: `data=${encodeURIComponent(LZString.compressToBase64(payload))}&compression=lz64`,
2567
- }
2568
- : {
2569
- method: 'POST',
2570
- headers: { ...this.getCustomHeaders(), 'Content-Type': 'application/json' },
2571
- body: payload,
2572
- };
2573
- const retryOptions = {
2574
- retryCheck: (err) => {
2575
- // don't automatically retry on 413 errors, we want to reduce the batch size first
2576
- if (isPostHogFetchContentTooLargeError(err)) {
2577
- return false;
2578
- }
2579
- // otherwise, retry on network errors
2580
- return isPostHogFetchError(err);
2581
- },
2582
- };
2583
- try {
2584
- await this.fetchWithRetry(url, fetchOptions, retryOptions);
2585
- }
2586
- catch (err) {
2587
- if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2588
- // if we get a 413 error, we want to reduce the batch size and try again
2589
- this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
2590
- this.logMsgIfDebug(() => console.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`));
2591
- // do not persist the queue change, we want to retry the same batch
2592
- continue;
2593
- }
2594
- // depending on the error type, eg a malformed JSON or broken queue, it'll always return an error
2595
- // 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
2596
- if (!(err instanceof PostHogFetchNetworkError)) {
2597
- persistQueueChange();
2598
- }
2599
- this._events.emit('error', err);
2600
- throw err;
2601
- }
2602
- persistQueueChange();
2603
- sentMessages.push(...batchMessages);
2604
- }
2605
- this._events.emit('flush', sentMessages);
2606
- return sentMessages;
2607
- }
2608
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
2609
- var _a;
2610
- (_a = AbortSignal).timeout ?? (_a.timeout = function timeout(ms) {
2611
- const ctrl = new AbortController();
2612
- setTimeout(() => ctrl.abort(), ms);
2613
- return ctrl.signal;
2614
- });
2615
- const body = options.body ? options.body : '';
2616
- const reqByteLength = Buffer.byteLength(body, STRING_FORMAT);
2617
- return await retriable(async () => {
2618
- let res = null;
2619
- try {
2620
- res = await this.fetch(url, {
2621
- signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
2622
- ...options,
2623
- });
2624
- }
2625
- catch (e) {
2626
- // fetch will only throw on network errors or on timeouts
2627
- throw new PostHogFetchNetworkError(e);
2628
- }
2629
- // If we're in no-cors mode, we can't access the response status
2630
- // We only throw on HTTP errors if we're not in no-cors mode
2631
- // https://developer.mozilla.org/en-US/docs/Web/API/Request/mode#no-cors
2632
- const isNoCors = options.mode === 'no-cors';
2633
- if (!isNoCors && (res.status < 200 || res.status >= 400)) {
2634
- throw new PostHogFetchHttpError(res, reqByteLength);
2635
- }
2636
- return res;
2637
- }, { ...this._retryOptions, ...retryOptions });
2638
- }
2639
- async _shutdown(shutdownTimeoutMs = 30000) {
2640
- // A little tricky - we want to have a max shutdown time and enforce it, even if that means we have some
2641
- // dangling promises. We'll keep track of the timeout and resolve/reject based on that.
2642
- await this._initPromise;
2643
- let hasTimedOut = false;
2644
- this.clearFlushTimer();
2645
- const doShutdown = async () => {
2646
- try {
2647
- await Promise.all(Object.values(this.pendingPromises));
2648
- while (true) {
2649
- const queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
2650
- if (queue.length === 0) {
2651
- break;
2652
- }
2653
- // flush again to make sure we send all events, some of which might've been added
2654
- // while we were waiting for the pending promises to resolve
2655
- // For example, see sendFeatureFlags in posthog-node/src/posthog-node.ts::capture
2656
- await this.flush();
2657
- if (hasTimedOut) {
2658
- break;
2659
- }
2660
- }
2661
- }
2662
- catch (e) {
2663
- if (!isPostHogFetchError(e)) {
2664
- throw e;
2665
- }
2666
- await logFlushError(e);
2667
- }
2668
- };
2669
- return Promise.race([
2670
- new Promise((_, reject) => {
2671
- safeSetTimeout(() => {
2672
- this.logMsgIfDebug(() => console.error('Timed out while shutting down PostHog'));
2673
- hasTimedOut = true;
2674
- reject('Timeout while shutting down PostHog. Some events may not have been sent.');
2675
- }, shutdownTimeoutMs);
2676
- }),
2677
- doShutdown(),
2678
- ]);
2679
- }
2680
- /**
2681
- * Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises
2682
- * have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
2683
- * @param shutdownTimeoutMs
2684
- */
2685
- async shutdown(shutdownTimeoutMs = 30000) {
2686
- if (this.shutdownPromise) {
2687
- 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'));
2688
- }
2689
- else {
2690
- this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
2691
- this.shutdownPromise = null;
2692
- });
2693
- }
2694
- return this.shutdownPromise;
2695
- }
2696
- }
2697
-
2698
- /**
2699
- * Fetch wrapper
2700
- *
2701
- * We want to polyfill fetch when not available with axios but use it when it is.
2702
- * NOTE: The current version of Axios has an issue when in non-node environments like Clouflare Workers.
2703
- * This is currently solved by using the global fetch if available instead.
2704
- * See https://github.com/PostHog/posthog-js-lite/issues/127 for more info
2705
- */
2706
- let _fetch = getFetch();
2707
- if (!_fetch) {
2708
- // eslint-disable-next-line @typescript-eslint/no-var-requires
2709
- const axios = require('axios');
2710
- _fetch = async (url, options) => {
2711
- const res = await axios.request({
2712
- url,
2713
- headers: options.headers,
2714
- method: options.method.toLowerCase(),
2715
- data: options.body,
2716
- signal: options.signal,
2717
- // fetch only throws on network errors, not on HTTP errors
2718
- validateStatus: () => true
2719
- });
2720
- return {
2721
- status: res.status,
2722
- text: async () => res.data,
2723
- json: async () => res.data
2724
- };
2725
- };
2726
- }
2727
- // NOTE: We have to export this as default, even though we prefer named exports as we are relying on detecting "fetch" in the global scope
2728
- var fetch$1 = _fetch;
2729
-
2730
- /**
2731
- * A lazy value that is only computed when needed. Inspired by C#'s Lazy<T> class.
2732
- */
2733
- class Lazy {
2734
- constructor(factory) {
2735
- this.factory = factory;
2736
- }
2737
- /**
2738
- * Gets the value, initializing it if necessary.
2739
- * Multiple concurrent calls will share the same initialization promise.
2740
- */
2741
- async getValue() {
2742
- if (this.value !== undefined) {
2743
- return this.value;
2744
- }
2745
- if (this.initializationPromise === undefined) {
2746
- this.initializationPromise = (async () => {
2747
- try {
2748
- const result = await this.factory();
2749
- this.value = result;
2750
- return result;
2751
- } finally {
2752
- // Clear the promise so we can retry if needed
2753
- this.initializationPromise = undefined;
2754
- }
2755
- })();
2756
- }
2757
- return this.initializationPromise;
2758
- }
2759
- /**
2760
- * Returns true if the value has been initialized.
2761
- */
2762
- isInitialized() {
2763
- return this.value !== undefined;
2764
- }
2765
- /**
2766
- * Returns a promise that resolves when the value is initialized.
2767
- * If already initialized, resolves immediately.
2768
- */
2769
- async waitForInitialization() {
2770
- if (this.isInitialized()) {
2771
- return;
2772
- }
2773
- await this.getValue();
2774
- }
2775
- }
2776
-
2777
- /// <reference lib="dom" />
2778
- const nodeCrypto = new Lazy(async () => {
2779
- try {
2780
- return await import('crypto');
2781
- } catch {
2782
- return undefined;
2783
- }
2784
- });
2785
- async function getNodeCrypto() {
2786
- return await nodeCrypto.getValue();
2787
- }
2788
- const webCrypto = new Lazy(async () => {
2789
- if (typeof globalThis.crypto?.subtle !== 'undefined') {
2790
- return globalThis.crypto.subtle;
2791
- }
2792
- try {
2793
- // Node.js: use built-in webcrypto and assign it if needed
2794
- const crypto = await nodeCrypto.getValue();
2795
- if (crypto?.webcrypto?.subtle) {
2796
- return crypto.webcrypto.subtle;
2797
- }
2798
- } catch {
2799
- // Ignore if not available
2800
- }
2801
- return undefined;
2802
- });
2803
- async function getWebCrypto() {
2804
- return await webCrypto.getValue();
2805
- }
2806
-
2807
- /// <reference lib="dom" />
2808
- async function hashSHA1(text) {
2809
- // Try Node.js crypto first
2810
- const nodeCrypto = await getNodeCrypto();
2811
- if (nodeCrypto) {
2812
- return nodeCrypto.createHash('sha1').update(text).digest('hex');
2813
- }
2814
- const webCrypto = await getWebCrypto();
2815
- // Fall back to Web Crypto API
2816
- if (webCrypto) {
2817
- const hashBuffer = await webCrypto.digest('SHA-1', new TextEncoder().encode(text));
2818
- const hashArray = Array.from(new Uint8Array(hashBuffer));
2819
- return hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
2820
- }
2821
- throw new Error('No crypto implementation available. Tried Node Crypto API and Web SubtleCrypto API');
2822
- }
2823
-
2824
- const SIXTY_SECONDS = 60 * 1000;
2825
- // eslint-disable-next-line
2826
- const LONG_SCALE = 0xfffffffffffffff;
2827
- const NULL_VALUES_ALLOWED_OPERATORS = ['is_not'];
2828
- class ClientError extends Error {
2829
- constructor(message) {
2830
- super();
2831
- Error.captureStackTrace(this, this.constructor);
2832
- this.name = 'ClientError';
2833
- this.message = message;
2834
- Object.setPrototypeOf(this, ClientError.prototype);
2835
- }
2836
- }
2837
- class InconclusiveMatchError extends Error {
2838
- constructor(message) {
2839
- super(message);
2840
- this.name = this.constructor.name;
2841
- Error.captureStackTrace(this, this.constructor);
2842
- // instanceof doesn't work in ES3 or ES5
2843
- // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
2844
- // this is the workaround
2845
- Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
2846
- }
2847
- }
2848
- class FeatureFlagsPoller {
2849
- constructor({
2850
- pollingInterval,
2851
- personalApiKey,
2852
- projectApiKey,
2853
- timeout,
2854
- host,
2855
- customHeaders,
2856
- ...options
2857
- }) {
2858
- this.debugMode = false;
2859
- this.shouldBeginExponentialBackoff = false;
2860
- this.backOffCount = 0;
2861
- this.pollingInterval = pollingInterval;
2862
- this.personalApiKey = personalApiKey;
2863
- this.featureFlags = [];
2864
- this.featureFlagsByKey = {};
2865
- this.groupTypeMapping = {};
2866
- this.cohorts = {};
2867
- this.loadedSuccessfullyOnce = false;
2868
- this.timeout = timeout;
2869
- this.projectApiKey = projectApiKey;
2870
- this.host = host;
2871
- this.poller = undefined;
2872
- this.fetch = options.fetch || fetch$1;
2873
- this.onError = options.onError;
2874
- this.customHeaders = customHeaders;
2875
- this.onLoad = options.onLoad;
2876
- void this.loadFeatureFlags();
2877
- }
2878
- debug(enabled = true) {
2879
- this.debugMode = enabled;
2880
- }
2881
- logMsgIfDebug(fn) {
2882
- if (this.debugMode) {
2883
- fn();
2884
- }
2885
- }
2886
- async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2887
- await this.loadFeatureFlags();
2888
- let response = undefined;
2889
- let featureFlag = undefined;
2890
- if (!this.loadedSuccessfullyOnce) {
2891
- return response;
2892
- }
2893
- for (const flag of this.featureFlags) {
2894
- if (key === flag.key) {
2895
- featureFlag = flag;
2896
- break;
2897
- }
2898
- }
2899
- if (featureFlag !== undefined) {
2900
- try {
2901
- response = await this.computeFlagLocally(featureFlag, distinctId, groups, personProperties, groupProperties);
2902
- this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2903
- } catch (e) {
2904
- if (e instanceof InconclusiveMatchError) {
2905
- this.logMsgIfDebug(() => console.debug(`InconclusiveMatchError when computing flag locally: ${key}: ${e}`));
2906
- } else if (e instanceof Error) {
2907
- this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2908
- }
2909
- }
2910
- }
2911
- return response;
2912
- }
2913
- async computeFeatureFlagPayloadLocally(key, matchValue) {
2914
- await this.loadFeatureFlags();
2915
- let response = undefined;
2916
- if (!this.loadedSuccessfullyOnce) {
2917
- return undefined;
2918
- }
2919
- if (typeof matchValue == 'boolean') {
2920
- response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue.toString()];
2921
- } else if (typeof matchValue == 'string') {
2922
- response = this.featureFlagsByKey?.[key]?.filters?.payloads?.[matchValue];
2923
- }
2924
- // Undefined means a loading or missing data issue. Null means evaluation happened and there was no match
2925
- if (response === undefined || response === null) {
2926
- return null;
2927
- }
2928
- try {
2929
- return JSON.parse(response);
2930
- } catch {
2931
- return response;
2932
- }
2933
- }
2934
- async getAllFlagsAndPayloads(distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2935
- await this.loadFeatureFlags();
2936
- const response = {};
2937
- const payloads = {};
2938
- let fallbackToDecide = this.featureFlags.length == 0;
2939
- await Promise.all(this.featureFlags.map(async flag => {
2940
- try {
2941
- const matchValue = await this.computeFlagLocally(flag, distinctId, groups, personProperties, groupProperties);
2942
- response[flag.key] = matchValue;
2943
- const matchPayload = await this.computeFeatureFlagPayloadLocally(flag.key, matchValue);
2944
- if (matchPayload) {
2945
- payloads[flag.key] = matchPayload;
2946
- }
2947
- } catch (e) {
2948
- if (e instanceof InconclusiveMatchError) ; else if (e instanceof Error) {
2949
- this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2950
- }
2951
- fallbackToDecide = true;
2952
- }
2953
- }));
2954
- return {
2955
- response,
2956
- payloads,
2957
- fallbackToDecide
2958
- };
2959
- }
2960
- async computeFlagLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2961
- if (flag.ensure_experience_continuity) {
2962
- throw new InconclusiveMatchError('Flag has experience continuity enabled');
2963
- }
2964
- if (!flag.active) {
2965
- return false;
2966
- }
2967
- const flagFilters = flag.filters || {};
2968
- const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2969
- if (aggregation_group_type_index != undefined) {
2970
- const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2971
- if (!groupName) {
2972
- this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2973
- throw new InconclusiveMatchError('Flag has unknown group type index');
2974
- }
2975
- if (!(groupName in groups)) {
2976
- this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2977
- return false;
2978
- }
2979
- const focusedGroupProperties = groupProperties[groupName];
2980
- return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties);
2981
- } else {
2982
- return await this.matchFeatureFlagProperties(flag, distinctId, personProperties);
2983
- }
2984
- }
2985
- async matchFeatureFlagProperties(flag, distinctId, properties) {
2986
- const flagFilters = flag.filters || {};
2987
- const flagConditions = flagFilters.groups || [];
2988
- let isInconclusive = false;
2989
- let result = undefined;
2990
- // # Stable sort conditions with variant overrides to the top. This ensures that if overrides are present, they are
2991
- // # evaluated first, and the variant override is applied to the first matching condition.
2992
- const sortedFlagConditions = [...flagConditions].sort((conditionA, conditionB) => {
2993
- const AHasVariantOverride = !!conditionA.variant;
2994
- const BHasVariantOverride = !!conditionB.variant;
2995
- if (AHasVariantOverride && BHasVariantOverride) {
2996
- return 0;
2997
- } else if (AHasVariantOverride) {
2998
- return -1;
2999
- } else if (BHasVariantOverride) {
3000
- return 1;
3001
- } else {
3002
- return 0;
3003
- }
3004
- });
3005
- for (const condition of sortedFlagConditions) {
3006
- try {
3007
- if (await this.isConditionMatch(flag, distinctId, condition, properties)) {
3008
- const variantOverride = condition.variant;
3009
- const flagVariants = flagFilters.multivariate?.variants || [];
3010
- if (variantOverride && flagVariants.some(variant => variant.key === variantOverride)) {
3011
- result = variantOverride;
3012
- } else {
3013
- result = (await this.getMatchingVariant(flag, distinctId)) || true;
3014
- }
3015
- break;
3016
- }
3017
- } catch (e) {
3018
- if (e instanceof InconclusiveMatchError) {
3019
- isInconclusive = true;
3020
- } else {
3021
- throw e;
3022
- }
3023
- }
3024
- }
3025
- if (result !== undefined) {
3026
- return result;
3027
- } else if (isInconclusive) {
3028
- throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
3029
- }
3030
- // We can only return False when all conditions are False
3031
- return false;
3032
- }
3033
- async isConditionMatch(flag, distinctId, condition, properties) {
3034
- const rolloutPercentage = condition.rollout_percentage;
3035
- const warnFunction = msg => {
3036
- this.logMsgIfDebug(() => console.warn(msg));
3037
- };
3038
- if ((condition.properties || []).length > 0) {
3039
- for (const prop of condition.properties) {
3040
- const propertyType = prop.type;
3041
- let matches = false;
3042
- if (propertyType === 'cohort') {
3043
- matches = matchCohort(prop, properties, this.cohorts, this.debugMode);
3044
- } else {
3045
- matches = matchProperty(prop, properties, warnFunction);
3046
- }
3047
- if (!matches) {
3048
- return false;
3049
- }
3050
- }
3051
- if (rolloutPercentage == undefined) {
3052
- return true;
3053
- }
3054
- }
3055
- if (rolloutPercentage != undefined && (await _hash(flag.key, distinctId)) > rolloutPercentage / 100.0) {
3056
- return false;
3057
- }
3058
- return true;
3059
- }
3060
- async getMatchingVariant(flag, distinctId) {
3061
- const hashValue = await _hash(flag.key, distinctId, 'variant');
3062
- const matchingVariant = this.variantLookupTable(flag).find(variant => {
3063
- return hashValue >= variant.valueMin && hashValue < variant.valueMax;
3064
- });
3065
- if (matchingVariant) {
3066
- return matchingVariant.key;
3067
- }
3068
- return undefined;
3069
- }
3070
- variantLookupTable(flag) {
3071
- const lookupTable = [];
3072
- let valueMin = 0;
3073
- let valueMax = 0;
3074
- const flagFilters = flag.filters || {};
3075
- const multivariates = flagFilters.multivariate?.variants || [];
3076
- multivariates.forEach(variant => {
3077
- valueMax = valueMin + variant.rollout_percentage / 100.0;
3078
- lookupTable.push({
3079
- valueMin,
3080
- valueMax,
3081
- key: variant.key
3082
- });
3083
- valueMin = valueMax;
3084
- });
3085
- return lookupTable;
3086
- }
3087
- async loadFeatureFlags(forceReload = false) {
3088
- if (!this.loadedSuccessfullyOnce || forceReload) {
3089
- await this._loadFeatureFlags();
3090
- }
3091
- }
3092
- /**
3093
- * Returns true if the feature flags poller has loaded successfully at least once and has more than 0 feature flags.
3094
- * This is useful to check if local evaluation is ready before calling getFeatureFlag.
3095
- */
3096
- isLocalEvaluationReady() {
3097
- return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
3098
- }
3099
- /**
3100
- * If a client is misconfigured with an invalid or improper API key, the polling interval is doubled each time
3101
- * until a successful request is made, up to a maximum of 60 seconds.
3102
- *
3103
- * @returns The polling interval to use for the next request.
3104
- */
3105
- getPollingInterval() {
3106
- if (!this.shouldBeginExponentialBackoff) {
3107
- return this.pollingInterval;
3108
- }
3109
- return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
3110
- }
3111
- async _loadFeatureFlags() {
3112
- if (this.poller) {
3113
- clearTimeout(this.poller);
3114
- this.poller = undefined;
3115
- }
3116
- this.poller = setTimeout(() => this._loadFeatureFlags(), this.getPollingInterval());
3117
- try {
3118
- const res = await this._requestFeatureFlagDefinitions();
3119
- // Handle undefined res case, this shouldn't happen, but it doesn't hurt to handle it anyway
3120
- if (!res) {
3121
- // Don't override existing flags when something goes wrong
3122
- return;
3123
- }
3124
- // NB ON ERROR HANDLING & `loadedSuccessfullyOnce`:
3125
- //
3126
- // `loadedSuccessfullyOnce` indicates we've successfully loaded a valid set of flags at least once.
3127
- // If we set it to `true` in an error scenario (e.g. 402 Over Quota, 401 Invalid Key, etc.),
3128
- // any manual call to `loadFeatureFlags()` (without forceReload) will skip refetching entirely,
3129
- // leaving us stuck with zero or outdated flags. The poller does keep running, but we also want
3130
- // manual reloads to be possible as soon as the error condition is resolved.
3131
- //
3132
- // Therefore, on error statuses, we do *not* set `loadedSuccessfullyOnce = true`, ensuring that
3133
- // both the background poller and any subsequent manual calls can keep trying to load flags
3134
- // once the issue (quota, permission, rate limit, etc.) is resolved.
3135
- switch (res.status) {
3136
- case 401:
3137
- // Invalid API key
3138
- this.shouldBeginExponentialBackoff = true;
3139
- this.backOffCount += 1;
3140
- 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`);
3141
- case 402:
3142
- // Quota exceeded - clear all flags
3143
- 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');
3144
- this.featureFlags = [];
3145
- this.featureFlagsByKey = {};
3146
- this.groupTypeMapping = {};
3147
- this.cohorts = {};
3148
- return;
3149
- case 403:
3150
- // Permissions issue
3151
- this.shouldBeginExponentialBackoff = true;
3152
- this.backOffCount += 1;
3153
- 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`);
3154
- case 429:
3155
- // Rate limited
3156
- this.shouldBeginExponentialBackoff = true;
3157
- this.backOffCount += 1;
3158
- 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`);
3159
- case 200:
3160
- {
3161
- // Process successful response
3162
- const responseJson = await res.json();
3163
- if (!('flags' in responseJson)) {
3164
- this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
3165
- return;
3166
- }
3167
- this.featureFlags = responseJson.flags || [];
3168
- this.featureFlagsByKey = this.featureFlags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
3169
- this.groupTypeMapping = responseJson.group_type_mapping || {};
3170
- this.cohorts = responseJson.cohorts || {};
3171
- this.loadedSuccessfullyOnce = true;
3172
- this.shouldBeginExponentialBackoff = false;
3173
- this.backOffCount = 0;
3174
- this.onLoad?.(this.featureFlags.length);
3175
- break;
3176
- }
3177
- default:
3178
- // Something else went wrong, or the server is down.
3179
- // In this case, don't override existing flags
3180
- return;
3181
- }
3182
- } catch (err) {
3183
- if (err instanceof ClientError) {
3184
- this.onError?.(err);
3185
- }
3186
- }
3187
- }
3188
- getPersonalApiKeyRequestOptions(method = 'GET') {
3189
- return {
3190
- method,
3191
- headers: {
3192
- ...this.customHeaders,
3193
- 'Content-Type': 'application/json',
3194
- Authorization: `Bearer ${this.personalApiKey}`
3195
- }
3196
- };
3197
- }
3198
- async _requestFeatureFlagDefinitions() {
3199
- const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
3200
- const options = this.getPersonalApiKeyRequestOptions();
3201
- let abortTimeout = null;
3202
- if (this.timeout && typeof this.timeout === 'number') {
3203
- const controller = new AbortController();
3204
- abortTimeout = safeSetTimeout(() => {
3205
- controller.abort();
3206
- }, this.timeout);
3207
- options.signal = controller.signal;
3208
- }
3209
- try {
3210
- return await this.fetch(url, options);
3211
- } finally {
3212
- clearTimeout(abortTimeout);
3213
- }
3214
- }
3215
- stopPoller() {
3216
- clearTimeout(this.poller);
3217
- }
3218
- _requestRemoteConfigPayload(flagKey) {
3219
- const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config/`;
3220
- const options = this.getPersonalApiKeyRequestOptions();
3221
- let abortTimeout = null;
3222
- if (this.timeout && typeof this.timeout === 'number') {
3223
- const controller = new AbortController();
3224
- abortTimeout = safeSetTimeout(() => {
3225
- controller.abort();
3226
- }, this.timeout);
3227
- options.signal = controller.signal;
3228
- }
3229
- try {
3230
- return this.fetch(url, options);
3231
- } finally {
3232
- clearTimeout(abortTimeout);
3233
- }
3234
- }
3235
- }
3236
- // # This function takes a distinct_id and a feature flag key and returns a float between 0 and 1.
3237
- // # Given the same distinct_id and key, it'll always return the same float. These floats are
3238
- // # uniformly distributed between 0 and 1, so if we want to show this feature to 20% of traffic
3239
- // # we can do _hash(key, distinct_id) < 0.2
3240
- async function _hash(key, distinctId, salt = '') {
3241
- const hashString = await hashSHA1(`${key}.${distinctId}${salt}`);
3242
- return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
3243
- }
3244
- function matchProperty(property, propertyValues, warnFunction) {
3245
- const key = property.key;
3246
- const value = property.value;
3247
- const operator = property.operator || 'exact';
3248
- if (!(key in propertyValues)) {
3249
- throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
3250
- } else if (operator === 'is_not_set') {
3251
- throw new InconclusiveMatchError(`Operator is_not_set is not supported`);
3252
- }
3253
- const overrideValue = propertyValues[key];
3254
- if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
3255
- // if the value is null, just fail the feature flag comparison
3256
- // this isn't an InconclusiveMatchError because the property value was provided.
3257
- if (warnFunction) {
3258
- warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
3259
- }
3260
- return false;
3261
- }
3262
- function computeExactMatch(value, overrideValue) {
3263
- if (Array.isArray(value)) {
3264
- return value.map(val => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
3265
- }
3266
- return String(value).toLowerCase() === String(overrideValue).toLowerCase();
3267
- }
3268
- function compare(lhs, rhs, operator) {
3269
- if (operator === 'gt') {
3270
- return lhs > rhs;
3271
- } else if (operator === 'gte') {
3272
- return lhs >= rhs;
3273
- } else if (operator === 'lt') {
3274
- return lhs < rhs;
3275
- } else if (operator === 'lte') {
3276
- return lhs <= rhs;
3277
- } else {
3278
- throw new Error(`Invalid operator: ${operator}`);
3279
- }
3280
- }
3281
- switch (operator) {
3282
- case 'exact':
3283
- return computeExactMatch(value, overrideValue);
3284
- case 'is_not':
3285
- return !computeExactMatch(value, overrideValue);
3286
- case 'is_set':
3287
- return key in propertyValues;
3288
- case 'icontains':
3289
- return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3290
- case 'not_icontains':
3291
- return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3292
- case 'regex':
3293
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
3294
- case 'not_regex':
3295
- return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
3296
- case 'gt':
3297
- case 'gte':
3298
- case 'lt':
3299
- case 'lte':
3300
- {
3301
- // :TRICKY: We adjust comparison based on the override value passed in,
3302
- // to make sure we handle both numeric and string comparisons appropriately.
3303
- let parsedValue = typeof value === 'number' ? value : null;
3304
- if (typeof value === 'string') {
3305
- try {
3306
- parsedValue = parseFloat(value);
3307
- } catch (err) {
3308
- // pass
3309
- }
3310
- }
3311
- if (parsedValue != null && overrideValue != null) {
3312
- // check both null and undefined
3313
- if (typeof overrideValue === 'string') {
3314
- return compare(overrideValue, String(value), operator);
3315
- } else {
3316
- return compare(overrideValue, parsedValue, operator);
3317
- }
3318
- } else {
3319
- return compare(String(overrideValue), String(value), operator);
3320
- }
3321
- }
3322
- case 'is_date_after':
3323
- case 'is_date_before':
3324
- {
3325
- let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
3326
- if (parsedDate == null) {
3327
- parsedDate = convertToDateTime(value);
3328
- }
3329
- if (parsedDate == null) {
3330
- throw new InconclusiveMatchError(`Invalid date: ${value}`);
3331
- }
3332
- const overrideDate = convertToDateTime(overrideValue);
3333
- if (['is_date_before'].includes(operator)) {
3334
- return overrideDate < parsedDate;
3335
- }
3336
- return overrideDate > parsedDate;
3337
- }
3338
- default:
3339
- throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
3340
- }
3341
- }
3342
- function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
3343
- const cohortId = String(property.value);
3344
- if (!(cohortId in cohortProperties)) {
3345
- throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
3346
- }
3347
- const propertyGroup = cohortProperties[cohortId];
3348
- return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
3349
- }
3350
- function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
3351
- if (!propertyGroup) {
3352
- return true;
3353
- }
3354
- const propertyGroupType = propertyGroup.type;
3355
- const properties = propertyGroup.values;
3356
- if (!properties || properties.length === 0) {
3357
- // empty groups are no-ops, always match
3358
- return true;
3359
- }
3360
- let errorMatchingLocally = false;
3361
- if ('values' in properties[0]) {
3362
- // a nested property group
3363
- for (const prop of properties) {
3364
- try {
3365
- const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
3366
- if (propertyGroupType === 'AND') {
3367
- if (!matches) {
3368
- return false;
3369
- }
3370
- } else {
3371
- // OR group
3372
- if (matches) {
3373
- return true;
3374
- }
3375
- }
3376
- } catch (err) {
3377
- if (err instanceof InconclusiveMatchError) {
3378
- if (debugMode) {
3379
- console.debug(`Failed to compute property ${prop} locally: ${err}`);
3380
- }
3381
- errorMatchingLocally = true;
3382
- } else {
3383
- throw err;
3384
- }
3385
- }
3386
- }
3387
- if (errorMatchingLocally) {
3388
- throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
3389
- }
3390
- // if we get here, all matched in AND case, or none matched in OR case
3391
- return propertyGroupType === 'AND';
3392
- } else {
3393
- for (const prop of properties) {
3394
- try {
3395
- let matches;
3396
- if (prop.type === 'cohort') {
3397
- matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
3398
- } else {
3399
- matches = matchProperty(prop, propertyValues);
3400
- }
3401
- const negation = prop.negation || false;
3402
- if (propertyGroupType === 'AND') {
3403
- // if negated property, do the inverse
3404
- if (!matches && !negation) {
3405
- return false;
3406
- }
3407
- if (matches && negation) {
3408
- return false;
3409
- }
3410
- } else {
3411
- // OR group
3412
- if (matches && !negation) {
3413
- return true;
3414
- }
3415
- if (!matches && negation) {
3416
- return true;
3417
- }
3418
- }
3419
- } catch (err) {
3420
- if (err instanceof InconclusiveMatchError) {
3421
- if (debugMode) {
3422
- console.debug(`Failed to compute property ${prop} locally: ${err}`);
3423
- }
3424
- errorMatchingLocally = true;
3425
- } else {
3426
- throw err;
3427
- }
3428
- }
3429
- }
3430
- if (errorMatchingLocally) {
3431
- throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
3432
- }
3433
- // if we get here, all matched in AND case, or none matched in OR case
3434
- return propertyGroupType === 'AND';
3435
- }
3436
- }
3437
- function isValidRegex(regex) {
3438
- try {
3439
- new RegExp(regex);
3440
- return true;
3441
- } catch (err) {
3442
- return false;
3443
- }
3444
- }
3445
- function convertToDateTime(value) {
3446
- if (value instanceof Date) {
3447
- return value;
3448
- } else if (typeof value === 'string' || typeof value === 'number') {
3449
- const date = new Date(value);
3450
- if (!isNaN(date.valueOf())) {
3451
- return date;
3452
- }
3453
- throw new InconclusiveMatchError(`${value} is in an invalid date format`);
3454
- } else {
3455
- throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
3456
- }
3457
- }
3458
- function relativeDateParseForFeatureFlagMatching(value) {
3459
- const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
3460
- const match = value.match(regex);
3461
- const parsedDt = new Date(new Date().toISOString());
3462
- if (match) {
3463
- if (!match.groups) {
3464
- return null;
3465
- }
3466
- const number = parseInt(match.groups['number']);
3467
- if (number >= 10000) {
3468
- // Guard against overflow, disallow numbers greater than 10_000
3469
- return null;
3470
- }
3471
- const interval = match.groups['interval'];
3472
- if (interval == 'h') {
3473
- parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
3474
- } else if (interval == 'd') {
3475
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
3476
- } else if (interval == 'w') {
3477
- parsedDt.setUTCDate(parsedDt.getUTCDate() - number * 7);
3478
- } else if (interval == 'm') {
3479
- parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
3480
- } else if (interval == 'y') {
3481
- parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
3482
- } else {
3483
- return null;
3484
- }
3485
- return parsedDt;
3486
- } else {
3487
- return null;
3488
- }
3489
- }
3490
-
3491
- class PostHogMemoryStorage {
3492
- constructor() {
3493
- this._memoryStorage = {};
3494
- }
3495
- getProperty(key) {
3496
- return this._memoryStorage[key];
3497
- }
3498
- setProperty(key, value) {
3499
- this._memoryStorage[key] = value !== null ? value : undefined;
3500
- }
3501
- }
3502
-
3503
- // Standard local evaluation rate limit is 600 per minute (10 per second),
3504
- // so the fastest a poller should ever be set is 100ms.
3505
- const MINIMUM_POLLING_INTERVAL = 100;
3506
- const THIRTY_SECONDS = 30 * 1000;
3507
- const MAX_CACHE_SIZE = 50 * 1000;
3508
- // The actual exported Nodejs API.
3509
- class PostHogBackendClient extends PostHogCoreStateless {
3510
- constructor(apiKey, options = {}) {
3511
- super(apiKey, options);
3512
- this._memoryStorage = new PostHogMemoryStorage();
3513
- this.options = options;
3514
- this.options.featureFlagsPollingInterval = typeof options.featureFlagsPollingInterval === 'number' ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
3515
- if (options.personalApiKey) {
3516
- if (options.personalApiKey.includes('phc_')) {
3517
- throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
3518
- }
3519
- this.featureFlagsPoller = new FeatureFlagsPoller({
3520
- pollingInterval: this.options.featureFlagsPollingInterval,
3521
- personalApiKey: options.personalApiKey,
3522
- projectApiKey: apiKey,
3523
- timeout: options.requestTimeout ?? 10000,
3524
- host: this.host,
3525
- fetch: options.fetch,
3526
- onError: err => {
3527
- this._events.emit('error', err);
3528
- },
3529
- onLoad: count => {
3530
- this._events.emit('localEvaluationFlagsLoaded', count);
3531
- },
3532
- customHeaders: this.getCustomHeaders()
3533
- });
3534
- }
3535
- this.errorTracking = new ErrorTracking(this, options);
3536
- this.distinctIdHasSentFlagCalls = {};
3537
- this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
3538
- }
3539
- getPersistedProperty(key) {
3540
- return this._memoryStorage.getProperty(key);
3541
- }
3542
- setPersistedProperty(key, value) {
3543
- return this._memoryStorage.setProperty(key, value);
3544
- }
3545
- fetch(url, options) {
3546
- return this.options.fetch ? this.options.fetch(url, options) : fetch$1(url, options);
3547
- }
3548
- getLibraryVersion() {
3549
- return version;
3550
- }
3551
- getCustomUserAgent() {
3552
- return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
3553
- }
3554
- enable() {
3555
- return super.optIn();
3556
- }
3557
- disable() {
3558
- return super.optOut();
3559
- }
3560
- debug(enabled = true) {
3561
- super.debug(enabled);
3562
- this.featureFlagsPoller?.debug(enabled);
3563
- }
3564
- capture(props) {
3565
- if (typeof props === 'string') {
3566
- this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
3567
- }
3568
- const {
3569
- distinctId,
3570
- event,
3571
- properties,
3572
- groups,
3573
- sendFeatureFlags,
3574
- timestamp,
3575
- disableGeoip,
3576
- uuid
3577
- } = props;
3578
- const _capture = props => {
3579
- super.captureStateless(distinctId, event, props, {
3580
- timestamp,
3581
- disableGeoip,
3582
- uuid
3583
- });
3584
- };
3585
- const _getFlags = async (distinctId, groups, disableGeoip) => {
3586
- return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
3587
- };
3588
- // :TRICKY: If we flush, or need to shut down, to not lose events we want this promise to resolve before we flush
3589
- const capturePromise = Promise.resolve().then(async () => {
3590
- if (sendFeatureFlags) {
3591
- // If we are sending feature flags, we need to make sure we have the latest flags
3592
- // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
3593
- return await _getFlags(distinctId, groups, disableGeoip);
3594
- }
3595
- if (event === '$feature_flag_called') {
3596
- // 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.
3597
- return {};
3598
- }
3599
- if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3600
- // Otherwise we may as well check for the flags locally and include them if they are already loaded
3601
- const groupsWithStringValues = {};
3602
- for (const [key, value] of Object.entries(groups || {})) {
3603
- groupsWithStringValues[key] = String(value);
3604
- }
3605
- return await this.getAllFlags(distinctId, {
3606
- groups: groupsWithStringValues,
3607
- disableGeoip,
3608
- onlyEvaluateLocally: true
3609
- });
3610
- }
3611
- return {};
3612
- }).then(flags => {
3613
- // Derive the relevant flag properties to add
3614
- const additionalProperties = {};
3615
- if (flags) {
3616
- for (const [feature, variant] of Object.entries(flags)) {
3617
- additionalProperties[`$feature/${feature}`] = variant;
3618
- }
3619
- }
3620
- const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
3621
- if (activeFlags.length > 0) {
3622
- additionalProperties['$active_feature_flags'] = activeFlags;
3623
- }
3624
- return additionalProperties;
3625
- }).catch(() => {
3626
- // Something went wrong getting the flag info - we should capture the event anyways
3627
- return {};
3628
- }).then(additionalProperties => {
3629
- // No matter what - capture the event
3630
- _capture({
3631
- ...additionalProperties,
3632
- ...properties,
3633
- $groups: groups
3634
- });
3635
- });
3636
- this.addPendingPromise(capturePromise);
3637
- }
3638
- async captureImmediate(props) {
3639
- if (typeof props === 'string') {
3640
- this.logMsgIfDebug(() => console.warn('Called capture() with a string as the first argument when an object was expected.'));
3641
- }
3642
- const {
3643
- distinctId,
3644
- event,
3645
- properties,
3646
- groups,
3647
- sendFeatureFlags,
3648
- timestamp,
3649
- disableGeoip,
3650
- uuid
3651
- } = props;
3652
- const _capture = props => {
3653
- return super.captureStatelessImmediate(distinctId, event, props, {
3654
- timestamp,
3655
- disableGeoip,
3656
- uuid
3657
- });
3658
- };
3659
- const _getFlags = async (distinctId, groups, disableGeoip) => {
3660
- return (await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)).flags;
3661
- };
3662
- const capturePromise = Promise.resolve().then(async () => {
3663
- if (sendFeatureFlags) {
3664
- // If we are sending feature flags, we need to make sure we have the latest flags
3665
- // return await super.getFeatureFlagsStateless(distinctId, groups, undefined, undefined, disableGeoip)
3666
- return await _getFlags(distinctId, groups, disableGeoip);
3667
- }
3668
- if (event === '$feature_flag_called') {
3669
- // 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.
3670
- return {};
3671
- }
3672
- if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3673
- // Otherwise we may as well check for the flags locally and include them if they are already loaded
3674
- const groupsWithStringValues = {};
3675
- for (const [key, value] of Object.entries(groups || {})) {
3676
- groupsWithStringValues[key] = String(value);
3677
- }
3678
- return await this.getAllFlags(distinctId, {
3679
- groups: groupsWithStringValues,
3680
- disableGeoip,
3681
- onlyEvaluateLocally: true
3682
- });
3683
- }
3684
- return {};
3685
- }).then(flags => {
3686
- // Derive the relevant flag properties to add
3687
- const additionalProperties = {};
3688
- if (flags) {
3689
- for (const [feature, variant] of Object.entries(flags)) {
3690
- additionalProperties[`$feature/${feature}`] = variant;
3691
- }
3692
- }
3693
- const activeFlags = Object.keys(flags || {}).filter(flag => flags?.[flag] !== false).sort();
3694
- if (activeFlags.length > 0) {
3695
- additionalProperties['$active_feature_flags'] = activeFlags;
3696
- }
3697
- return additionalProperties;
3698
- }).catch(() => {
3699
- // Something went wrong getting the flag info - we should capture the event anyways
3700
- return {};
3701
- }).then(additionalProperties => {
3702
- // No matter what - capture the event
3703
- _capture({
3704
- ...additionalProperties,
3705
- ...properties,
3706
- $groups: groups
3707
- });
3708
- });
3709
- await capturePromise;
3710
- }
3711
- identify({
3712
- distinctId,
3713
- properties,
3714
- disableGeoip
3715
- }) {
3716
- // Catch properties passed as $set and move them to the top level
3717
- // promote $set and $set_once to top level
3718
- const userPropsOnce = properties?.$set_once;
3719
- delete properties?.$set_once;
3720
- // if no $set is provided we assume all properties are $set
3721
- const userProps = properties?.$set || properties;
3722
- super.identifyStateless(distinctId, {
3723
- $set: userProps,
3724
- $set_once: userPropsOnce
3725
- }, {
3726
- disableGeoip
3727
- });
3728
- }
3729
- async identifyImmediate({
3730
- distinctId,
3731
- properties,
3732
- disableGeoip
3733
- }) {
3734
- // promote $set and $set_once to top level
3735
- const userPropsOnce = properties?.$set_once;
3736
- delete properties?.$set_once;
3737
- // if no $set is provided we assume all properties are $set
3738
- const userProps = properties?.$set || properties;
3739
- await super.identifyStatelessImmediate(distinctId, {
3740
- $set: userProps,
3741
- $set_once: userPropsOnce
3742
- }, {
3743
- disableGeoip
3744
- });
3745
- }
3746
- alias(data) {
3747
- super.aliasStateless(data.alias, data.distinctId, undefined, {
3748
- disableGeoip: data.disableGeoip
3749
- });
3750
- }
3751
- async aliasImmediate(data) {
3752
- await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
3753
- disableGeoip: data.disableGeoip
3754
- });
3755
- }
3756
- isLocalEvaluationReady() {
3757
- return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
3758
- }
3759
- async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
3760
- if (this.isLocalEvaluationReady()) {
3761
- return true;
3762
- }
3763
- if (this.featureFlagsPoller === undefined) {
3764
- return false;
3765
- }
3766
- return new Promise(resolve => {
3767
- const timeout = setTimeout(() => {
3768
- cleanup();
3769
- resolve(false);
3770
- }, timeoutMs);
3771
- const cleanup = this._events.on('localEvaluationFlagsLoaded', count => {
3772
- clearTimeout(timeout);
3773
- cleanup();
3774
- resolve(count > 0);
3775
- });
3776
- });
3777
- }
3778
- async getFeatureFlag(key, distinctId, options) {
3779
- const {
3780
- groups,
3781
- disableGeoip
3782
- } = options || {};
3783
- let {
3784
- onlyEvaluateLocally,
3785
- sendFeatureFlagEvents,
3786
- personProperties,
3787
- groupProperties
3788
- } = options || {};
3789
- const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3790
- personProperties = adjustedProperties.allPersonProperties;
3791
- groupProperties = adjustedProperties.allGroupProperties;
3792
- // set defaults
3793
- if (onlyEvaluateLocally == undefined) {
3794
- onlyEvaluateLocally = false;
3795
- }
3796
- if (sendFeatureFlagEvents == undefined) {
3797
- sendFeatureFlagEvents = true;
3798
- }
3799
- let response = await this.featureFlagsPoller?.getFeatureFlag(key, distinctId, groups, personProperties, groupProperties);
3800
- const flagWasLocallyEvaluated = response !== undefined;
3801
- let requestId = undefined;
3802
- let flagDetail = undefined;
3803
- if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
3804
- const remoteResponse = await super.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3805
- if (remoteResponse === undefined) {
3806
- return undefined;
3807
- }
3808
- flagDetail = remoteResponse.response;
3809
- response = getFeatureFlagValue(flagDetail);
3810
- requestId = remoteResponse?.requestId;
3811
- }
3812
- const featureFlagReportedKey = `${key}_${response}`;
3813
- if (sendFeatureFlagEvents && (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))) {
3814
- if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) {
3815
- this.distinctIdHasSentFlagCalls = {};
3816
- }
3817
- if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) {
3818
- this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
3819
- } else {
3820
- this.distinctIdHasSentFlagCalls[distinctId] = [featureFlagReportedKey];
3821
- }
3822
- this.capture({
3823
- distinctId,
3824
- event: '$feature_flag_called',
3825
- properties: {
3826
- $feature_flag: key,
3827
- $feature_flag_response: response,
3828
- $feature_flag_id: flagDetail?.metadata?.id,
3829
- $feature_flag_version: flagDetail?.metadata?.version,
3830
- $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,
3831
- locally_evaluated: flagWasLocallyEvaluated,
3832
- [`$feature/${key}`]: response,
3833
- $feature_flag_request_id: requestId
3834
- },
3835
- groups,
3836
- disableGeoip
3837
- });
3838
- }
3839
- return response;
3840
- }
3841
- async getFeatureFlagPayload(key, distinctId, matchValue, options) {
3842
- const {
3843
- groups,
3844
- disableGeoip
3845
- } = options || {};
3846
- let {
3847
- onlyEvaluateLocally,
3848
- sendFeatureFlagEvents,
3849
- personProperties,
3850
- groupProperties
3851
- } = options || {};
3852
- const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3853
- personProperties = adjustedProperties.allPersonProperties;
3854
- groupProperties = adjustedProperties.allGroupProperties;
3855
- let response = undefined;
3856
- const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
3857
- if (localEvaluationEnabled) {
3858
- // Try to get match value locally if not provided
3859
- if (!matchValue) {
3860
- matchValue = await this.getFeatureFlag(key, distinctId, {
3861
- ...options,
3862
- onlyEvaluateLocally: true,
3863
- sendFeatureFlagEvents: false
3864
- });
3865
- }
3866
- if (matchValue) {
3867
- response = await this.featureFlagsPoller?.computeFeatureFlagPayloadLocally(key, matchValue);
3868
- }
3869
- }
3870
- //}
3871
- // set defaults
3872
- if (onlyEvaluateLocally == undefined) {
3873
- onlyEvaluateLocally = false;
3874
- }
3875
- if (sendFeatureFlagEvents == undefined) {
3876
- sendFeatureFlagEvents = true;
3877
- }
3878
- // set defaults
3879
- if (onlyEvaluateLocally == undefined) {
3880
- onlyEvaluateLocally = false;
3881
- }
3882
- const payloadWasLocallyEvaluated = response !== undefined;
3883
- if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) {
3884
- response = await super.getFeatureFlagPayloadStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
3885
- }
3886
- return response;
3887
- }
3888
- async getRemoteConfigPayload(flagKey) {
3889
- return (await this.featureFlagsPoller?._requestRemoteConfigPayload(flagKey))?.json();
3890
- }
3891
- async isFeatureEnabled(key, distinctId, options) {
3892
- const feat = await this.getFeatureFlag(key, distinctId, options);
3893
- if (feat === undefined) {
3894
- return undefined;
3895
- }
3896
- return !!feat || false;
3897
- }
3898
- async getAllFlags(distinctId, options) {
3899
- const response = await this.getAllFlagsAndPayloads(distinctId, options);
3900
- return response.featureFlags || {};
3901
- }
3902
- async getAllFlagsAndPayloads(distinctId, options) {
3903
- const {
3904
- groups,
3905
- disableGeoip
3906
- } = options || {};
3907
- let {
3908
- onlyEvaluateLocally,
3909
- personProperties,
3910
- groupProperties
3911
- } = options || {};
3912
- const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3913
- personProperties = adjustedProperties.allPersonProperties;
3914
- groupProperties = adjustedProperties.allGroupProperties;
3915
- // set defaults
3916
- if (onlyEvaluateLocally == undefined) {
3917
- onlyEvaluateLocally = false;
3918
- }
3919
- const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(distinctId, groups, personProperties, groupProperties);
3920
- let featureFlags = {};
3921
- let featureFlagPayloads = {};
3922
- let fallbackToDecide = true;
3923
- if (localEvaluationResult) {
3924
- featureFlags = localEvaluationResult.response;
3925
- featureFlagPayloads = localEvaluationResult.payloads;
3926
- fallbackToDecide = localEvaluationResult.fallbackToDecide;
3927
- }
3928
- if (fallbackToDecide && !onlyEvaluateLocally) {
3929
- const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip);
3930
- featureFlags = {
3931
- ...featureFlags,
3932
- ...(remoteEvaluationResult.flags || {})
3933
- };
3934
- featureFlagPayloads = {
3935
- ...featureFlagPayloads,
3936
- ...(remoteEvaluationResult.payloads || {})
3937
- };
3938
- }
3939
- return {
3940
- featureFlags,
3941
- featureFlagPayloads
3942
- };
3943
- }
3944
- groupIdentify({
3945
- groupType,
3946
- groupKey,
3947
- properties,
3948
- distinctId,
3949
- disableGeoip
3950
- }) {
3951
- super.groupIdentifyStateless(groupType, groupKey, properties, {
3952
- disableGeoip
3953
- }, distinctId);
3954
- }
3955
- /**
3956
- * Reloads the feature flag definitions from the server for local evaluation.
3957
- * This is useful to call if you want to ensure that the feature flags are up to date before calling getFeatureFlag.
3958
- */
3959
- async reloadFeatureFlags() {
3960
- await this.featureFlagsPoller?.loadFeatureFlags(true);
3961
- }
3962
- async _shutdown(shutdownTimeoutMs) {
3963
- this.featureFlagsPoller?.stopPoller();
3964
- return super._shutdown(shutdownTimeoutMs);
3965
- }
3966
- addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3967
- const allPersonProperties = {
3968
- distinct_id: distinctId,
3969
- ...(personProperties || {})
3970
- };
3971
- const allGroupProperties = {};
3972
- if (groups) {
3973
- for (const groupName of Object.keys(groups)) {
3974
- allGroupProperties[groupName] = {
3975
- $group_key: groups[groupName],
3976
- ...(groupProperties?.[groupName] || {})
3977
- };
3978
- }
3979
- }
3980
- return {
3981
- allPersonProperties,
3982
- allGroupProperties
3983
- };
3984
- }
3985
- captureException(error, distinctId, additionalProperties) {
3986
- const syntheticException = new Error('PostHog syntheticException');
3987
- ErrorTracking.captureException(this, error, {
3988
- syntheticException
3989
- }, distinctId, additionalProperties);
3990
- }
3991
- }
3992
-
3993
- // Portions of this file are derived from getsentry/sentry-javascript by Software, Inc. dba Sentry
3994
- // Licensed under the MIT License
3995
- // This was originally forked from https://github.com/csnover/TraceKit, and was largely
3996
- // re-written as part of raven - js.
3997
- //
3998
- // This code was later copied to the JavaScript mono - repo and further modified and
3999
- // refactored over the years.
4000
- // Copyright (c) 2013 Onur Can Cakmak onur.cakmak@gmail.com and all TraceKit contributors.
4001
- //
4002
- // Permission is hereby granted, free of charge, to any person obtaining a copy of this
4003
- // software and associated documentation files(the 'Software'), to deal in the Software
4004
- // without restriction, including without limitation the rights to use, copy, modify,
4005
- // merge, publish, distribute, sublicense, and / or sell copies of the Software, and to
4006
- // permit persons to whom the Software is furnished to do so, subject to the following
4007
- // conditions:
4008
- //
4009
- // The above copyright notice and this permission notice shall be included in all copies
4010
- // or substantial portions of the Software.
4011
- //
4012
- // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
4013
- // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
4014
- // PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
4015
- // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
4016
- // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
4017
- // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4018
- const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
4019
- const STACKTRACE_FRAME_LIMIT = 50;
4020
- const UNKNOWN_FUNCTION = '?';
4021
- /** Node Stack line parser */
4022
- function node(getModule) {
4023
- const FILENAME_MATCH = /^\s*[-]{4,}$/;
4024
- const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
4025
- return line => {
4026
- const lineMatch = line.match(FULL_MATCH);
4027
- if (lineMatch) {
4028
- let object;
4029
- let method;
4030
- let functionName;
4031
- let typeName;
4032
- let methodName;
4033
- if (lineMatch[1]) {
4034
- functionName = lineMatch[1];
4035
- let methodStart = functionName.lastIndexOf('.');
4036
- if (functionName[methodStart - 1] === '.') {
4037
- methodStart--;
4038
- }
4039
- if (methodStart > 0) {
4040
- object = functionName.slice(0, methodStart);
4041
- method = functionName.slice(methodStart + 1);
4042
- const objectEnd = object.indexOf('.Module');
4043
- if (objectEnd > 0) {
4044
- functionName = functionName.slice(objectEnd + 1);
4045
- object = object.slice(0, objectEnd);
4046
- }
4047
- }
4048
- typeName = undefined;
4049
- }
4050
- if (method) {
4051
- typeName = object;
4052
- methodName = method;
4053
- }
4054
- if (method === '<anonymous>') {
4055
- methodName = undefined;
4056
- functionName = undefined;
4057
- }
4058
- if (functionName === undefined) {
4059
- methodName = methodName || UNKNOWN_FUNCTION;
4060
- functionName = typeName ? `${typeName}.${methodName}` : methodName;
4061
- }
4062
- let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];
4063
- const isNative = lineMatch[5] === 'native';
4064
- // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`
4065
- if (filename?.match(/\/[A-Z]:/)) {
4066
- filename = filename.slice(1);
4067
- }
4068
- if (!filename && lineMatch[5] && !isNative) {
4069
- filename = lineMatch[5];
4070
- }
4071
- return {
4072
- filename: filename ? decodeURI(filename) : undefined,
4073
- module: getModule ? getModule(filename) : undefined,
4074
- function: functionName,
4075
- lineno: _parseIntOrUndefined(lineMatch[3]),
4076
- colno: _parseIntOrUndefined(lineMatch[4]),
4077
- in_app: filenameIsInApp(filename || '', isNative),
4078
- platform: 'node:javascript'
4079
- };
4080
- }
4081
- if (line.match(FILENAME_MATCH)) {
4082
- return {
4083
- filename: line,
4084
- platform: 'node:javascript'
4085
- };
4086
- }
4087
- return undefined;
4088
- };
4089
- }
4090
- /**
4091
- * Does this filename look like it's part of the app code?
4092
- */
4093
- function filenameIsInApp(filename, isNative = false) {
4094
- const isInternal = isNative || filename &&
4095
- // It's not internal if it's an absolute linux path
4096
- !filename.startsWith('/') &&
4097
- // It's not internal if it's an absolute windows path
4098
- !filename.match(/^[A-Z]:/) &&
4099
- // It's not internal if the path is starting with a dot
4100
- !filename.startsWith('.') &&
4101
- // 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
4102
- !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//); // Schema from: https://stackoverflow.com/a/3641782
4103
- // in_app is all that's not an internal Node function or a module within node_modules
4104
- // note that isNative appears to return true even for node core libraries
4105
- // see https://github.com/getsentry/raven-node/issues/176
4106
- return !isInternal && filename !== undefined && !filename.includes('node_modules/');
4107
- }
4108
- function _parseIntOrUndefined(input) {
4109
- return parseInt(input || '', 10) || undefined;
4110
- }
4111
- function nodeStackLineParser(getModule) {
4112
- return [90, node(getModule)];
4113
- }
4114
- function createStackParser(getModule) {
4115
- const parsers = [nodeStackLineParser(getModule)];
4116
- const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);
4117
- return (stack, skipFirstLines = 0) => {
4118
- const frames = [];
4119
- const lines = stack.split('\n');
4120
- for (let i = skipFirstLines; i < lines.length; i++) {
4121
- const line = lines[i];
4122
- // Ignore lines over 1kb as they are unlikely to be stack frames.
4123
- if (line.length > 1024) {
4124
- continue;
4125
- }
4126
- // https://github.com/getsentry/sentry-javascript/issues/5459
4127
- // Remove webpack (error: *) wrappers
4128
- const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;
4129
- // https://github.com/getsentry/sentry-javascript/issues/7813
4130
- // Skip Error: lines
4131
- if (cleanedLine.match(/\S*Error: /)) {
4132
- continue;
4133
- }
4134
- for (const parser of sortedParsers) {
4135
- const frame = parser(cleanedLine);
4136
- if (frame) {
4137
- frames.push(frame);
4138
- break;
4139
- }
4140
- }
4141
- if (frames.length >= STACKTRACE_FRAME_LIMIT) {
4142
- break;
4143
- }
4144
- }
4145
- return reverseAndStripFrames(frames);
4146
- };
4147
- }
4148
- function reverseAndStripFrames(stack) {
4149
- if (!stack.length) {
4150
- return [];
4151
- }
4152
- const localStack = Array.from(stack);
4153
- localStack.reverse();
4154
- return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({
4155
- ...frame,
4156
- filename: frame.filename || getLastStackFrame(localStack).filename,
4157
- function: frame.function || UNKNOWN_FUNCTION
4158
- }));
4159
- }
4160
- function getLastStackFrame(arr) {
4161
- return arr[arr.length - 1] || {};
4162
- }
4163
-
4164
- ErrorTracking.stackParser = createStackParser(createGetModuleFromFilename());
4165
- ErrorTracking.frameModifiers = [addSourceContext];
4166
- class PostHog extends PostHogBackendClient {
4167
- getLibraryId() {
4168
- return 'posthog-node';
4169
- }
4170
- }
4171
-
4172
10
  declare class LangChainCallbackHandler extends BaseCallbackHandler {
4173
11
  name: string;
4174
12
  private client;