@bulletproof-sh/ctrl-daemon 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +4255 -2
  2. package/package.json +4 -1
package/dist/index.js CHANGED
@@ -1,7 +1,4237 @@
1
1
  // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+
2
13
  // src/index.ts
3
14
  import * as path3 from "path";
4
15
 
16
+ // src/analytics.ts
17
+ import os from "os";
18
+
19
+ // node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
20
+ import { dirname, posix, sep } from "path";
21
+ function createModulerModifier() {
22
+ const getModuleFromFileName = createGetModuleFromFilename();
23
+ return async (frames) => {
24
+ for (const frame of frames)
25
+ frame.module = getModuleFromFileName(frame.filename);
26
+ return frames;
27
+ };
28
+ }
29
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
30
+ const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
31
+ return (filename) => {
32
+ if (!filename)
33
+ return;
34
+ const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
35
+ let { dir, base: file, ext } = posix.parse(normalizedFilename);
36
+ if (ext === ".js" || ext === ".mjs" || ext === ".cjs")
37
+ file = file.slice(0, -1 * ext.length);
38
+ const decodedFile = decodeURIComponent(file);
39
+ if (!dir)
40
+ dir = ".";
41
+ const n = dir.lastIndexOf("/node_modules");
42
+ if (n > -1)
43
+ return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`;
44
+ if (dir.startsWith(normalizedBase)) {
45
+ const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
46
+ return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
47
+ }
48
+ return decodedFile;
49
+ };
50
+ }
51
+ function normalizeWindowsPath(path) {
52
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
53
+ }
54
+
55
+ // node_modules/@posthog/core/dist/featureFlagUtils.mjs
56
+ var normalizeFlagsResponse = (flagsResponse) => {
57
+ if ("flags" in flagsResponse) {
58
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
59
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
60
+ return {
61
+ ...flagsResponse,
62
+ featureFlags,
63
+ featureFlagPayloads
64
+ };
65
+ }
66
+ {
67
+ const featureFlags = flagsResponse.featureFlags ?? {};
68
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
69
+ k,
70
+ parsePayload(v)
71
+ ]));
72
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
73
+ key,
74
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
75
+ ]));
76
+ return {
77
+ ...flagsResponse,
78
+ featureFlags,
79
+ featureFlagPayloads,
80
+ flags
81
+ };
82
+ }
83
+ };
84
+ function getFlagDetailFromFlagAndPayload(key, value, payload) {
85
+ return {
86
+ key,
87
+ enabled: typeof value == "string" ? true : value,
88
+ variant: typeof value == "string" ? value : undefined,
89
+ reason: undefined,
90
+ metadata: {
91
+ id: undefined,
92
+ version: undefined,
93
+ payload: payload ? JSON.stringify(payload) : undefined,
94
+ description: undefined
95
+ }
96
+ };
97
+ }
98
+ var getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
99
+ key,
100
+ getFeatureFlagValue(detail)
101
+ ]).filter(([, value]) => value !== undefined));
102
+ var getPayloadsFromFlags = (flags) => {
103
+ const safeFlags = flags ?? {};
104
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
105
+ const details = safeFlags[flag];
106
+ return details.enabled && details.metadata && details.metadata.payload !== undefined;
107
+ }).map((flag) => {
108
+ const payload = safeFlags[flag].metadata?.payload;
109
+ return [
110
+ flag,
111
+ payload ? parsePayload(payload) : undefined
112
+ ];
113
+ }));
114
+ };
115
+ var getFeatureFlagValue = (detail) => detail === undefined ? undefined : detail.variant ?? detail.enabled;
116
+ var parsePayload = (response) => {
117
+ if (typeof response != "string")
118
+ return response;
119
+ try {
120
+ return JSON.parse(response);
121
+ } catch {
122
+ return response;
123
+ }
124
+ };
125
+
126
+ // node_modules/@posthog/core/dist/vendor/uuidv7.mjs
127
+ /*! For license information please see uuidv7.mjs.LICENSE.txt */
128
+ var DIGITS = "0123456789abcdef";
129
+
130
+ class UUID {
131
+ constructor(bytes) {
132
+ this.bytes = bytes;
133
+ }
134
+ static ofInner(bytes) {
135
+ if (bytes.length === 16)
136
+ return new UUID(bytes);
137
+ throw new TypeError("not 128-bit length");
138
+ }
139
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
140
+ if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 281474976710655 || randA > 4095 || randBHi > 1073741823 || randBLo > 4294967295)
141
+ throw new RangeError("invalid field value");
142
+ const bytes = new Uint8Array(16);
143
+ bytes[0] = unixTsMs / 2 ** 40;
144
+ bytes[1] = unixTsMs / 2 ** 32;
145
+ bytes[2] = unixTsMs / 2 ** 24;
146
+ bytes[3] = unixTsMs / 2 ** 16;
147
+ bytes[4] = unixTsMs / 256;
148
+ bytes[5] = unixTsMs;
149
+ bytes[6] = 112 | randA >>> 8;
150
+ bytes[7] = randA;
151
+ bytes[8] = 128 | randBHi >>> 24;
152
+ bytes[9] = randBHi >>> 16;
153
+ bytes[10] = randBHi >>> 8;
154
+ bytes[11] = randBHi;
155
+ bytes[12] = randBLo >>> 24;
156
+ bytes[13] = randBLo >>> 16;
157
+ bytes[14] = randBLo >>> 8;
158
+ bytes[15] = randBLo;
159
+ return new UUID(bytes);
160
+ }
161
+ static parse(uuid) {
162
+ let hex;
163
+ switch (uuid.length) {
164
+ case 32:
165
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
166
+ break;
167
+ case 36:
168
+ hex = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join("");
169
+ break;
170
+ case 38:
171
+ hex = /^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(uuid)?.slice(1, 6).join("");
172
+ break;
173
+ case 45:
174
+ hex = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join("");
175
+ break;
176
+ default:
177
+ break;
178
+ }
179
+ if (hex) {
180
+ const inner = new Uint8Array(16);
181
+ for (let i = 0;i < 16; i += 4) {
182
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
183
+ inner[i + 0] = n >>> 24;
184
+ inner[i + 1] = n >>> 16;
185
+ inner[i + 2] = n >>> 8;
186
+ inner[i + 3] = n;
187
+ }
188
+ return new UUID(inner);
189
+ }
190
+ throw new SyntaxError("could not parse UUID string");
191
+ }
192
+ toString() {
193
+ let text = "";
194
+ for (let i = 0;i < this.bytes.length; i++) {
195
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
196
+ text += DIGITS.charAt(15 & this.bytes[i]);
197
+ if (i === 3 || i === 5 || i === 7 || i === 9)
198
+ text += "-";
199
+ }
200
+ return text;
201
+ }
202
+ toHex() {
203
+ let text = "";
204
+ for (let i = 0;i < this.bytes.length; i++) {
205
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
206
+ text += DIGITS.charAt(15 & this.bytes[i]);
207
+ }
208
+ return text;
209
+ }
210
+ toJSON() {
211
+ return this.toString();
212
+ }
213
+ getVariant() {
214
+ const n = this.bytes[8] >>> 4;
215
+ if (n < 0)
216
+ throw new Error("unreachable");
217
+ if (n <= 7)
218
+ return this.bytes.every((e) => e === 0) ? "NIL" : "VAR_0";
219
+ if (n <= 11)
220
+ return "VAR_10";
221
+ if (n <= 13)
222
+ return "VAR_110";
223
+ if (n <= 15)
224
+ return this.bytes.every((e) => e === 255) ? "MAX" : "VAR_RESERVED";
225
+ else
226
+ throw new Error("unreachable");
227
+ }
228
+ getVersion() {
229
+ return this.getVariant() === "VAR_10" ? this.bytes[6] >>> 4 : undefined;
230
+ }
231
+ clone() {
232
+ return new UUID(this.bytes.slice(0));
233
+ }
234
+ equals(other) {
235
+ return this.compareTo(other) === 0;
236
+ }
237
+ compareTo(other) {
238
+ for (let i = 0;i < 16; i++) {
239
+ const diff = this.bytes[i] - other.bytes[i];
240
+ if (diff !== 0)
241
+ return Math.sign(diff);
242
+ }
243
+ return 0;
244
+ }
245
+ }
246
+
247
+ class V7Generator {
248
+ constructor(randomNumberGenerator) {
249
+ this.timestamp = 0;
250
+ this.counter = 0;
251
+ this.random = randomNumberGenerator ?? getDefaultRandom();
252
+ }
253
+ generate() {
254
+ return this.generateOrResetCore(Date.now(), 1e4);
255
+ }
256
+ generateOrAbort() {
257
+ return this.generateOrAbortCore(Date.now(), 1e4);
258
+ }
259
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
260
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
261
+ if (value === undefined) {
262
+ this.timestamp = 0;
263
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
264
+ }
265
+ return value;
266
+ }
267
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
268
+ const MAX_COUNTER = 4398046511103;
269
+ if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 281474976710655)
270
+ throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
271
+ if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655)
272
+ throw new RangeError("`rollbackAllowance` out of reasonable range");
273
+ if (unixTsMs > this.timestamp) {
274
+ this.timestamp = unixTsMs;
275
+ this.resetCounter();
276
+ } else {
277
+ if (!(unixTsMs + rollbackAllowance >= this.timestamp))
278
+ return;
279
+ this.counter++;
280
+ if (this.counter > MAX_COUNTER) {
281
+ this.timestamp++;
282
+ this.resetCounter();
283
+ }
284
+ }
285
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
286
+ }
287
+ resetCounter() {
288
+ this.counter = 1024 * this.random.nextUint32() + (1023 & this.random.nextUint32());
289
+ }
290
+ generateV4() {
291
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
292
+ bytes[6] = 64 | bytes[6] >>> 4;
293
+ bytes[8] = 128 | bytes[8] >>> 2;
294
+ return UUID.ofInner(bytes);
295
+ }
296
+ }
297
+ var getDefaultRandom = () => ({
298
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
299
+ });
300
+ var defaultGenerator;
301
+ var uuidv7 = () => uuidv7obj().toString();
302
+ var uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
303
+
304
+ // node_modules/@posthog/core/dist/types.mjs
305
+ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
306
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
307
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
308
+ PostHogPersistedProperty["Props"] = "props";
309
+ PostHogPersistedProperty["EnablePersonProcessing"] = "enable_person_processing";
310
+ PostHogPersistedProperty["PersonMode"] = "person_mode";
311
+ PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
312
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
313
+ PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
314
+ PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
315
+ PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
316
+ PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
317
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
318
+ PostHogPersistedProperty["Queue"] = "queue";
319
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
320
+ PostHogPersistedProperty["SessionId"] = "session_id";
321
+ PostHogPersistedProperty["SessionStartTimestamp"] = "session_start_timestamp";
322
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
323
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
324
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
325
+ PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
326
+ PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
327
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
328
+ PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
329
+ PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
330
+ PostHogPersistedProperty["Surveys"] = "surveys";
331
+ PostHogPersistedProperty["RemoteConfig"] = "remote_config";
332
+ PostHogPersistedProperty["FlagsEndpointWasHit"] = "flags_endpoint_was_hit";
333
+ return PostHogPersistedProperty;
334
+ }({});
335
+
336
+ // node_modules/@posthog/core/dist/utils/bot-detection.mjs
337
+ var DEFAULT_BLOCKED_UA_STRS = [
338
+ "amazonbot",
339
+ "amazonproductbot",
340
+ "app.hypefactors.com",
341
+ "applebot",
342
+ "archive.org_bot",
343
+ "awariobot",
344
+ "backlinksextendedbot",
345
+ "baiduspider",
346
+ "bingbot",
347
+ "bingpreview",
348
+ "chrome-lighthouse",
349
+ "dataforseobot",
350
+ "deepscan",
351
+ "duckduckbot",
352
+ "facebookexternal",
353
+ "facebookcatalog",
354
+ "http://yandex.com/bots",
355
+ "hubspot",
356
+ "ia_archiver",
357
+ "leikibot",
358
+ "linkedinbot",
359
+ "meta-externalagent",
360
+ "mj12bot",
361
+ "msnbot",
362
+ "nessus",
363
+ "petalbot",
364
+ "pinterest",
365
+ "prerender",
366
+ "rogerbot",
367
+ "screaming frog",
368
+ "sebot-wa",
369
+ "sitebulb",
370
+ "slackbot",
371
+ "slurp",
372
+ "trendictionbot",
373
+ "turnitin",
374
+ "twitterbot",
375
+ "vercel-screenshot",
376
+ "vercelbot",
377
+ "yahoo! slurp",
378
+ "yandexbot",
379
+ "zoombot",
380
+ "bot.htm",
381
+ "bot.php",
382
+ "(bot;",
383
+ "bot/",
384
+ "crawler",
385
+ "ahrefsbot",
386
+ "ahrefssiteaudit",
387
+ "semrushbot",
388
+ "siteauditbot",
389
+ "splitsignalbot",
390
+ "gptbot",
391
+ "oai-searchbot",
392
+ "chatgpt-user",
393
+ "perplexitybot",
394
+ "better uptime bot",
395
+ "sentryuptimebot",
396
+ "uptimerobot",
397
+ "headlesschrome",
398
+ "cypress",
399
+ "google-hoteladsverifier",
400
+ "adsbot-google",
401
+ "apis-google",
402
+ "duplexweb-google",
403
+ "feedfetcher-google",
404
+ "google favicon",
405
+ "google web preview",
406
+ "google-read-aloud",
407
+ "googlebot",
408
+ "googleother",
409
+ "google-cloudvertexbot",
410
+ "googleweblight",
411
+ "mediapartners-google",
412
+ "storebot-google",
413
+ "google-inspectiontool",
414
+ "bytespider"
415
+ ];
416
+ var isBlockedUA = function(ua, customBlockedUserAgents = []) {
417
+ if (!ua)
418
+ return false;
419
+ const uaLower = ua.toLowerCase();
420
+ return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA) => {
421
+ const blockedUaLower = blockedUA.toLowerCase();
422
+ return uaLower.indexOf(blockedUaLower) !== -1;
423
+ });
424
+ };
425
+ // node_modules/@posthog/core/dist/utils/type-utils.mjs
426
+ var nativeIsArray = Array.isArray;
427
+ var ObjProto = Object.prototype;
428
+ var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
429
+ var type_utils_toString = ObjProto.toString;
430
+ var isArray = nativeIsArray || function(obj) {
431
+ return type_utils_toString.call(obj) === "[object Array]";
432
+ };
433
+ var isObject = (x) => x === Object(x) && !isArray(x);
434
+ var isUndefined = (x) => x === undefined;
435
+ var isString = (x) => type_utils_toString.call(x) == "[object String]";
436
+ var isEmptyString = (x) => isString(x) && x.trim().length === 0;
437
+ var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
438
+ var isPlainError = (x) => x instanceof Error;
439
+ function isPrimitive(value) {
440
+ return value === null || typeof value != "object";
441
+ }
442
+ function isBuiltin(candidate, className) {
443
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
444
+ }
445
+ function isErrorEvent(event) {
446
+ return isBuiltin(event, "ErrorEvent");
447
+ }
448
+ function isEvent(candidate) {
449
+ return !isUndefined(Event) && isInstanceOf(candidate, Event);
450
+ }
451
+ function isPlainObject(candidate) {
452
+ return isBuiltin(candidate, "Object");
453
+ }
454
+ function isInstanceOf(candidate, base) {
455
+ try {
456
+ return candidate instanceof base;
457
+ } catch {
458
+ return false;
459
+ }
460
+ }
461
+
462
+ // node_modules/@posthog/core/dist/utils/number-utils.mjs
463
+ function clampToRange(value, min, max, logger, fallbackValue) {
464
+ if (min > max) {
465
+ logger.warn("min cannot be greater than max.");
466
+ min = max;
467
+ }
468
+ if (isNumber(value))
469
+ if (value > max) {
470
+ logger.warn(" cannot be greater than max: " + max + ". Using max value instead.");
471
+ return max;
472
+ } else {
473
+ if (!(value < min))
474
+ return value;
475
+ logger.warn(" cannot be less than min: " + min + ". Using min value instead.");
476
+ return min;
477
+ }
478
+ logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
479
+ return clampToRange(fallbackValue || max, min, max, logger);
480
+ }
481
+
482
+ // node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
483
+ var ONE_DAY_IN_MS = 86400000;
484
+
485
+ class BucketedRateLimiter {
486
+ constructor(options) {
487
+ this._buckets = {};
488
+ this._onBucketRateLimited = options._onBucketRateLimited;
489
+ this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);
490
+ this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);
491
+ this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);
492
+ }
493
+ _applyRefill(bucket, now) {
494
+ const elapsedMs = now - bucket.lastAccess;
495
+ const refillIntervals = Math.floor(elapsedMs / this._refillInterval);
496
+ if (refillIntervals > 0) {
497
+ const tokensToAdd = refillIntervals * this._refillRate;
498
+ bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);
499
+ bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;
500
+ }
501
+ }
502
+ consumeRateLimit(key) {
503
+ const now = Date.now();
504
+ const keyStr = String(key);
505
+ let bucket = this._buckets[keyStr];
506
+ if (bucket)
507
+ this._applyRefill(bucket, now);
508
+ else {
509
+ bucket = {
510
+ tokens: this._bucketSize,
511
+ lastAccess: now
512
+ };
513
+ this._buckets[keyStr] = bucket;
514
+ }
515
+ if (bucket.tokens === 0)
516
+ return true;
517
+ bucket.tokens--;
518
+ if (bucket.tokens === 0)
519
+ this._onBucketRateLimited?.(key);
520
+ return bucket.tokens === 0;
521
+ }
522
+ stop() {
523
+ this._buckets = {};
524
+ }
525
+ }
526
+ // node_modules/@posthog/core/dist/utils/promise-queue.mjs
527
+ class PromiseQueue {
528
+ add(promise) {
529
+ const promiseUUID = uuidv7();
530
+ this.promiseByIds[promiseUUID] = promise;
531
+ promise.catch(() => {}).finally(() => {
532
+ delete this.promiseByIds[promiseUUID];
533
+ });
534
+ return promise;
535
+ }
536
+ async join() {
537
+ let promises = Object.values(this.promiseByIds);
538
+ let length = promises.length;
539
+ while (length > 0) {
540
+ await Promise.all(promises);
541
+ promises = Object.values(this.promiseByIds);
542
+ length = promises.length;
543
+ }
544
+ }
545
+ get length() {
546
+ return Object.keys(this.promiseByIds).length;
547
+ }
548
+ constructor() {
549
+ this.promiseByIds = {};
550
+ }
551
+ }
552
+ // node_modules/@posthog/core/dist/utils/logger.mjs
553
+ function createConsole(consoleLike = console) {
554
+ const lockedMethods = {
555
+ log: consoleLike.log.bind(consoleLike),
556
+ warn: consoleLike.warn.bind(consoleLike),
557
+ error: consoleLike.error.bind(consoleLike),
558
+ debug: consoleLike.debug.bind(consoleLike)
559
+ };
560
+ return lockedMethods;
561
+ }
562
+ var _createLogger = (prefix, maybeCall, consoleLike) => {
563
+ function _log(level, ...args) {
564
+ maybeCall(() => {
565
+ const consoleMethod = consoleLike[level];
566
+ consoleMethod(prefix, ...args);
567
+ });
568
+ }
569
+ const logger = {
570
+ info: (...args) => {
571
+ _log("log", ...args);
572
+ },
573
+ warn: (...args) => {
574
+ _log("warn", ...args);
575
+ },
576
+ error: (...args) => {
577
+ _log("error", ...args);
578
+ },
579
+ critical: (...args) => {
580
+ consoleLike["error"](prefix, ...args);
581
+ },
582
+ createLogger: (additionalPrefix) => _createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)
583
+ };
584
+ return logger;
585
+ };
586
+ var passThrough = (fn) => fn();
587
+ function createLogger(prefix, maybeCall = passThrough) {
588
+ return _createLogger(prefix, maybeCall, createConsole());
589
+ }
590
+ // node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
591
+ var MOBILE = "Mobile";
592
+ var IOS = "iOS";
593
+ var ANDROID = "Android";
594
+ var TABLET = "Tablet";
595
+ var ANDROID_TABLET = ANDROID + " " + TABLET;
596
+ var APPLE = "Apple";
597
+ var APPLE_WATCH = APPLE + " Watch";
598
+ var SAFARI = "Safari";
599
+ var BLACKBERRY = "BlackBerry";
600
+ var SAMSUNG = "Samsung";
601
+ var SAMSUNG_BROWSER = SAMSUNG + "Browser";
602
+ var SAMSUNG_INTERNET = SAMSUNG + " Internet";
603
+ var CHROME = "Chrome";
604
+ var CHROME_OS = CHROME + " OS";
605
+ var CHROME_IOS = CHROME + " " + IOS;
606
+ var INTERNET_EXPLORER = "Internet Explorer";
607
+ var INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + " " + MOBILE;
608
+ var OPERA = "Opera";
609
+ var OPERA_MINI = OPERA + " Mini";
610
+ var EDGE = "Edge";
611
+ var MICROSOFT_EDGE = "Microsoft " + EDGE;
612
+ var FIREFOX = "Firefox";
613
+ var FIREFOX_IOS = FIREFOX + " " + IOS;
614
+ var NINTENDO = "Nintendo";
615
+ var PLAYSTATION = "PlayStation";
616
+ var XBOX = "Xbox";
617
+ var ANDROID_MOBILE = ANDROID + " " + MOBILE;
618
+ var MOBILE_SAFARI = MOBILE + " " + SAFARI;
619
+ var WINDOWS = "Windows";
620
+ var WINDOWS_PHONE = WINDOWS + " Phone";
621
+ var GENERIC = "Generic";
622
+ var GENERIC_MOBILE = GENERIC + " " + MOBILE.toLowerCase();
623
+ var GENERIC_TABLET = GENERIC + " " + TABLET.toLowerCase();
624
+ var KONQUEROR = "Konqueror";
625
+ var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
626
+ var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
627
+ var XBOX_REGEX = new RegExp(XBOX, "i");
628
+ var PLAYSTATION_REGEX = new RegExp(PLAYSTATION + " \\w+", "i");
629
+ var NINTENDO_REGEX = new RegExp(NINTENDO + " \\w+", "i");
630
+ var BLACKBERRY_REGEX = new RegExp(BLACKBERRY + "|PlayBook|BB10", "i");
631
+ var windowsVersionMap = {
632
+ "NT3.51": "NT 3.11",
633
+ "NT4.0": "NT 4.0",
634
+ "5.0": "2000",
635
+ "5.1": "XP",
636
+ "5.2": "XP",
637
+ "6.0": "Vista",
638
+ "6.1": "7",
639
+ "6.2": "8",
640
+ "6.3": "8.1",
641
+ "6.4": "10",
642
+ "10.0": "10"
643
+ };
644
+ var versionRegexes = {
645
+ [INTERNET_EXPLORER_MOBILE]: [
646
+ new RegExp("rv:" + BROWSER_VERSION_REGEX_SUFFIX)
647
+ ],
648
+ [MICROSOFT_EDGE]: [
649
+ new RegExp(EDGE + "?\\/" + BROWSER_VERSION_REGEX_SUFFIX)
650
+ ],
651
+ [CHROME]: [
652
+ new RegExp("(" + CHROME + "|CrMo)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
653
+ ],
654
+ [CHROME_IOS]: [
655
+ new RegExp("CriOS\\/" + BROWSER_VERSION_REGEX_SUFFIX)
656
+ ],
657
+ "UC Browser": [
658
+ new RegExp("(UCBrowser|UCWEB)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
659
+ ],
660
+ [SAFARI]: [
661
+ DEFAULT_BROWSER_VERSION_REGEX
662
+ ],
663
+ [MOBILE_SAFARI]: [
664
+ DEFAULT_BROWSER_VERSION_REGEX
665
+ ],
666
+ [OPERA]: [
667
+ new RegExp("(" + OPERA + "|OPR)\\/" + BROWSER_VERSION_REGEX_SUFFIX)
668
+ ],
669
+ [FIREFOX]: [
670
+ new RegExp(FIREFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
671
+ ],
672
+ [FIREFOX_IOS]: [
673
+ new RegExp("FxiOS\\/" + BROWSER_VERSION_REGEX_SUFFIX)
674
+ ],
675
+ [KONQUEROR]: [
676
+ new RegExp("Konqueror[:/]?" + BROWSER_VERSION_REGEX_SUFFIX, "i")
677
+ ],
678
+ [BLACKBERRY]: [
679
+ new RegExp(BLACKBERRY + " " + BROWSER_VERSION_REGEX_SUFFIX),
680
+ DEFAULT_BROWSER_VERSION_REGEX
681
+ ],
682
+ [ANDROID_MOBILE]: [
683
+ new RegExp("android\\s" + BROWSER_VERSION_REGEX_SUFFIX, "i")
684
+ ],
685
+ [SAMSUNG_INTERNET]: [
686
+ new RegExp(SAMSUNG_BROWSER + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
687
+ ],
688
+ [INTERNET_EXPLORER]: [
689
+ new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
690
+ ],
691
+ Mozilla: [
692
+ new RegExp("rv:" + BROWSER_VERSION_REGEX_SUFFIX)
693
+ ]
694
+ };
695
+ var osMatchers = [
696
+ [
697
+ new RegExp(XBOX + "; " + XBOX + " (.*?)[);]", "i"),
698
+ (match) => [
699
+ XBOX,
700
+ match && match[1] || ""
701
+ ]
702
+ ],
703
+ [
704
+ new RegExp(NINTENDO, "i"),
705
+ [
706
+ NINTENDO,
707
+ ""
708
+ ]
709
+ ],
710
+ [
711
+ new RegExp(PLAYSTATION, "i"),
712
+ [
713
+ PLAYSTATION,
714
+ ""
715
+ ]
716
+ ],
717
+ [
718
+ BLACKBERRY_REGEX,
719
+ [
720
+ BLACKBERRY,
721
+ ""
722
+ ]
723
+ ],
724
+ [
725
+ new RegExp(WINDOWS, "i"),
726
+ (_, user_agent) => {
727
+ if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent))
728
+ return [
729
+ WINDOWS_PHONE,
730
+ ""
731
+ ];
732
+ if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\b/.test(user_agent))
733
+ return [
734
+ WINDOWS + " " + MOBILE,
735
+ ""
736
+ ];
737
+ const match = /Windows NT ([0-9.]+)/i.exec(user_agent);
738
+ if (match && match[1]) {
739
+ const version = match[1];
740
+ let osVersion = windowsVersionMap[version] || "";
741
+ if (/arm/i.test(user_agent))
742
+ osVersion = "RT";
743
+ return [
744
+ WINDOWS,
745
+ osVersion
746
+ ];
747
+ }
748
+ return [
749
+ WINDOWS,
750
+ ""
751
+ ];
752
+ }
753
+ ],
754
+ [
755
+ /((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,
756
+ (match) => {
757
+ if (match && match[3]) {
758
+ const versionParts = [
759
+ match[3],
760
+ match[4],
761
+ match[5] || "0"
762
+ ];
763
+ return [
764
+ IOS,
765
+ versionParts.join(".")
766
+ ];
767
+ }
768
+ return [
769
+ IOS,
770
+ ""
771
+ ];
772
+ }
773
+ ],
774
+ [
775
+ /(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,
776
+ (match) => {
777
+ let version = "";
778
+ if (match && match.length >= 3)
779
+ version = isUndefined(match[2]) ? match[3] : match[2];
780
+ return [
781
+ "watchOS",
782
+ version
783
+ ];
784
+ }
785
+ ],
786
+ [
787
+ new RegExp("(" + ANDROID + " (\\d+)\\.(\\d+)\\.?(\\d+)?|" + ANDROID + ")", "i"),
788
+ (match) => {
789
+ if (match && match[2]) {
790
+ const versionParts = [
791
+ match[2],
792
+ match[3],
793
+ match[4] || "0"
794
+ ];
795
+ return [
796
+ ANDROID,
797
+ versionParts.join(".")
798
+ ];
799
+ }
800
+ return [
801
+ ANDROID,
802
+ ""
803
+ ];
804
+ }
805
+ ],
806
+ [
807
+ /Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,
808
+ (match) => {
809
+ const result = [
810
+ "Mac OS X",
811
+ ""
812
+ ];
813
+ if (match && match[1]) {
814
+ const versionParts = [
815
+ match[1],
816
+ match[2],
817
+ match[3] || "0"
818
+ ];
819
+ result[1] = versionParts.join(".");
820
+ }
821
+ return result;
822
+ }
823
+ ],
824
+ [
825
+ /Mac/i,
826
+ [
827
+ "Mac OS X",
828
+ ""
829
+ ]
830
+ ],
831
+ [
832
+ /CrOS/,
833
+ [
834
+ CHROME_OS,
835
+ ""
836
+ ]
837
+ ],
838
+ [
839
+ /Linux|debian/i,
840
+ [
841
+ "Linux",
842
+ ""
843
+ ]
844
+ ]
845
+ ];
846
+
847
+ // node_modules/@posthog/core/dist/utils/index.mjs
848
+ var STRING_FORMAT = "utf8";
849
+ function assert(truthyValue, message) {
850
+ if (!truthyValue || typeof truthyValue != "string" || isEmpty(truthyValue))
851
+ throw new Error(message);
852
+ }
853
+ function isEmpty(truthyValue) {
854
+ if (truthyValue.trim().length === 0)
855
+ return true;
856
+ return false;
857
+ }
858
+ function removeTrailingSlash(url) {
859
+ return url?.replace(/\/+$/, "");
860
+ }
861
+ async function retriable(fn, props) {
862
+ let lastError = null;
863
+ for (let i = 0;i < props.retryCount + 1; i++) {
864
+ if (i > 0)
865
+ await new Promise((r) => setTimeout(r, props.retryDelay));
866
+ try {
867
+ const res = await fn();
868
+ return res;
869
+ } catch (e) {
870
+ lastError = e;
871
+ if (!props.retryCheck(e))
872
+ throw e;
873
+ }
874
+ }
875
+ throw lastError;
876
+ }
877
+ function currentISOTime() {
878
+ return new Date().toISOString();
879
+ }
880
+ function safeSetTimeout(fn, timeout) {
881
+ const t = setTimeout(fn, timeout);
882
+ t?.unref && t?.unref();
883
+ return t;
884
+ }
885
+ var isError = (x) => x instanceof Error;
886
+ function allSettled(promises) {
887
+ return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
888
+ status: "fulfilled",
889
+ value
890
+ }), (reason) => ({
891
+ status: "rejected",
892
+ reason
893
+ }))));
894
+ }
895
+ // node_modules/@posthog/core/dist/eventemitter.mjs
896
+ class SimpleEventEmitter {
897
+ constructor() {
898
+ this.events = {};
899
+ this.events = {};
900
+ }
901
+ on(event, listener) {
902
+ if (!this.events[event])
903
+ this.events[event] = [];
904
+ this.events[event].push(listener);
905
+ return () => {
906
+ this.events[event] = this.events[event].filter((x) => x !== listener);
907
+ };
908
+ }
909
+ emit(event, payload) {
910
+ for (const listener of this.events[event] || [])
911
+ listener(payload);
912
+ for (const listener of this.events["*"] || [])
913
+ listener(event, payload);
914
+ }
915
+ }
916
+
917
+ // node_modules/@posthog/core/dist/gzip.mjs
918
+ function isGzipSupported() {
919
+ return "CompressionStream" in globalThis;
920
+ }
921
+ async function gzipCompress(input, isDebug = true) {
922
+ try {
923
+ const dataStream = new Blob([
924
+ input
925
+ ], {
926
+ type: "text/plain"
927
+ }).stream();
928
+ const compressedStream = dataStream.pipeThrough(new CompressionStream("gzip"));
929
+ return await new Response(compressedStream).blob();
930
+ } catch (error) {
931
+ if (isDebug)
932
+ console.error("Failed to gzip compress data", error);
933
+ return null;
934
+ }
935
+ }
936
+
937
+ // node_modules/@posthog/core/dist/posthog-core-stateless.mjs
938
+ class PostHogFetchHttpError extends Error {
939
+ constructor(response, reqByteLength) {
940
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
941
+ }
942
+ get status() {
943
+ return this.response.status;
944
+ }
945
+ get text() {
946
+ return this.response.text();
947
+ }
948
+ get json() {
949
+ return this.response.json();
950
+ }
951
+ }
952
+
953
+ class PostHogFetchNetworkError extends Error {
954
+ constructor(error) {
955
+ super("Network error while fetching PostHog", error instanceof Error ? {
956
+ cause: error
957
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
958
+ }
959
+ }
960
+ async function logFlushError(err) {
961
+ if (err instanceof PostHogFetchHttpError) {
962
+ let text = "";
963
+ try {
964
+ text = await err.text;
965
+ } catch {}
966
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
967
+ } else
968
+ console.error("Error while flushing PostHog", err);
969
+ return Promise.resolve();
970
+ }
971
+ function isPostHogFetchError(err) {
972
+ return typeof err == "object" && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
973
+ }
974
+ function isPostHogFetchContentTooLargeError(err) {
975
+ return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
976
+ }
977
+ class PostHogCoreStateless {
978
+ constructor(apiKey, options = {}) {
979
+ this.flushPromise = null;
980
+ this.shutdownPromise = null;
981
+ this.promiseQueue = new PromiseQueue;
982
+ this._events = new SimpleEventEmitter;
983
+ this._isInitialized = false;
984
+ assert(apiKey, "You must pass your PostHog project's api key.");
985
+ this.apiKey = apiKey;
986
+ this.host = removeTrailingSlash(options.host || "https://us.i.posthog.com");
987
+ this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
988
+ this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
989
+ this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);
990
+ this.flushInterval = options.flushInterval ?? 1e4;
991
+ this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
992
+ this.defaultOptIn = options.defaultOptIn ?? true;
993
+ this.disableSurveys = options.disableSurveys ?? false;
994
+ this._retryOptions = {
995
+ retryCount: options.fetchRetryCount ?? 3,
996
+ retryDelay: options.fetchRetryDelay ?? 3000,
997
+ retryCheck: isPostHogFetchError
998
+ };
999
+ this.requestTimeout = options.requestTimeout ?? 1e4;
1000
+ this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
1001
+ this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
1002
+ this.disableGeoip = options.disableGeoip ?? true;
1003
+ this.disabled = options.disabled ?? false;
1004
+ this.historicalMigration = options?.historicalMigration ?? false;
1005
+ this._initPromise = Promise.resolve();
1006
+ this._isInitialized = true;
1007
+ this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
1008
+ this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;
1009
+ if (options?.evaluationEnvironments && !options?.evaluationContexts)
1010
+ this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");
1011
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
1012
+ }
1013
+ logMsgIfDebug(fn) {
1014
+ if (this.isDebug)
1015
+ fn();
1016
+ }
1017
+ wrap(fn) {
1018
+ if (this.disabled)
1019
+ return void this._logger.warn("The client is disabled");
1020
+ if (this._isInitialized)
1021
+ return fn();
1022
+ this._initPromise.then(() => fn());
1023
+ }
1024
+ getCommonEventProperties() {
1025
+ return {
1026
+ $lib: this.getLibraryId(),
1027
+ $lib_version: this.getLibraryVersion()
1028
+ };
1029
+ }
1030
+ get optedOut() {
1031
+ return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
1032
+ }
1033
+ async optIn() {
1034
+ this.wrap(() => {
1035
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
1036
+ });
1037
+ }
1038
+ async optOut() {
1039
+ this.wrap(() => {
1040
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
1041
+ });
1042
+ }
1043
+ on(event, cb) {
1044
+ return this._events.on(event, cb);
1045
+ }
1046
+ debug(enabled = true) {
1047
+ this.removeDebugCallback?.();
1048
+ if (enabled) {
1049
+ const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
1050
+ this.removeDebugCallback = () => {
1051
+ removeDebugCallback();
1052
+ this.removeDebugCallback = undefined;
1053
+ };
1054
+ }
1055
+ }
1056
+ get isDebug() {
1057
+ return !!this.removeDebugCallback;
1058
+ }
1059
+ get isDisabled() {
1060
+ return this.disabled;
1061
+ }
1062
+ buildPayload(payload) {
1063
+ return {
1064
+ distinct_id: payload.distinct_id,
1065
+ event: payload.event,
1066
+ properties: {
1067
+ ...payload.properties || {},
1068
+ ...this.getCommonEventProperties()
1069
+ }
1070
+ };
1071
+ }
1072
+ addPendingPromise(promise) {
1073
+ return this.promiseQueue.add(promise);
1074
+ }
1075
+ identifyStateless(distinctId, properties, options) {
1076
+ this.wrap(() => {
1077
+ const payload = {
1078
+ ...this.buildPayload({
1079
+ distinct_id: distinctId,
1080
+ event: "$identify",
1081
+ properties
1082
+ })
1083
+ };
1084
+ this.enqueue("identify", payload, options);
1085
+ });
1086
+ }
1087
+ async identifyStatelessImmediate(distinctId, properties, options) {
1088
+ const payload = {
1089
+ ...this.buildPayload({
1090
+ distinct_id: distinctId,
1091
+ event: "$identify",
1092
+ properties
1093
+ })
1094
+ };
1095
+ await this.sendImmediate("identify", payload, options);
1096
+ }
1097
+ captureStateless(distinctId, event, properties, options) {
1098
+ this.wrap(() => {
1099
+ const payload = this.buildPayload({
1100
+ distinct_id: distinctId,
1101
+ event,
1102
+ properties
1103
+ });
1104
+ this.enqueue("capture", payload, options);
1105
+ });
1106
+ }
1107
+ async captureStatelessImmediate(distinctId, event, properties, options) {
1108
+ const payload = this.buildPayload({
1109
+ distinct_id: distinctId,
1110
+ event,
1111
+ properties
1112
+ });
1113
+ await this.sendImmediate("capture", payload, options);
1114
+ }
1115
+ aliasStateless(alias, distinctId, properties, options) {
1116
+ this.wrap(() => {
1117
+ const payload = this.buildPayload({
1118
+ event: "$create_alias",
1119
+ distinct_id: distinctId,
1120
+ properties: {
1121
+ ...properties || {},
1122
+ distinct_id: distinctId,
1123
+ alias
1124
+ }
1125
+ });
1126
+ this.enqueue("alias", payload, options);
1127
+ });
1128
+ }
1129
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
1130
+ const payload = this.buildPayload({
1131
+ event: "$create_alias",
1132
+ distinct_id: distinctId,
1133
+ properties: {
1134
+ ...properties || {},
1135
+ distinct_id: distinctId,
1136
+ alias
1137
+ }
1138
+ });
1139
+ await this.sendImmediate("alias", payload, options);
1140
+ }
1141
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
1142
+ this.wrap(() => {
1143
+ const payload = this.buildPayload({
1144
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
1145
+ event: "$groupidentify",
1146
+ properties: {
1147
+ $group_type: groupType,
1148
+ $group_key: groupKey,
1149
+ $group_set: groupProperties || {},
1150
+ ...eventProperties || {}
1151
+ }
1152
+ });
1153
+ this.enqueue("capture", payload, options);
1154
+ });
1155
+ }
1156
+ async getRemoteConfig() {
1157
+ await this._initPromise;
1158
+ let host = this.host;
1159
+ if (host === "https://us.i.posthog.com")
1160
+ host = "https://us-assets.i.posthog.com";
1161
+ else if (host === "https://eu.i.posthog.com")
1162
+ host = "https://eu-assets.i.posthog.com";
1163
+ const url = `${host}/array/${this.apiKey}/config`;
1164
+ const fetchOptions = {
1165
+ method: "GET",
1166
+ headers: {
1167
+ ...this.getCustomHeaders(),
1168
+ "Content-Type": "application/json"
1169
+ }
1170
+ };
1171
+ return this.fetchWithRetry(url, fetchOptions, {
1172
+ retryCount: 0
1173
+ }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
1174
+ this._logger.error("Remote config could not be loaded", error);
1175
+ this._events.emit("error", error);
1176
+ });
1177
+ }
1178
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = true) {
1179
+ await this._initPromise;
1180
+ const configParam = fetchConfig ? "&config=true" : "";
1181
+ const url = `${this.host}/flags/?v=2${configParam}`;
1182
+ const requestData = {
1183
+ token: this.apiKey,
1184
+ distinct_id: distinctId,
1185
+ groups,
1186
+ person_properties: personProperties,
1187
+ group_properties: groupProperties,
1188
+ ...extraPayload
1189
+ };
1190
+ if (this.evaluationContexts && this.evaluationContexts.length > 0)
1191
+ requestData.evaluation_contexts = this.evaluationContexts;
1192
+ const fetchOptions = {
1193
+ method: "POST",
1194
+ headers: {
1195
+ ...this.getCustomHeaders(),
1196
+ "Content-Type": "application/json"
1197
+ },
1198
+ body: JSON.stringify(requestData)
1199
+ };
1200
+ this._logger.info("Flags URL", url);
1201
+ return this.fetchWithRetry(url, fetchOptions, {
1202
+ retryCount: 0
1203
+ }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => ({
1204
+ success: true,
1205
+ response: normalizeFlagsResponse(response)
1206
+ })).catch((error) => {
1207
+ this._events.emit("error", error);
1208
+ return {
1209
+ success: false,
1210
+ error: this.categorizeRequestError(error)
1211
+ };
1212
+ });
1213
+ }
1214
+ categorizeRequestError(error) {
1215
+ if (error instanceof PostHogFetchHttpError)
1216
+ return {
1217
+ type: "api_error",
1218
+ statusCode: error.status
1219
+ };
1220
+ if (error instanceof PostHogFetchNetworkError) {
1221
+ const cause = error.error;
1222
+ if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError"))
1223
+ return {
1224
+ type: "timeout"
1225
+ };
1226
+ return {
1227
+ type: "connection_error"
1228
+ };
1229
+ }
1230
+ return {
1231
+ type: "unknown_error"
1232
+ };
1233
+ }
1234
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1235
+ await this._initPromise;
1236
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
1237
+ if (flagDetailResponse === undefined)
1238
+ return {
1239
+ response: undefined,
1240
+ requestId: undefined
1241
+ };
1242
+ let response = getFeatureFlagValue(flagDetailResponse.response);
1243
+ if (response === undefined)
1244
+ response = false;
1245
+ return {
1246
+ response,
1247
+ requestId: flagDetailResponse.requestId
1248
+ };
1249
+ }
1250
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1251
+ await this._initPromise;
1252
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1253
+ key
1254
+ ]);
1255
+ if (flagsResponse === undefined)
1256
+ return;
1257
+ const featureFlags = flagsResponse.flags;
1258
+ const flagDetail = featureFlags[key];
1259
+ return {
1260
+ response: flagDetail,
1261
+ requestId: flagsResponse.requestId,
1262
+ evaluatedAt: flagsResponse.evaluatedAt
1263
+ };
1264
+ }
1265
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1266
+ await this._initPromise;
1267
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1268
+ key
1269
+ ]);
1270
+ if (!payloads)
1271
+ return;
1272
+ const response = payloads[key];
1273
+ if (response === undefined)
1274
+ return null;
1275
+ return response;
1276
+ }
1277
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1278
+ await this._initPromise;
1279
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
1280
+ return payloads;
1281
+ }
1282
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1283
+ await this._initPromise;
1284
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1285
+ }
1286
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1287
+ await this._initPromise;
1288
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1289
+ if (!featureFlagDetails)
1290
+ return {
1291
+ flags: undefined,
1292
+ payloads: undefined,
1293
+ requestId: undefined
1294
+ };
1295
+ return {
1296
+ flags: featureFlagDetails.featureFlags,
1297
+ payloads: featureFlagDetails.featureFlagPayloads,
1298
+ requestId: featureFlagDetails.requestId
1299
+ };
1300
+ }
1301
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1302
+ await this._initPromise;
1303
+ const extraPayload = {};
1304
+ if (disableGeoip ?? this.disableGeoip)
1305
+ extraPayload["geoip_disable"] = true;
1306
+ if (flagKeysToEvaluate)
1307
+ extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
1308
+ const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
1309
+ if (!result.success)
1310
+ return;
1311
+ const flagsResponse = result.response;
1312
+ if (flagsResponse.errorsWhileComputingFlags)
1313
+ 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");
1314
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
1315
+ 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");
1316
+ return {
1317
+ flags: {},
1318
+ featureFlags: {},
1319
+ featureFlagPayloads: {},
1320
+ requestId: flagsResponse?.requestId,
1321
+ quotaLimited: flagsResponse.quotaLimited
1322
+ };
1323
+ }
1324
+ return flagsResponse;
1325
+ }
1326
+ async getSurveysStateless() {
1327
+ await this._initPromise;
1328
+ if (this.disableSurveys === true) {
1329
+ this._logger.info("Loading surveys is disabled.");
1330
+ return [];
1331
+ }
1332
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
1333
+ const fetchOptions = {
1334
+ method: "GET",
1335
+ headers: {
1336
+ ...this.getCustomHeaders(),
1337
+ "Content-Type": "application/json"
1338
+ }
1339
+ };
1340
+ const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
1341
+ if (response2.status !== 200 || !response2.json) {
1342
+ const msg = `Surveys API could not be loaded: ${response2.status}`;
1343
+ const error = new Error(msg);
1344
+ this._logger.error(error);
1345
+ this._events.emit("error", new Error(msg));
1346
+ return;
1347
+ }
1348
+ return response2.json();
1349
+ }).catch((error) => {
1350
+ this._logger.error("Surveys API could not be loaded", error);
1351
+ this._events.emit("error", error);
1352
+ });
1353
+ const newSurveys = response?.surveys;
1354
+ if (newSurveys)
1355
+ this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
1356
+ return newSurveys ?? [];
1357
+ }
1358
+ get props() {
1359
+ if (!this._props)
1360
+ this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
1361
+ return this._props || {};
1362
+ }
1363
+ set props(val) {
1364
+ this._props = val;
1365
+ }
1366
+ async register(properties) {
1367
+ this.wrap(() => {
1368
+ this.props = {
1369
+ ...this.props,
1370
+ ...properties
1371
+ };
1372
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1373
+ });
1374
+ }
1375
+ async unregister(property) {
1376
+ this.wrap(() => {
1377
+ delete this.props[property];
1378
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1379
+ });
1380
+ }
1381
+ processBeforeEnqueue(message) {
1382
+ return message;
1383
+ }
1384
+ async flushStorage() {}
1385
+ enqueue(type, _message, options) {
1386
+ this.wrap(() => {
1387
+ if (this.optedOut)
1388
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1389
+ let message = this.prepareMessage(type, _message, options);
1390
+ message = this.processBeforeEnqueue(message);
1391
+ if (message === null)
1392
+ return;
1393
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1394
+ if (queue.length >= this.maxQueueSize) {
1395
+ queue.shift();
1396
+ this._logger.info("Queue is full, the oldest event is dropped.");
1397
+ }
1398
+ queue.push({
1399
+ message
1400
+ });
1401
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
1402
+ this._events.emit(type, message);
1403
+ if (queue.length >= this.flushAt)
1404
+ this.flushBackground();
1405
+ if (this.flushInterval && !this._flushTimer)
1406
+ this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
1407
+ });
1408
+ }
1409
+ async sendImmediate(type, _message, options) {
1410
+ if (this.disabled)
1411
+ return void this._logger.warn("The client is disabled");
1412
+ if (!this._isInitialized)
1413
+ await this._initPromise;
1414
+ if (this.optedOut)
1415
+ return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1416
+ let message = this.prepareMessage(type, _message, options);
1417
+ message = this.processBeforeEnqueue(message);
1418
+ if (message === null)
1419
+ return;
1420
+ const data = {
1421
+ api_key: this.apiKey,
1422
+ batch: [
1423
+ message
1424
+ ],
1425
+ sent_at: currentISOTime()
1426
+ };
1427
+ if (this.historicalMigration)
1428
+ data.historical_migration = true;
1429
+ const payload = JSON.stringify(data);
1430
+ const url = `${this.host}/batch/`;
1431
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1432
+ const fetchOptions = {
1433
+ method: "POST",
1434
+ headers: {
1435
+ ...this.getCustomHeaders(),
1436
+ "Content-Type": "application/json",
1437
+ ...gzippedPayload !== null && {
1438
+ "Content-Encoding": "gzip"
1439
+ }
1440
+ },
1441
+ body: gzippedPayload || payload
1442
+ };
1443
+ try {
1444
+ await this.fetchWithRetry(url, fetchOptions);
1445
+ } catch (err) {
1446
+ this._events.emit("error", err);
1447
+ }
1448
+ }
1449
+ prepareMessage(type, _message, options) {
1450
+ const message = {
1451
+ ..._message,
1452
+ type,
1453
+ library: this.getLibraryId(),
1454
+ library_version: this.getLibraryVersion(),
1455
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1456
+ uuid: options?.uuid ? options.uuid : uuidv7()
1457
+ };
1458
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1459
+ if (addGeoipDisableProperty) {
1460
+ if (!message.properties)
1461
+ message.properties = {};
1462
+ message["properties"]["$geoip_disable"] = true;
1463
+ }
1464
+ if (message.distinctId) {
1465
+ message.distinct_id = message.distinctId;
1466
+ delete message.distinctId;
1467
+ }
1468
+ return message;
1469
+ }
1470
+ clearFlushTimer() {
1471
+ if (this._flushTimer) {
1472
+ clearTimeout(this._flushTimer);
1473
+ this._flushTimer = undefined;
1474
+ }
1475
+ }
1476
+ flushBackground() {
1477
+ this.flush().catch(async (err) => {
1478
+ await logFlushError(err);
1479
+ });
1480
+ }
1481
+ async flush() {
1482
+ const nextFlushPromise = allSettled([
1483
+ this.flushPromise
1484
+ ]).then(() => this._flush());
1485
+ this.flushPromise = nextFlushPromise;
1486
+ this.addPendingPromise(nextFlushPromise);
1487
+ allSettled([
1488
+ nextFlushPromise
1489
+ ]).then(() => {
1490
+ if (this.flushPromise === nextFlushPromise)
1491
+ this.flushPromise = null;
1492
+ });
1493
+ return nextFlushPromise;
1494
+ }
1495
+ getCustomHeaders() {
1496
+ const customUserAgent = this.getCustomUserAgent();
1497
+ const headers = {};
1498
+ if (customUserAgent && customUserAgent !== "")
1499
+ headers["User-Agent"] = customUserAgent;
1500
+ return headers;
1501
+ }
1502
+ async _flush() {
1503
+ this.clearFlushTimer();
1504
+ await this._initPromise;
1505
+ let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1506
+ if (!queue.length)
1507
+ return;
1508
+ const sentMessages = [];
1509
+ const originalQueueLength = queue.length;
1510
+ while (queue.length > 0 && sentMessages.length < originalQueueLength) {
1511
+ const batchItems = queue.slice(0, this.maxBatchSize);
1512
+ const batchMessages = batchItems.map((item) => item.message);
1513
+ const persistQueueChange = async () => {
1514
+ const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1515
+ const newQueue = refreshedQueue.slice(batchItems.length);
1516
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
1517
+ queue = newQueue;
1518
+ await this.flushStorage();
1519
+ };
1520
+ const data = {
1521
+ api_key: this.apiKey,
1522
+ batch: batchMessages,
1523
+ sent_at: currentISOTime()
1524
+ };
1525
+ if (this.historicalMigration)
1526
+ data.historical_migration = true;
1527
+ const payload = JSON.stringify(data);
1528
+ const url = `${this.host}/batch/`;
1529
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1530
+ const fetchOptions = {
1531
+ method: "POST",
1532
+ headers: {
1533
+ ...this.getCustomHeaders(),
1534
+ "Content-Type": "application/json",
1535
+ ...gzippedPayload !== null && {
1536
+ "Content-Encoding": "gzip"
1537
+ }
1538
+ },
1539
+ body: gzippedPayload || payload
1540
+ };
1541
+ const retryOptions = {
1542
+ retryCheck: (err) => {
1543
+ if (isPostHogFetchContentTooLargeError(err))
1544
+ return false;
1545
+ return isPostHogFetchError(err);
1546
+ }
1547
+ };
1548
+ try {
1549
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
1550
+ } catch (err) {
1551
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
1552
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
1553
+ this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
1554
+ continue;
1555
+ }
1556
+ if (!(err instanceof PostHogFetchNetworkError))
1557
+ await persistQueueChange();
1558
+ this._events.emit("error", err);
1559
+ throw err;
1560
+ }
1561
+ await persistQueueChange();
1562
+ sentMessages.push(...batchMessages);
1563
+ }
1564
+ this._events.emit("flush", sentMessages);
1565
+ }
1566
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1567
+ AbortSignal.timeout ??= function(ms) {
1568
+ const ctrl = new AbortController;
1569
+ setTimeout(() => ctrl.abort(), ms);
1570
+ return ctrl.signal;
1571
+ };
1572
+ const body = options.body ? options.body : "";
1573
+ let reqByteLength = -1;
1574
+ try {
1575
+ reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
1576
+ } catch {
1577
+ if (body instanceof Blob)
1578
+ reqByteLength = body.size;
1579
+ else {
1580
+ const encoded = new TextEncoder().encode(body);
1581
+ reqByteLength = encoded.length;
1582
+ }
1583
+ }
1584
+ return await retriable(async () => {
1585
+ let res = null;
1586
+ try {
1587
+ res = await this.fetch(url, {
1588
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1589
+ ...options
1590
+ });
1591
+ } catch (e) {
1592
+ throw new PostHogFetchNetworkError(e);
1593
+ }
1594
+ const isNoCors = options.mode === "no-cors";
1595
+ if (!isNoCors && (res.status < 200 || res.status >= 400))
1596
+ throw new PostHogFetchHttpError(res, reqByteLength);
1597
+ return res;
1598
+ }, {
1599
+ ...this._retryOptions,
1600
+ ...retryOptions
1601
+ });
1602
+ }
1603
+ async _shutdown(shutdownTimeoutMs = 30000) {
1604
+ await this._initPromise;
1605
+ let hasTimedOut = false;
1606
+ this.clearFlushTimer();
1607
+ const doShutdown = async () => {
1608
+ try {
1609
+ await this.promiseQueue.join();
1610
+ while (true) {
1611
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1612
+ if (queue.length === 0)
1613
+ break;
1614
+ await this.flush();
1615
+ if (hasTimedOut)
1616
+ break;
1617
+ }
1618
+ } catch (e) {
1619
+ if (!isPostHogFetchError(e))
1620
+ throw e;
1621
+ await logFlushError(e);
1622
+ }
1623
+ };
1624
+ return Promise.race([
1625
+ new Promise((_, reject) => {
1626
+ safeSetTimeout(() => {
1627
+ this._logger.error("Timed out while shutting down PostHog");
1628
+ hasTimedOut = true;
1629
+ reject("Timeout while shutting down PostHog. Some events may not have been sent.");
1630
+ }, shutdownTimeoutMs);
1631
+ }),
1632
+ doShutdown()
1633
+ ]);
1634
+ }
1635
+ async shutdown(shutdownTimeoutMs = 30000) {
1636
+ if (this.shutdownPromise)
1637
+ this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");
1638
+ else
1639
+ this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
1640
+ this.shutdownPromise = null;
1641
+ });
1642
+ return this.shutdownPromise;
1643
+ }
1644
+ }
1645
+ // node_modules/@posthog/core/dist/error-tracking/index.mjs
1646
+ var exports_error_tracking = {};
1647
+ __export(exports_error_tracking, {
1648
+ winjsStackLineParser: () => winjsStackLineParser,
1649
+ reverseAndStripFrames: () => reverseAndStripFrames,
1650
+ opera11StackLineParser: () => opera11StackLineParser,
1651
+ opera10StackLineParser: () => opera10StackLineParser,
1652
+ nodeStackLineParser: () => nodeStackLineParser,
1653
+ geckoStackLineParser: () => geckoStackLineParser,
1654
+ createStackParser: () => createStackParser,
1655
+ createDefaultStackParser: () => createDefaultStackParser,
1656
+ chromeStackLineParser: () => chromeStackLineParser,
1657
+ StringCoercer: () => StringCoercer,
1658
+ ReduceableCache: () => ReduceableCache,
1659
+ PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
1660
+ PrimitiveCoercer: () => PrimitiveCoercer,
1661
+ ObjectCoercer: () => ObjectCoercer,
1662
+ EventCoercer: () => EventCoercer,
1663
+ ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
1664
+ ErrorEventCoercer: () => ErrorEventCoercer,
1665
+ ErrorCoercer: () => ErrorCoercer,
1666
+ DOMExceptionCoercer: () => DOMExceptionCoercer
1667
+ });
1668
+
1669
+ // node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1670
+ var parsedStackResults;
1671
+ var lastKeysCount;
1672
+ var cachedFilenameChunkIds;
1673
+ function getFilenameToChunkIdMap(stackParser) {
1674
+ const chunkIdMap = globalThis._posthogChunkIds;
1675
+ if (!chunkIdMap)
1676
+ return;
1677
+ const chunkIdKeys = Object.keys(chunkIdMap);
1678
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount)
1679
+ return cachedFilenameChunkIds;
1680
+ lastKeysCount = chunkIdKeys.length;
1681
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
1682
+ if (!parsedStackResults)
1683
+ parsedStackResults = {};
1684
+ const result = parsedStackResults[stackKey];
1685
+ if (result)
1686
+ acc[result[0]] = result[1];
1687
+ else {
1688
+ const parsedStack = stackParser(stackKey);
1689
+ for (let i = parsedStack.length - 1;i >= 0; i--) {
1690
+ const stackFrame = parsedStack[i];
1691
+ const filename = stackFrame?.filename;
1692
+ const chunkId = chunkIdMap[stackKey];
1693
+ if (filename && chunkId) {
1694
+ acc[filename] = chunkId;
1695
+ parsedStackResults[stackKey] = [
1696
+ filename,
1697
+ chunkId
1698
+ ];
1699
+ break;
1700
+ }
1701
+ }
1702
+ }
1703
+ return acc;
1704
+ }, {});
1705
+ return cachedFilenameChunkIds;
1706
+ }
1707
+
1708
+ // node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1709
+ var MAX_CAUSE_RECURSION = 4;
1710
+
1711
+ class ErrorPropertiesBuilder {
1712
+ constructor(coercers, stackParser, modifiers = []) {
1713
+ this.coercers = coercers;
1714
+ this.stackParser = stackParser;
1715
+ this.modifiers = modifiers;
1716
+ }
1717
+ buildFromUnknown(input, hint = {}) {
1718
+ const providedMechanism = hint && hint.mechanism;
1719
+ const mechanism = providedMechanism || {
1720
+ handled: true,
1721
+ type: "generic"
1722
+ };
1723
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
1724
+ const exceptionWithCause = coercingContext.apply(input);
1725
+ const parsingContext = this.buildParsingContext(hint);
1726
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
1727
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
1728
+ return {
1729
+ $exception_list: exceptionList,
1730
+ $exception_level: "error"
1731
+ };
1732
+ }
1733
+ async modifyFrames(exceptionList) {
1734
+ for (const exc of exceptionList)
1735
+ if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames))
1736
+ exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
1737
+ return exceptionList;
1738
+ }
1739
+ coerceFallback(ctx) {
1740
+ return {
1741
+ type: "Error",
1742
+ value: "Unknown error",
1743
+ stack: ctx.syntheticException?.stack,
1744
+ synthetic: true
1745
+ };
1746
+ }
1747
+ parseStacktrace(err, ctx) {
1748
+ let cause;
1749
+ if (err.cause != null)
1750
+ cause = this.parseStacktrace(err.cause, ctx);
1751
+ let stack;
1752
+ if (err.stack != "" && err.stack != null)
1753
+ stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);
1754
+ return {
1755
+ ...err,
1756
+ cause,
1757
+ stack
1758
+ };
1759
+ }
1760
+ applyChunkIds(frames, chunkIdMap) {
1761
+ return frames.map((frame) => {
1762
+ if (frame.filename && chunkIdMap)
1763
+ frame.chunk_id = chunkIdMap[frame.filename];
1764
+ return frame;
1765
+ });
1766
+ }
1767
+ applyCoercers(input, ctx) {
1768
+ for (const adapter of this.coercers)
1769
+ if (adapter.match(input))
1770
+ return adapter.coerce(input, ctx);
1771
+ return this.coerceFallback(ctx);
1772
+ }
1773
+ async applyModifiers(frames) {
1774
+ let newFrames = frames;
1775
+ for (const modifier of this.modifiers)
1776
+ newFrames = await modifier(newFrames);
1777
+ return newFrames;
1778
+ }
1779
+ convertToExceptionList(exceptionWithStack, mechanism) {
1780
+ const currentException = {
1781
+ type: exceptionWithStack.type,
1782
+ value: exceptionWithStack.value,
1783
+ mechanism: {
1784
+ type: mechanism.type ?? "generic",
1785
+ handled: mechanism.handled ?? true,
1786
+ synthetic: exceptionWithStack.synthetic ?? false
1787
+ }
1788
+ };
1789
+ if (exceptionWithStack.stack)
1790
+ currentException.stacktrace = {
1791
+ type: "raw",
1792
+ frames: exceptionWithStack.stack
1793
+ };
1794
+ const exceptionList = [
1795
+ currentException
1796
+ ];
1797
+ if (exceptionWithStack.cause != null)
1798
+ exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
1799
+ ...mechanism,
1800
+ handled: true
1801
+ }));
1802
+ return exceptionList;
1803
+ }
1804
+ buildParsingContext(hint) {
1805
+ const context = {
1806
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser),
1807
+ skipFirstLines: hint.skipFirstLines ?? 1
1808
+ };
1809
+ return context;
1810
+ }
1811
+ buildCoercingContext(mechanism, hint, depth = 0) {
1812
+ const coerce = (input, depth2) => {
1813
+ if (!(depth2 <= MAX_CAUSE_RECURSION))
1814
+ return;
1815
+ {
1816
+ const ctx = this.buildCoercingContext(mechanism, hint, depth2);
1817
+ return this.applyCoercers(input, ctx);
1818
+ }
1819
+ };
1820
+ const context = {
1821
+ ...hint,
1822
+ syntheticException: depth == 0 ? hint.syntheticException : undefined,
1823
+ mechanism,
1824
+ apply: (input) => coerce(input, depth),
1825
+ next: (input) => coerce(input, depth + 1)
1826
+ };
1827
+ return context;
1828
+ }
1829
+ }
1830
+ // node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1831
+ var UNKNOWN_FUNCTION = "?";
1832
+ function createFrame(platform, filename, func, lineno, colno) {
1833
+ const frame = {
1834
+ platform,
1835
+ filename,
1836
+ function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
1837
+ in_app: true
1838
+ };
1839
+ if (!isUndefined(lineno))
1840
+ frame.lineno = lineno;
1841
+ if (!isUndefined(colno))
1842
+ frame.colno = colno;
1843
+ return frame;
1844
+ }
1845
+
1846
+ // node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1847
+ var extractSafariExtensionDetails = (func, filename) => {
1848
+ const isSafariExtension = func.indexOf("safari-extension") !== -1;
1849
+ const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
1850
+ return isSafariExtension || isSafariWebExtension ? [
1851
+ func.indexOf("@") !== -1 ? func.split("@")[0] : UNKNOWN_FUNCTION,
1852
+ isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`
1853
+ ] : [
1854
+ func,
1855
+ filename
1856
+ ];
1857
+ };
1858
+
1859
+ // node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1860
+ var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
1861
+ var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1862
+ var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1863
+ var chromeStackLineParser = (line, platform) => {
1864
+ const noFnParts = chromeRegexNoFnName.exec(line);
1865
+ if (noFnParts) {
1866
+ const [, filename, line2, col] = noFnParts;
1867
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line2, +col);
1868
+ }
1869
+ const parts = chromeRegex.exec(line);
1870
+ if (parts) {
1871
+ const isEval = parts[2] && parts[2].indexOf("eval") === 0;
1872
+ if (isEval) {
1873
+ const subMatch = chromeEvalRegex.exec(parts[2]);
1874
+ if (subMatch) {
1875
+ parts[2] = subMatch[1];
1876
+ parts[3] = subMatch[2];
1877
+ parts[4] = subMatch[3];
1878
+ }
1879
+ }
1880
+ const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);
1881
+ return createFrame(platform, filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);
1882
+ }
1883
+ };
1884
+
1885
+ // node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1886
+ var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
1887
+ var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1888
+ var geckoStackLineParser = (line, platform) => {
1889
+ const parts = geckoREgex.exec(line);
1890
+ if (parts) {
1891
+ const isEval = parts[3] && parts[3].indexOf(" > eval") > -1;
1892
+ if (isEval) {
1893
+ const subMatch = geckoEvalRegex.exec(parts[3]);
1894
+ if (subMatch) {
1895
+ parts[1] = parts[1] || "eval";
1896
+ parts[3] = subMatch[1];
1897
+ parts[4] = subMatch[2];
1898
+ parts[5] = "";
1899
+ }
1900
+ }
1901
+ let filename = parts[3];
1902
+ let func = parts[1] || UNKNOWN_FUNCTION;
1903
+ [func, filename] = extractSafariExtensionDetails(func, filename);
1904
+ return createFrame(platform, filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);
1905
+ }
1906
+ };
1907
+
1908
+ // node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1909
+ var winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1910
+ var winjsStackLineParser = (line, platform) => {
1911
+ const parts = winjsRegex.exec(line);
1912
+ return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined) : undefined;
1913
+ };
1914
+
1915
+ // node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1916
+ var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
1917
+ var opera10StackLineParser = (line, platform) => {
1918
+ const parts = opera10Regex.exec(line);
1919
+ return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;
1920
+ };
1921
+ var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1922
+ var opera11StackLineParser = (line, platform) => {
1923
+ const parts = opera11Regex.exec(line);
1924
+ return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;
1925
+ };
1926
+
1927
+ // node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1928
+ var FILENAME_MATCH = /^\s*[-]{4,}$/;
1929
+ var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
1930
+ var nodeStackLineParser = (line, platform) => {
1931
+ const lineMatch = line.match(FULL_MATCH);
1932
+ if (lineMatch) {
1933
+ let object;
1934
+ let method;
1935
+ let functionName;
1936
+ let typeName;
1937
+ let methodName;
1938
+ if (lineMatch[1]) {
1939
+ functionName = lineMatch[1];
1940
+ let methodStart = functionName.lastIndexOf(".");
1941
+ if (functionName[methodStart - 1] === ".")
1942
+ methodStart--;
1943
+ if (methodStart > 0) {
1944
+ object = functionName.slice(0, methodStart);
1945
+ method = functionName.slice(methodStart + 1);
1946
+ const objectEnd = object.indexOf(".Module");
1947
+ if (objectEnd > 0) {
1948
+ functionName = functionName.slice(objectEnd + 1);
1949
+ object = object.slice(0, objectEnd);
1950
+ }
1951
+ }
1952
+ typeName = undefined;
1953
+ }
1954
+ if (method) {
1955
+ typeName = object;
1956
+ methodName = method;
1957
+ }
1958
+ if (method === "<anonymous>") {
1959
+ methodName = undefined;
1960
+ functionName = undefined;
1961
+ }
1962
+ if (functionName === undefined) {
1963
+ methodName = methodName || UNKNOWN_FUNCTION;
1964
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
1965
+ }
1966
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
1967
+ const isNative = lineMatch[5] === "native";
1968
+ if (filename?.match(/\/[A-Z]:/))
1969
+ filename = filename.slice(1);
1970
+ if (!filename && lineMatch[5] && !isNative)
1971
+ filename = lineMatch[5];
1972
+ return {
1973
+ filename: filename ? decodeURI(filename) : undefined,
1974
+ module: undefined,
1975
+ function: functionName,
1976
+ lineno: _parseIntOrUndefined(lineMatch[3]),
1977
+ colno: _parseIntOrUndefined(lineMatch[4]),
1978
+ in_app: filenameIsInApp(filename || "", isNative),
1979
+ platform
1980
+ };
1981
+ }
1982
+ if (line.match(FILENAME_MATCH))
1983
+ return {
1984
+ filename: line,
1985
+ platform
1986
+ };
1987
+ };
1988
+ function filenameIsInApp(filename, isNative = false) {
1989
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
1990
+ return !isInternal && filename !== undefined && !filename.includes("node_modules/");
1991
+ }
1992
+ function _parseIntOrUndefined(input) {
1993
+ return parseInt(input || "", 10) || undefined;
1994
+ }
1995
+
1996
+ // node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1997
+ var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1998
+ var STACKTRACE_FRAME_LIMIT = 50;
1999
+ function reverseAndStripFrames(stack) {
2000
+ if (!stack.length)
2001
+ return [];
2002
+ const localStack = Array.from(stack);
2003
+ localStack.reverse();
2004
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
2005
+ ...frame,
2006
+ filename: frame.filename || getLastStackFrame(localStack).filename,
2007
+ function: frame.function || UNKNOWN_FUNCTION
2008
+ }));
2009
+ }
2010
+ function getLastStackFrame(arr) {
2011
+ return arr[arr.length - 1] || {};
2012
+ }
2013
+ function createDefaultStackParser() {
2014
+ return createStackParser("web:javascript", chromeStackLineParser, geckoStackLineParser);
2015
+ }
2016
+ function createStackParser(platform, ...parsers) {
2017
+ return (stack, skipFirstLines = 0) => {
2018
+ const frames = [];
2019
+ const lines = stack.split(`
2020
+ `);
2021
+ for (let i = skipFirstLines;i < lines.length; i++) {
2022
+ const line = lines[i];
2023
+ if (line.length > 1024)
2024
+ continue;
2025
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
2026
+ if (!cleanedLine.match(/\S*Error: /)) {
2027
+ for (const parser of parsers) {
2028
+ const frame = parser(cleanedLine, platform);
2029
+ if (frame) {
2030
+ frames.push(frame);
2031
+ break;
2032
+ }
2033
+ }
2034
+ if (frames.length >= STACKTRACE_FRAME_LIMIT)
2035
+ break;
2036
+ }
2037
+ }
2038
+ return reverseAndStripFrames(frames);
2039
+ };
2040
+ }
2041
+ // node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
2042
+ class DOMExceptionCoercer {
2043
+ match(err) {
2044
+ return this.isDOMException(err) || this.isDOMError(err);
2045
+ }
2046
+ coerce(err, ctx) {
2047
+ const hasStack = isString(err.stack);
2048
+ return {
2049
+ type: this.getType(err),
2050
+ value: this.getValue(err),
2051
+ stack: hasStack ? err.stack : undefined,
2052
+ cause: err.cause ? ctx.next(err.cause) : undefined,
2053
+ synthetic: false
2054
+ };
2055
+ }
2056
+ getType(candidate) {
2057
+ return this.isDOMError(candidate) ? "DOMError" : "DOMException";
2058
+ }
2059
+ getValue(err) {
2060
+ const name = err.name || (this.isDOMError(err) ? "DOMError" : "DOMException");
2061
+ const message = err.message ? `${name}: ${err.message}` : name;
2062
+ return message;
2063
+ }
2064
+ isDOMException(err) {
2065
+ return isBuiltin(err, "DOMException");
2066
+ }
2067
+ isDOMError(err) {
2068
+ return isBuiltin(err, "DOMError");
2069
+ }
2070
+ }
2071
+ // node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2072
+ class ErrorCoercer {
2073
+ match(err) {
2074
+ return isPlainError(err);
2075
+ }
2076
+ coerce(err, ctx) {
2077
+ return {
2078
+ type: this.getType(err),
2079
+ value: this.getMessage(err, ctx),
2080
+ stack: this.getStack(err),
2081
+ cause: err.cause ? ctx.next(err.cause) : undefined,
2082
+ synthetic: false
2083
+ };
2084
+ }
2085
+ getType(err) {
2086
+ return err.name || err.constructor.name;
2087
+ }
2088
+ getMessage(err, _ctx) {
2089
+ const message = err.message;
2090
+ if (message.error && typeof message.error.message == "string")
2091
+ return String(message.error.message);
2092
+ return String(message);
2093
+ }
2094
+ getStack(err) {
2095
+ return err.stacktrace || err.stack || undefined;
2096
+ }
2097
+ }
2098
+ // node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
2099
+ class ErrorEventCoercer {
2100
+ constructor() {}
2101
+ match(err) {
2102
+ return isErrorEvent(err) && err.error != null;
2103
+ }
2104
+ coerce(err, ctx) {
2105
+ const exceptionLike = ctx.apply(err.error);
2106
+ if (!exceptionLike)
2107
+ return {
2108
+ type: "ErrorEvent",
2109
+ value: err.message,
2110
+ stack: ctx.syntheticException?.stack,
2111
+ synthetic: true
2112
+ };
2113
+ return exceptionLike;
2114
+ }
2115
+ }
2116
+ // node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2117
+ var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
2118
+
2119
+ class StringCoercer {
2120
+ match(input) {
2121
+ return typeof input == "string";
2122
+ }
2123
+ coerce(input, ctx) {
2124
+ const [type, value] = this.getInfos(input);
2125
+ return {
2126
+ type: type ?? "Error",
2127
+ value: value ?? input,
2128
+ stack: ctx.syntheticException?.stack,
2129
+ synthetic: true
2130
+ };
2131
+ }
2132
+ getInfos(candidate) {
2133
+ let type = "Error";
2134
+ let value = candidate;
2135
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
2136
+ if (groups) {
2137
+ type = groups[1];
2138
+ value = groups[2];
2139
+ }
2140
+ return [
2141
+ type,
2142
+ value
2143
+ ];
2144
+ }
2145
+ }
2146
+ // node_modules/@posthog/core/dist/error-tracking/types.mjs
2147
+ var severityLevels = [
2148
+ "fatal",
2149
+ "error",
2150
+ "warning",
2151
+ "log",
2152
+ "info",
2153
+ "debug"
2154
+ ];
2155
+
2156
+ // node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2157
+ function extractExceptionKeysForMessage(err, maxLength = 40) {
2158
+ const keys = Object.keys(err);
2159
+ keys.sort();
2160
+ if (!keys.length)
2161
+ return "[object has no keys]";
2162
+ for (let i = keys.length;i > 0; i--) {
2163
+ const serialized = keys.slice(0, i).join(", ");
2164
+ if (!(serialized.length > maxLength)) {
2165
+ if (i === keys.length)
2166
+ return serialized;
2167
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
2168
+ }
2169
+ }
2170
+ return "";
2171
+ }
2172
+
2173
+ // node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2174
+ class ObjectCoercer {
2175
+ match(candidate) {
2176
+ return typeof candidate == "object" && candidate !== null;
2177
+ }
2178
+ coerce(candidate, ctx) {
2179
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
2180
+ if (errorProperty)
2181
+ return ctx.apply(errorProperty);
2182
+ return {
2183
+ type: this.getType(candidate),
2184
+ value: this.getValue(candidate),
2185
+ stack: ctx.syntheticException?.stack,
2186
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
2187
+ synthetic: true
2188
+ };
2189
+ }
2190
+ getType(err) {
2191
+ return isEvent(err) ? err.constructor.name : "Error";
2192
+ }
2193
+ getValue(err) {
2194
+ if ("name" in err && typeof err.name == "string") {
2195
+ let message = `'${err.name}' captured as exception`;
2196
+ if ("message" in err && typeof err.message == "string")
2197
+ message += ` with message: '${err.message}'`;
2198
+ return message;
2199
+ }
2200
+ if ("message" in err && typeof err.message == "string")
2201
+ return err.message;
2202
+ const className = this.getObjectClassName(err);
2203
+ const keys = extractExceptionKeysForMessage(err);
2204
+ return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
2205
+ }
2206
+ isSeverityLevel(x) {
2207
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
2208
+ }
2209
+ getErrorPropertyFromObject(obj) {
2210
+ for (const prop in obj)
2211
+ if (Object.prototype.hasOwnProperty.call(obj, prop)) {
2212
+ const value = obj[prop];
2213
+ if (isError(value))
2214
+ return value;
2215
+ }
2216
+ }
2217
+ getObjectClassName(obj) {
2218
+ try {
2219
+ const prototype = Object.getPrototypeOf(obj);
2220
+ return prototype ? prototype.constructor.name : undefined;
2221
+ } catch (e) {
2222
+ return;
2223
+ }
2224
+ }
2225
+ }
2226
+ // node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2227
+ class EventCoercer {
2228
+ match(err) {
2229
+ return isEvent(err);
2230
+ }
2231
+ coerce(evt, ctx) {
2232
+ const constructorName = evt.constructor.name;
2233
+ return {
2234
+ type: constructorName,
2235
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
2236
+ stack: ctx.syntheticException?.stack,
2237
+ synthetic: true
2238
+ };
2239
+ }
2240
+ }
2241
+ // node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2242
+ class PrimitiveCoercer {
2243
+ match(candidate) {
2244
+ return isPrimitive(candidate);
2245
+ }
2246
+ coerce(value, ctx) {
2247
+ return {
2248
+ type: "Error",
2249
+ value: `Primitive value captured as exception: ${String(value)}`,
2250
+ stack: ctx.syntheticException?.stack,
2251
+ synthetic: true
2252
+ };
2253
+ }
2254
+ }
2255
+ // node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2256
+ class PromiseRejectionEventCoercer {
2257
+ match(err) {
2258
+ return isBuiltin(err, "PromiseRejectionEvent");
2259
+ }
2260
+ coerce(err, ctx) {
2261
+ const reason = this.getUnhandledRejectionReason(err);
2262
+ if (isPrimitive(reason))
2263
+ return {
2264
+ type: "UnhandledRejection",
2265
+ value: `Non-Error promise rejection captured with value: ${String(reason)}`,
2266
+ stack: ctx.syntheticException?.stack,
2267
+ synthetic: true
2268
+ };
2269
+ return ctx.apply(reason);
2270
+ }
2271
+ getUnhandledRejectionReason(error) {
2272
+ if (isPrimitive(error))
2273
+ return error;
2274
+ try {
2275
+ if ("reason" in error)
2276
+ return error.reason;
2277
+ if ("detail" in error && "reason" in error.detail)
2278
+ return error.detail.reason;
2279
+ } catch {}
2280
+ return error;
2281
+ }
2282
+ }
2283
+ // node_modules/@posthog/core/dist/error-tracking/utils.mjs
2284
+ class ReduceableCache {
2285
+ constructor(_maxSize) {
2286
+ this._maxSize = _maxSize;
2287
+ this._cache = new Map;
2288
+ }
2289
+ get(key) {
2290
+ const value = this._cache.get(key);
2291
+ if (value === undefined)
2292
+ return;
2293
+ this._cache.delete(key);
2294
+ this._cache.set(key, value);
2295
+ return value;
2296
+ }
2297
+ set(key, value) {
2298
+ this._cache.set(key, value);
2299
+ }
2300
+ reduce() {
2301
+ while (this._cache.size >= this._maxSize) {
2302
+ const value = this._cache.keys().next().value;
2303
+ if (value)
2304
+ this._cache.delete(value);
2305
+ }
2306
+ }
2307
+ }
2308
+ // node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
2309
+ import { createReadStream } from "fs";
2310
+ import { createInterface } from "readline";
2311
+ var LRU_FILE_CONTENTS_CACHE = new exports_error_tracking.ReduceableCache(25);
2312
+ var LRU_FILE_CONTENTS_FS_READ_FAILED = new exports_error_tracking.ReduceableCache(20);
2313
+ var DEFAULT_LINES_OF_CONTEXT = 7;
2314
+ var MAX_CONTEXTLINES_COLNO = 1000;
2315
+ var MAX_CONTEXTLINES_LINENO = 1e4;
2316
+ async function addSourceContext(frames) {
2317
+ const filesToLines = {};
2318
+ for (let i = frames.length - 1;i >= 0; i--) {
2319
+ const frame = frames[i];
2320
+ const filename = frame?.filename;
2321
+ if (!frame || typeof filename != "string" || typeof frame.lineno != "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame))
2322
+ continue;
2323
+ const filesToLinesOutput = filesToLines[filename];
2324
+ if (!filesToLinesOutput)
2325
+ filesToLines[filename] = [];
2326
+ filesToLines[filename].push(frame.lineno);
2327
+ }
2328
+ const files = Object.keys(filesToLines);
2329
+ if (files.length == 0)
2330
+ return frames;
2331
+ const readlinePromises = [];
2332
+ for (const file of files) {
2333
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file))
2334
+ continue;
2335
+ const filesToLineRanges = filesToLines[file];
2336
+ if (!filesToLineRanges)
2337
+ continue;
2338
+ filesToLineRanges.sort((a, b) => a - b);
2339
+ const ranges = makeLineReaderRanges(filesToLineRanges);
2340
+ if (ranges.every((r) => rangeExistsInContentCache(file, r)))
2341
+ continue;
2342
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
2343
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
2344
+ }
2345
+ await Promise.all(readlinePromises).catch(() => {});
2346
+ if (frames && frames.length > 0)
2347
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
2348
+ LRU_FILE_CONTENTS_CACHE.reduce();
2349
+ return frames;
2350
+ }
2351
+ function getContextLinesFromFile(path, ranges, output) {
2352
+ return new Promise((resolve) => {
2353
+ const stream = createReadStream(path);
2354
+ const lineReaded = createInterface({
2355
+ input: stream
2356
+ });
2357
+ function destroyStreamAndResolve() {
2358
+ stream.destroy();
2359
+ resolve();
2360
+ }
2361
+ let lineNumber = 0;
2362
+ let currentRangeIndex = 0;
2363
+ const range = ranges[currentRangeIndex];
2364
+ if (range === undefined)
2365
+ return void destroyStreamAndResolve();
2366
+ let rangeStart = range[0];
2367
+ let rangeEnd = range[1];
2368
+ function onStreamError() {
2369
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
2370
+ lineReaded.close();
2371
+ lineReaded.removeAllListeners();
2372
+ destroyStreamAndResolve();
2373
+ }
2374
+ stream.on("error", onStreamError);
2375
+ lineReaded.on("error", onStreamError);
2376
+ lineReaded.on("close", destroyStreamAndResolve);
2377
+ lineReaded.on("line", (line) => {
2378
+ lineNumber++;
2379
+ if (lineNumber < rangeStart)
2380
+ return;
2381
+ output[lineNumber] = snipLine(line, 0);
2382
+ if (lineNumber >= rangeEnd) {
2383
+ if (currentRangeIndex === ranges.length - 1) {
2384
+ lineReaded.close();
2385
+ lineReaded.removeAllListeners();
2386
+ return;
2387
+ }
2388
+ currentRangeIndex++;
2389
+ const range2 = ranges[currentRangeIndex];
2390
+ if (range2 === undefined) {
2391
+ lineReaded.close();
2392
+ lineReaded.removeAllListeners();
2393
+ return;
2394
+ }
2395
+ rangeStart = range2[0];
2396
+ rangeEnd = range2[1];
2397
+ }
2398
+ });
2399
+ });
2400
+ }
2401
+ function addSourceContextToFrames(frames, cache) {
2402
+ for (const frame of frames)
2403
+ if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
2404
+ const contents = cache.get(frame.filename);
2405
+ if (contents === undefined)
2406
+ continue;
2407
+ addContextToFrame(frame.lineno, frame, contents);
2408
+ }
2409
+ }
2410
+ function addContextToFrame(lineno, frame, contents) {
2411
+ if (frame.lineno === undefined || contents === undefined)
2412
+ return;
2413
+ frame.pre_context = [];
2414
+ for (let i = makeRangeStart(lineno);i < lineno; i++) {
2415
+ const line = contents[i];
2416
+ if (line === undefined)
2417
+ return void clearLineContext(frame);
2418
+ frame.pre_context.push(line);
2419
+ }
2420
+ if (contents[lineno] === undefined)
2421
+ return void clearLineContext(frame);
2422
+ frame.context_line = contents[lineno];
2423
+ const end = makeRangeEnd(lineno);
2424
+ frame.post_context = [];
2425
+ for (let i = lineno + 1;i <= end; i++) {
2426
+ const line = contents[i];
2427
+ if (line === undefined)
2428
+ break;
2429
+ frame.post_context.push(line);
2430
+ }
2431
+ }
2432
+ function clearLineContext(frame) {
2433
+ delete frame.pre_context;
2434
+ delete frame.context_line;
2435
+ delete frame.post_context;
2436
+ }
2437
+ function shouldSkipContextLinesForFile(path) {
2438
+ return path.startsWith("node:") || path.endsWith(".min.js") || path.endsWith(".min.cjs") || path.endsWith(".min.mjs") || path.startsWith("data:");
2439
+ }
2440
+ function shouldSkipContextLinesForFrame(frame) {
2441
+ if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO)
2442
+ return true;
2443
+ if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO)
2444
+ return true;
2445
+ return false;
2446
+ }
2447
+ function rangeExistsInContentCache(file, range) {
2448
+ const contents = LRU_FILE_CONTENTS_CACHE.get(file);
2449
+ if (contents === undefined)
2450
+ return false;
2451
+ for (let i = range[0];i <= range[1]; i++)
2452
+ if (contents[i] === undefined)
2453
+ return false;
2454
+ return true;
2455
+ }
2456
+ function makeLineReaderRanges(lines) {
2457
+ if (!lines.length)
2458
+ return [];
2459
+ let i = 0;
2460
+ const line = lines[0];
2461
+ if (typeof line != "number")
2462
+ return [];
2463
+ let current = makeContextRange(line);
2464
+ const out = [];
2465
+ while (true) {
2466
+ if (i === lines.length - 1) {
2467
+ out.push(current);
2468
+ break;
2469
+ }
2470
+ const next = lines[i + 1];
2471
+ if (typeof next != "number")
2472
+ break;
2473
+ if (next <= current[1])
2474
+ current[1] = next + DEFAULT_LINES_OF_CONTEXT;
2475
+ else {
2476
+ out.push(current);
2477
+ current = makeContextRange(next);
2478
+ }
2479
+ i++;
2480
+ }
2481
+ return out;
2482
+ }
2483
+ function makeContextRange(line) {
2484
+ return [
2485
+ makeRangeStart(line),
2486
+ makeRangeEnd(line)
2487
+ ];
2488
+ }
2489
+ function makeRangeStart(line) {
2490
+ return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);
2491
+ }
2492
+ function makeRangeEnd(line) {
2493
+ return line + DEFAULT_LINES_OF_CONTEXT;
2494
+ }
2495
+ function emplace(map, key, contents) {
2496
+ const value = map.get(key);
2497
+ if (value === undefined) {
2498
+ map.set(key, contents);
2499
+ return contents;
2500
+ }
2501
+ return value;
2502
+ }
2503
+ function snipLine(line, colno) {
2504
+ let newLine = line;
2505
+ const lineLength = newLine.length;
2506
+ if (lineLength <= 150)
2507
+ return newLine;
2508
+ if (colno > lineLength)
2509
+ colno = lineLength;
2510
+ let start = Math.max(colno - 60, 0);
2511
+ if (start < 5)
2512
+ start = 0;
2513
+ let end = Math.min(start + 140, lineLength);
2514
+ if (end > lineLength - 5)
2515
+ end = lineLength;
2516
+ if (end === lineLength)
2517
+ start = Math.max(end - 140, 0);
2518
+ newLine = newLine.slice(start, end);
2519
+ if (start > 0)
2520
+ newLine = `...${newLine}`;
2521
+ if (end < lineLength)
2522
+ newLine += "...";
2523
+ return newLine;
2524
+ }
2525
+
2526
+ // node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
2527
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
2528
+ let calledFatalError = false;
2529
+ return Object.assign((error) => {
2530
+ const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => listener.name !== "domainUncaughtExceptionClear" && listener._posthogErrorHandler !== true).length;
2531
+ const processWouldExit = userProvidedListenersCount === 0;
2532
+ captureFn(error, {
2533
+ mechanism: {
2534
+ type: "onuncaughtexception",
2535
+ handled: false
2536
+ }
2537
+ });
2538
+ if (!calledFatalError && processWouldExit) {
2539
+ calledFatalError = true;
2540
+ onFatalFn(error);
2541
+ }
2542
+ }, {
2543
+ _posthogErrorHandler: true
2544
+ });
2545
+ }
2546
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
2547
+ globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
2548
+ }
2549
+ function addUnhandledRejectionListener(captureFn) {
2550
+ globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
2551
+ mechanism: {
2552
+ type: "onunhandledrejection",
2553
+ handled: false
2554
+ }
2555
+ }));
2556
+ }
2557
+
2558
+ // node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
2559
+ var SHUTDOWN_TIMEOUT = 2000;
2560
+
2561
+ class ErrorTracking {
2562
+ constructor(client, options, _logger) {
2563
+ this.client = client;
2564
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
2565
+ this._logger = _logger;
2566
+ this._rateLimiter = new BucketedRateLimiter({
2567
+ refillRate: 1,
2568
+ bucketSize: 10,
2569
+ refillInterval: 1e4,
2570
+ _logger: this._logger
2571
+ });
2572
+ this.startAutocaptureIfEnabled();
2573
+ }
2574
+ static isPreviouslyCapturedError(x) {
2575
+ return isObject(x) && "__posthog_previously_captured_error" in x && x.__posthog_previously_captured_error === true;
2576
+ }
2577
+ static async buildEventMessage(error, hint, distinctId, additionalProperties) {
2578
+ const properties = {
2579
+ ...additionalProperties
2580
+ };
2581
+ if (!distinctId)
2582
+ properties.$process_person_profile = false;
2583
+ const exceptionProperties = this.errorPropertiesBuilder.buildFromUnknown(error, hint);
2584
+ exceptionProperties.$exception_list = await this.errorPropertiesBuilder.modifyFrames(exceptionProperties.$exception_list);
2585
+ return {
2586
+ event: "$exception",
2587
+ distinctId: distinctId || uuidv7(),
2588
+ properties: {
2589
+ ...exceptionProperties,
2590
+ ...properties
2591
+ },
2592
+ _originatedFromCaptureException: true
2593
+ };
2594
+ }
2595
+ startAutocaptureIfEnabled() {
2596
+ if (this.isEnabled()) {
2597
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
2598
+ addUnhandledRejectionListener(this.onException.bind(this));
2599
+ }
2600
+ }
2601
+ onException(exception, hint) {
2602
+ this.client.addPendingPromise((async () => {
2603
+ if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
2604
+ const eventMessage = await ErrorTracking.buildEventMessage(exception, hint);
2605
+ const exceptionProperties = eventMessage.properties;
2606
+ const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
2607
+ const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
2608
+ if (isRateLimited)
2609
+ return void this._logger.info("Skipping exception capture because of client rate limiting.", {
2610
+ exception: exceptionType
2611
+ });
2612
+ return this.client.capture(eventMessage);
2613
+ }
2614
+ })());
2615
+ }
2616
+ async onFatalError(exception) {
2617
+ console.error(exception);
2618
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
2619
+ process.exit(1);
2620
+ }
2621
+ isEnabled() {
2622
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
2623
+ }
2624
+ shutdown() {
2625
+ this._rateLimiter.stop();
2626
+ }
2627
+ }
2628
+
2629
+ // node_modules/posthog-node/dist/version.mjs
2630
+ var version = "5.26.0";
2631
+
2632
+ // node_modules/posthog-node/dist/types.mjs
2633
+ var FeatureFlagError2 = {
2634
+ ERRORS_WHILE_COMPUTING: "errors_while_computing_flags",
2635
+ FLAG_MISSING: "flag_missing",
2636
+ QUOTA_LIMITED: "quota_limited",
2637
+ UNKNOWN_ERROR: "unknown_error"
2638
+ };
2639
+
2640
+ // node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
2641
+ async function hashSHA1(text) {
2642
+ const subtle = globalThis.crypto?.subtle;
2643
+ if (!subtle)
2644
+ throw new Error("SubtleCrypto API not available");
2645
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
2646
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
2647
+ return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
2648
+ }
2649
+
2650
+ // node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
2651
+ var SIXTY_SECONDS = 60000;
2652
+ var LONG_SCALE = 1152921504606847000;
2653
+ var NULL_VALUES_ALLOWED_OPERATORS = [
2654
+ "is_not"
2655
+ ];
2656
+
2657
+ class ClientError extends Error {
2658
+ constructor(message) {
2659
+ super();
2660
+ Error.captureStackTrace(this, this.constructor);
2661
+ this.name = "ClientError";
2662
+ this.message = message;
2663
+ Object.setPrototypeOf(this, ClientError.prototype);
2664
+ }
2665
+ }
2666
+
2667
+ class InconclusiveMatchError extends Error {
2668
+ constructor(message) {
2669
+ super(message);
2670
+ this.name = this.constructor.name;
2671
+ Error.captureStackTrace(this, this.constructor);
2672
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
2673
+ }
2674
+ }
2675
+
2676
+ class RequiresServerEvaluation extends Error {
2677
+ constructor(message) {
2678
+ super(message);
2679
+ this.name = this.constructor.name;
2680
+ Error.captureStackTrace(this, this.constructor);
2681
+ Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
2682
+ }
2683
+ }
2684
+
2685
+ class FeatureFlagsPoller {
2686
+ constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }) {
2687
+ this.debugMode = false;
2688
+ this.shouldBeginExponentialBackoff = false;
2689
+ this.backOffCount = 0;
2690
+ this.pollingInterval = pollingInterval;
2691
+ this.personalApiKey = personalApiKey;
2692
+ this.featureFlags = [];
2693
+ this.featureFlagsByKey = {};
2694
+ this.groupTypeMapping = {};
2695
+ this.cohorts = {};
2696
+ this.loadedSuccessfullyOnce = false;
2697
+ this.timeout = timeout;
2698
+ this.projectApiKey = projectApiKey;
2699
+ this.host = host;
2700
+ this.poller = undefined;
2701
+ this.fetch = options.fetch || fetch;
2702
+ this.onError = options.onError;
2703
+ this.customHeaders = customHeaders;
2704
+ this.onLoad = options.onLoad;
2705
+ this.cacheProvider = options.cacheProvider;
2706
+ this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
2707
+ this.loadFeatureFlags();
2708
+ }
2709
+ debug(enabled = true) {
2710
+ this.debugMode = enabled;
2711
+ }
2712
+ logMsgIfDebug(fn) {
2713
+ if (this.debugMode)
2714
+ fn();
2715
+ }
2716
+ createEvaluationContext(distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {
2717
+ return {
2718
+ distinctId,
2719
+ groups,
2720
+ personProperties,
2721
+ groupProperties,
2722
+ evaluationCache
2723
+ };
2724
+ }
2725
+ async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2726
+ await this.loadFeatureFlags();
2727
+ let response;
2728
+ let featureFlag;
2729
+ if (!this.loadedSuccessfullyOnce)
2730
+ return response;
2731
+ featureFlag = this.featureFlagsByKey[key];
2732
+ if (featureFlag !== undefined) {
2733
+ const evaluationContext = this.createEvaluationContext(distinctId, groups, personProperties, groupProperties);
2734
+ try {
2735
+ const result = await this.computeFlagAndPayloadLocally(featureFlag, evaluationContext);
2736
+ response = result.value;
2737
+ this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2738
+ } catch (e) {
2739
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError)
2740
+ this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));
2741
+ else if (e instanceof Error)
2742
+ this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2743
+ }
2744
+ }
2745
+ return response;
2746
+ }
2747
+ async getAllFlagsAndPayloads(evaluationContext, flagKeysToExplicitlyEvaluate) {
2748
+ await this.loadFeatureFlags();
2749
+ const response = {};
2750
+ const payloads = {};
2751
+ let fallbackToFlags = this.featureFlags.length == 0;
2752
+ const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key) => this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;
2753
+ const sharedEvaluationContext = {
2754
+ ...evaluationContext,
2755
+ evaluationCache: evaluationContext.evaluationCache ?? {}
2756
+ };
2757
+ await Promise.all(flagsToEvaluate.map(async (flag) => {
2758
+ try {
2759
+ const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext);
2760
+ response[flag.key] = matchValue;
2761
+ if (matchPayload)
2762
+ payloads[flag.key] = matchPayload;
2763
+ } catch (e) {
2764
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError)
2765
+ this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));
2766
+ else if (e instanceof Error)
2767
+ this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2768
+ fallbackToFlags = true;
2769
+ }
2770
+ }));
2771
+ return {
2772
+ response,
2773
+ payloads,
2774
+ fallbackToFlags
2775
+ };
2776
+ }
2777
+ async computeFlagAndPayloadLocally(flag, evaluationContext, options = {}) {
2778
+ const { matchValue, skipLoadCheck = false } = options;
2779
+ if (!skipLoadCheck)
2780
+ await this.loadFeatureFlags();
2781
+ if (!this.loadedSuccessfullyOnce)
2782
+ return {
2783
+ value: false,
2784
+ payload: null
2785
+ };
2786
+ let flagValue;
2787
+ flagValue = matchValue !== undefined ? matchValue : await this.computeFlagValueLocally(flag, evaluationContext);
2788
+ const payload = this.getFeatureFlagPayload(flag.key, flagValue);
2789
+ return {
2790
+ value: flagValue,
2791
+ payload
2792
+ };
2793
+ }
2794
+ async computeFlagValueLocally(flag, evaluationContext) {
2795
+ const { distinctId, groups, personProperties, groupProperties } = evaluationContext;
2796
+ if (flag.ensure_experience_continuity)
2797
+ throw new InconclusiveMatchError("Flag has experience continuity enabled");
2798
+ if (!flag.active)
2799
+ return false;
2800
+ const flagFilters = flag.filters || {};
2801
+ const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2802
+ if (aggregation_group_type_index != null) {
2803
+ const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2804
+ if (!groupName) {
2805
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2806
+ throw new InconclusiveMatchError("Flag has unknown group type index");
2807
+ }
2808
+ if (!(groupName in groups)) {
2809
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2810
+ return false;
2811
+ }
2812
+ if (flag.bucketing_identifier === "device_id" && (personProperties?.$device_id === undefined || personProperties?.$device_id === null || personProperties?.$device_id === ""))
2813
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${flag.key}`));
2814
+ const focusedGroupProperties = groupProperties[groupName];
2815
+ return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext);
2816
+ }
2817
+ {
2818
+ const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties);
2819
+ if (bucketingValue === undefined) {
2820
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${flag.key} without $device_id, falling back to server evaluation`));
2821
+ throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`);
2822
+ }
2823
+ return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext);
2824
+ }
2825
+ }
2826
+ getBucketingValueForFlag(flag, distinctId, properties) {
2827
+ if (flag.filters?.aggregation_group_type_index != null)
2828
+ return distinctId;
2829
+ if (flag.bucketing_identifier === "device_id") {
2830
+ const deviceId = properties?.$device_id;
2831
+ if (deviceId == null || deviceId === "")
2832
+ return;
2833
+ return deviceId;
2834
+ }
2835
+ return distinctId;
2836
+ }
2837
+ getFeatureFlagPayload(key, flagValue) {
2838
+ let payload = null;
2839
+ if (flagValue !== false && flagValue != null) {
2840
+ if (typeof flagValue == "boolean")
2841
+ payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
2842
+ else if (typeof flagValue == "string")
2843
+ payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
2844
+ if (payload != null) {
2845
+ if (typeof payload == "object")
2846
+ return payload;
2847
+ if (typeof payload == "string")
2848
+ try {
2849
+ return JSON.parse(payload);
2850
+ } catch {}
2851
+ return payload;
2852
+ }
2853
+ }
2854
+ return null;
2855
+ }
2856
+ async evaluateFlagDependency(property, properties, evaluationContext) {
2857
+ const { evaluationCache } = evaluationContext;
2858
+ const targetFlagKey = property.key;
2859
+ if (!this.featureFlagsByKey)
2860
+ throw new InconclusiveMatchError("Feature flags not available for dependency evaluation");
2861
+ if (!("dependency_chain" in property))
2862
+ throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);
2863
+ const dependencyChain = property.dependency_chain;
2864
+ if (!Array.isArray(dependencyChain))
2865
+ throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);
2866
+ if (dependencyChain.length === 0)
2867
+ throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);
2868
+ for (const depFlagKey of dependencyChain) {
2869
+ if (!(depFlagKey in evaluationCache)) {
2870
+ const depFlag = this.featureFlagsByKey[depFlagKey];
2871
+ if (depFlag)
2872
+ if (depFlag.active)
2873
+ try {
2874
+ const depResult = await this.computeFlagValueLocally(depFlag, evaluationContext);
2875
+ evaluationCache[depFlagKey] = depResult;
2876
+ } catch (error) {
2877
+ throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);
2878
+ }
2879
+ else
2880
+ evaluationCache[depFlagKey] = false;
2881
+ else
2882
+ throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
2883
+ }
2884
+ const cachedResult = evaluationCache[depFlagKey];
2885
+ if (cachedResult == null)
2886
+ throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);
2887
+ }
2888
+ const targetFlagValue = evaluationCache[targetFlagKey];
2889
+ return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);
2890
+ }
2891
+ flagEvaluatesToExpectedValue(expectedValue, flagValue) {
2892
+ if (typeof expectedValue == "boolean")
2893
+ return expectedValue === flagValue || typeof flagValue == "string" && flagValue !== "" && expectedValue === true;
2894
+ if (typeof expectedValue == "string")
2895
+ return flagValue === expectedValue;
2896
+ return false;
2897
+ }
2898
+ async matchFeatureFlagProperties(flag, bucketingValue, properties, evaluationContext) {
2899
+ const flagFilters = flag.filters || {};
2900
+ const flagConditions = flagFilters.groups || [];
2901
+ let isInconclusive = false;
2902
+ let result;
2903
+ for (const condition of flagConditions)
2904
+ try {
2905
+ if (await this.isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext)) {
2906
+ const variantOverride = condition.variant;
2907
+ const flagVariants = flagFilters.multivariate?.variants || [];
2908
+ result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, bucketingValue) || true;
2909
+ break;
2910
+ }
2911
+ } catch (e) {
2912
+ if (e instanceof RequiresServerEvaluation)
2913
+ throw e;
2914
+ if (e instanceof InconclusiveMatchError)
2915
+ isInconclusive = true;
2916
+ else
2917
+ throw e;
2918
+ }
2919
+ if (result !== undefined)
2920
+ return result;
2921
+ if (isInconclusive)
2922
+ throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
2923
+ return false;
2924
+ }
2925
+ async isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext) {
2926
+ const rolloutPercentage = condition.rollout_percentage;
2927
+ const warnFunction = (msg) => {
2928
+ this.logMsgIfDebug(() => console.warn(msg));
2929
+ };
2930
+ if ((condition.properties || []).length > 0) {
2931
+ for (const prop of condition.properties) {
2932
+ const propertyType = prop.type;
2933
+ let matches = false;
2934
+ matches = propertyType === "cohort" ? matchCohort(prop, properties, this.cohorts, this.debugMode) : propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
2935
+ if (!matches)
2936
+ return false;
2937
+ }
2938
+ if (rolloutPercentage == undefined)
2939
+ return true;
2940
+ }
2941
+ if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
2942
+ return false;
2943
+ return true;
2944
+ }
2945
+ async getMatchingVariant(flag, bucketingValue) {
2946
+ const hashValue = await _hash(flag.key, bucketingValue, "variant");
2947
+ const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
2948
+ if (matchingVariant)
2949
+ return matchingVariant.key;
2950
+ }
2951
+ variantLookupTable(flag) {
2952
+ const lookupTable = [];
2953
+ let valueMin = 0;
2954
+ let valueMax = 0;
2955
+ const flagFilters = flag.filters || {};
2956
+ const multivariates = flagFilters.multivariate?.variants || [];
2957
+ multivariates.forEach((variant) => {
2958
+ valueMax = valueMin + variant.rollout_percentage / 100;
2959
+ lookupTable.push({
2960
+ valueMin,
2961
+ valueMax,
2962
+ key: variant.key
2963
+ });
2964
+ valueMin = valueMax;
2965
+ });
2966
+ return lookupTable;
2967
+ }
2968
+ updateFlagState(flagData) {
2969
+ this.featureFlags = flagData.flags;
2970
+ this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
2971
+ this.groupTypeMapping = flagData.groupTypeMapping;
2972
+ this.cohorts = flagData.cohorts;
2973
+ this.loadedSuccessfullyOnce = true;
2974
+ }
2975
+ warnAboutExperienceContinuityFlags(flags) {
2976
+ if (this.strictLocalEvaluation)
2977
+ return;
2978
+ const experienceContinuityFlags = flags.filter((f) => f.ensure_experience_continuity);
2979
+ if (experienceContinuityFlags.length > 0)
2980
+ console.warn(`[PostHog] You are using local evaluation but ${experienceContinuityFlags.length} flag(s) have experience continuity enabled: ${experienceContinuityFlags.map((f) => f.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`);
2981
+ }
2982
+ async loadFromCache(debugMessage) {
2983
+ if (!this.cacheProvider)
2984
+ return false;
2985
+ try {
2986
+ const cached = await this.cacheProvider.getFlagDefinitions();
2987
+ if (cached) {
2988
+ this.updateFlagState(cached);
2989
+ this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
2990
+ this.onLoad?.(this.featureFlags.length);
2991
+ this.warnAboutExperienceContinuityFlags(cached.flags);
2992
+ return true;
2993
+ }
2994
+ return false;
2995
+ } catch (err) {
2996
+ this.onError?.(new Error(`Failed to load from cache: ${err}`));
2997
+ return false;
2998
+ }
2999
+ }
3000
+ async loadFeatureFlags(forceReload = false) {
3001
+ if (this.loadedSuccessfullyOnce && !forceReload)
3002
+ return;
3003
+ if (!forceReload && this.nextFetchAllowedAt && Date.now() < this.nextFetchAllowedAt)
3004
+ return void this.logMsgIfDebug(() => console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));
3005
+ if (!this.loadingPromise)
3006
+ this.loadingPromise = this._loadFeatureFlags().catch((err) => this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(() => {
3007
+ this.loadingPromise = undefined;
3008
+ });
3009
+ return this.loadingPromise;
3010
+ }
3011
+ isLocalEvaluationReady() {
3012
+ return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
3013
+ }
3014
+ getPollingInterval() {
3015
+ if (!this.shouldBeginExponentialBackoff)
3016
+ return this.pollingInterval;
3017
+ return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
3018
+ }
3019
+ beginBackoff() {
3020
+ this.shouldBeginExponentialBackoff = true;
3021
+ this.backOffCount += 1;
3022
+ this.nextFetchAllowedAt = Date.now() + this.getPollingInterval();
3023
+ }
3024
+ clearBackoff() {
3025
+ this.shouldBeginExponentialBackoff = false;
3026
+ this.backOffCount = 0;
3027
+ this.nextFetchAllowedAt = undefined;
3028
+ }
3029
+ async _loadFeatureFlags() {
3030
+ if (this.poller) {
3031
+ clearTimeout(this.poller);
3032
+ this.poller = undefined;
3033
+ }
3034
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3035
+ try {
3036
+ let shouldFetch = true;
3037
+ if (this.cacheProvider)
3038
+ try {
3039
+ shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();
3040
+ } catch (err) {
3041
+ this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));
3042
+ }
3043
+ if (!shouldFetch) {
3044
+ const loaded = await this.loadFromCache("Loaded flags from cache (skipped fetch)");
3045
+ if (loaded)
3046
+ return;
3047
+ if (this.loadedSuccessfullyOnce)
3048
+ return;
3049
+ }
3050
+ const res = await this._requestFeatureFlagDefinitions();
3051
+ if (!res)
3052
+ return;
3053
+ switch (res.status) {
3054
+ case 304:
3055
+ this.logMsgIfDebug(() => console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data"));
3056
+ this.flagsEtag = res.headers?.get("ETag") ?? this.flagsEtag;
3057
+ this.loadedSuccessfullyOnce = true;
3058
+ this.clearBackoff();
3059
+ return;
3060
+ case 401:
3061
+ this.beginBackoff();
3062
+ 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`);
3063
+ case 402:
3064
+ 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");
3065
+ this.featureFlags = [];
3066
+ this.featureFlagsByKey = {};
3067
+ this.groupTypeMapping = {};
3068
+ this.cohorts = {};
3069
+ return;
3070
+ case 403:
3071
+ this.beginBackoff();
3072
+ 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`);
3073
+ case 429:
3074
+ this.beginBackoff();
3075
+ 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`);
3076
+ case 200: {
3077
+ const responseJson = await res.json() ?? {};
3078
+ if (!("flags" in responseJson))
3079
+ return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
3080
+ this.flagsEtag = res.headers?.get("ETag") ?? undefined;
3081
+ const flagData = {
3082
+ flags: responseJson.flags ?? [],
3083
+ groupTypeMapping: responseJson.group_type_mapping || {},
3084
+ cohorts: responseJson.cohorts || {}
3085
+ };
3086
+ this.updateFlagState(flagData);
3087
+ this.clearBackoff();
3088
+ if (this.cacheProvider && shouldFetch)
3089
+ try {
3090
+ await this.cacheProvider.onFlagDefinitionsReceived(flagData);
3091
+ } catch (err) {
3092
+ this.onError?.(new Error(`Failed to store in cache: ${err}`));
3093
+ }
3094
+ this.onLoad?.(this.featureFlags.length);
3095
+ this.warnAboutExperienceContinuityFlags(flagData.flags);
3096
+ break;
3097
+ }
3098
+ default:
3099
+ return;
3100
+ }
3101
+ } catch (err) {
3102
+ if (err instanceof ClientError)
3103
+ this.onError?.(err);
3104
+ }
3105
+ }
3106
+ getPersonalApiKeyRequestOptions(method = "GET", etag) {
3107
+ const headers = {
3108
+ ...this.customHeaders,
3109
+ "Content-Type": "application/json",
3110
+ Authorization: `Bearer ${this.personalApiKey}`
3111
+ };
3112
+ if (etag)
3113
+ headers["If-None-Match"] = etag;
3114
+ return {
3115
+ method,
3116
+ headers
3117
+ };
3118
+ }
3119
+ _requestFeatureFlagDefinitions() {
3120
+ const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
3121
+ const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
3122
+ let abortTimeout = null;
3123
+ if (this.timeout && typeof this.timeout == "number") {
3124
+ const controller = new AbortController;
3125
+ abortTimeout = safeSetTimeout(() => {
3126
+ controller.abort();
3127
+ }, this.timeout);
3128
+ options.signal = controller.signal;
3129
+ }
3130
+ try {
3131
+ const fetch1 = this.fetch;
3132
+ return fetch1(url, options);
3133
+ } finally {
3134
+ clearTimeout(abortTimeout);
3135
+ }
3136
+ }
3137
+ async stopPoller(timeoutMs = 30000) {
3138
+ clearTimeout(this.poller);
3139
+ if (this.cacheProvider)
3140
+ try {
3141
+ const shutdownResult = this.cacheProvider.shutdown();
3142
+ if (shutdownResult instanceof Promise)
3143
+ await Promise.race([
3144
+ shutdownResult,
3145
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
3146
+ ]);
3147
+ } catch (err) {
3148
+ this.onError?.(new Error(`Error during cache shutdown: ${err}`));
3149
+ }
3150
+ }
3151
+ }
3152
+ async function _hash(key, bucketingValue, salt = "") {
3153
+ const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);
3154
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
3155
+ }
3156
+ function matchProperty(property, propertyValues, warnFunction) {
3157
+ const key = property.key;
3158
+ const value = property.value;
3159
+ const operator = property.operator || "exact";
3160
+ if (key in propertyValues) {
3161
+ if (operator === "is_not_set")
3162
+ throw new InconclusiveMatchError("Operator is_not_set is not supported");
3163
+ } else
3164
+ throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
3165
+ const overrideValue = propertyValues[key];
3166
+ if (overrideValue == null && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
3167
+ if (warnFunction)
3168
+ warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
3169
+ return false;
3170
+ }
3171
+ function computeExactMatch(value2, overrideValue2) {
3172
+ if (Array.isArray(value2))
3173
+ return value2.map((val) => String(val).toLowerCase()).includes(String(overrideValue2).toLowerCase());
3174
+ return String(value2).toLowerCase() === String(overrideValue2).toLowerCase();
3175
+ }
3176
+ function compare(lhs, rhs, operator2) {
3177
+ if (operator2 === "gt")
3178
+ return lhs > rhs;
3179
+ if (operator2 === "gte")
3180
+ return lhs >= rhs;
3181
+ if (operator2 === "lt")
3182
+ return lhs < rhs;
3183
+ if (operator2 === "lte")
3184
+ return lhs <= rhs;
3185
+ throw new Error(`Invalid operator: ${operator2}`);
3186
+ }
3187
+ switch (operator) {
3188
+ case "exact":
3189
+ return computeExactMatch(value, overrideValue);
3190
+ case "is_not":
3191
+ return !computeExactMatch(value, overrideValue);
3192
+ case "is_set":
3193
+ return key in propertyValues;
3194
+ case "icontains":
3195
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3196
+ case "not_icontains":
3197
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3198
+ case "regex":
3199
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
3200
+ case "not_regex":
3201
+ return isValidRegex(String(value)) && String(overrideValue).match(String(value)) === null;
3202
+ case "gt":
3203
+ case "gte":
3204
+ case "lt":
3205
+ case "lte": {
3206
+ let parsedValue = typeof value == "number" ? value : null;
3207
+ if (typeof value == "string")
3208
+ try {
3209
+ parsedValue = parseFloat(value);
3210
+ } catch (err) {}
3211
+ if (parsedValue == null || overrideValue == null)
3212
+ return compare(String(overrideValue), String(value), operator);
3213
+ if (typeof overrideValue == "string")
3214
+ return compare(overrideValue, String(value), operator);
3215
+ return compare(overrideValue, parsedValue, operator);
3216
+ }
3217
+ case "is_date_after":
3218
+ case "is_date_before": {
3219
+ if (typeof value == "boolean")
3220
+ throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
3221
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
3222
+ if (parsedDate == null)
3223
+ parsedDate = convertToDateTime(value);
3224
+ if (parsedDate == null)
3225
+ throw new InconclusiveMatchError(`Invalid date: ${value}`);
3226
+ const overrideDate = convertToDateTime(overrideValue);
3227
+ if ([
3228
+ "is_date_before"
3229
+ ].includes(operator))
3230
+ return overrideDate < parsedDate;
3231
+ return overrideDate > parsedDate;
3232
+ }
3233
+ default:
3234
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
3235
+ }
3236
+ }
3237
+ function checkCohortExists(cohortId, cohortProperties) {
3238
+ if (!(cohortId in cohortProperties))
3239
+ throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);
3240
+ }
3241
+ function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
3242
+ const cohortId = String(property.value);
3243
+ checkCohortExists(cohortId, cohortProperties);
3244
+ const propertyGroup = cohortProperties[cohortId];
3245
+ return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
3246
+ }
3247
+ function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
3248
+ if (!propertyGroup)
3249
+ return true;
3250
+ const propertyGroupType = propertyGroup.type;
3251
+ const properties = propertyGroup.values;
3252
+ if (!properties || properties.length === 0)
3253
+ return true;
3254
+ let errorMatchingLocally = false;
3255
+ if ("values" in properties[0]) {
3256
+ for (const prop of properties)
3257
+ try {
3258
+ const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
3259
+ if (propertyGroupType === "AND") {
3260
+ if (!matches)
3261
+ return false;
3262
+ } else if (matches)
3263
+ return true;
3264
+ } catch (err) {
3265
+ if (err instanceof RequiresServerEvaluation)
3266
+ throw err;
3267
+ if (err instanceof InconclusiveMatchError) {
3268
+ if (debugMode)
3269
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
3270
+ errorMatchingLocally = true;
3271
+ } else
3272
+ throw err;
3273
+ }
3274
+ if (errorMatchingLocally)
3275
+ throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
3276
+ return propertyGroupType === "AND";
3277
+ }
3278
+ for (const prop of properties)
3279
+ try {
3280
+ let matches;
3281
+ if (prop.type === "cohort")
3282
+ matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
3283
+ else if (prop.type === "flag") {
3284
+ if (debugMode)
3285
+ console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${prop.key || "unknown"}'`);
3286
+ continue;
3287
+ } else
3288
+ matches = matchProperty(prop, propertyValues);
3289
+ const negation = prop.negation || false;
3290
+ if (propertyGroupType === "AND") {
3291
+ if (!matches && !negation)
3292
+ return false;
3293
+ if (matches && negation)
3294
+ return false;
3295
+ } else {
3296
+ if (matches && !negation)
3297
+ return true;
3298
+ if (!matches && negation)
3299
+ return true;
3300
+ }
3301
+ } catch (err) {
3302
+ if (err instanceof RequiresServerEvaluation)
3303
+ throw err;
3304
+ if (err instanceof InconclusiveMatchError) {
3305
+ if (debugMode)
3306
+ console.debug(`Failed to compute property ${prop} locally: ${err}`);
3307
+ errorMatchingLocally = true;
3308
+ } else
3309
+ throw err;
3310
+ }
3311
+ if (errorMatchingLocally)
3312
+ throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
3313
+ return propertyGroupType === "AND";
3314
+ }
3315
+ function isValidRegex(regex) {
3316
+ try {
3317
+ new RegExp(regex);
3318
+ return true;
3319
+ } catch (err) {
3320
+ return false;
3321
+ }
3322
+ }
3323
+ function convertToDateTime(value) {
3324
+ if (value instanceof Date)
3325
+ return value;
3326
+ if (typeof value == "string" || typeof value == "number") {
3327
+ const date = new Date(value);
3328
+ if (!isNaN(date.valueOf()))
3329
+ return date;
3330
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
3331
+ }
3332
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
3333
+ }
3334
+ function relativeDateParseForFeatureFlagMatching(value) {
3335
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
3336
+ const match = value.match(regex);
3337
+ const parsedDt = new Date(new Date().toISOString());
3338
+ if (!match)
3339
+ return null;
3340
+ {
3341
+ if (!match.groups)
3342
+ return null;
3343
+ const number = parseInt(match.groups["number"]);
3344
+ if (number >= 1e4)
3345
+ return null;
3346
+ const interval = match.groups["interval"];
3347
+ if (interval == "h")
3348
+ parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
3349
+ else if (interval == "d")
3350
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
3351
+ else if (interval == "w")
3352
+ parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
3353
+ else if (interval == "m")
3354
+ parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
3355
+ else {
3356
+ if (interval != "y")
3357
+ return null;
3358
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
3359
+ }
3360
+ return parsedDt;
3361
+ }
3362
+ }
3363
+
3364
+ // node_modules/posthog-node/dist/storage-memory.mjs
3365
+ class PostHogMemoryStorage {
3366
+ getProperty(key) {
3367
+ return this._memoryStorage[key];
3368
+ }
3369
+ setProperty(key, value) {
3370
+ this._memoryStorage[key] = value !== null ? value : undefined;
3371
+ }
3372
+ constructor() {
3373
+ this._memoryStorage = {};
3374
+ }
3375
+ }
3376
+
3377
+ // node_modules/posthog-node/dist/client.mjs
3378
+ var MINIMUM_POLLING_INTERVAL = 100;
3379
+ var THIRTY_SECONDS = 30000;
3380
+ var MAX_CACHE_SIZE = 50000;
3381
+
3382
+ class PostHogBackendClient extends PostHogCoreStateless {
3383
+ constructor(apiKey, options = {}) {
3384
+ super(apiKey, options), this._memoryStorage = new PostHogMemoryStorage;
3385
+ this.options = options;
3386
+ this.context = this.initializeContext();
3387
+ this.options.featureFlagsPollingInterval = typeof options.featureFlagsPollingInterval == "number" ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
3388
+ if (options.personalApiKey) {
3389
+ if (options.personalApiKey.includes("phc_"))
3390
+ throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
3391
+ const shouldEnableLocalEvaluation = options.enableLocalEvaluation !== false;
3392
+ if (shouldEnableLocalEvaluation)
3393
+ this.featureFlagsPoller = new FeatureFlagsPoller({
3394
+ pollingInterval: this.options.featureFlagsPollingInterval,
3395
+ personalApiKey: options.personalApiKey,
3396
+ projectApiKey: apiKey,
3397
+ timeout: options.requestTimeout ?? 1e4,
3398
+ host: this.host,
3399
+ fetch: options.fetch,
3400
+ onError: (err) => {
3401
+ this._events.emit("error", err);
3402
+ },
3403
+ onLoad: (count) => {
3404
+ this._events.emit("localEvaluationFlagsLoaded", count);
3405
+ },
3406
+ customHeaders: this.getCustomHeaders(),
3407
+ cacheProvider: options.flagDefinitionCacheProvider,
3408
+ strictLocalEvaluation: options.strictLocalEvaluation
3409
+ });
3410
+ }
3411
+ this.errorTracking = new ErrorTracking(this, options, this._logger);
3412
+ this.distinctIdHasSentFlagCalls = {};
3413
+ this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
3414
+ }
3415
+ getPersistedProperty(key) {
3416
+ return this._memoryStorage.getProperty(key);
3417
+ }
3418
+ setPersistedProperty(key, value) {
3419
+ return this._memoryStorage.setProperty(key, value);
3420
+ }
3421
+ fetch(url, options) {
3422
+ return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
3423
+ }
3424
+ getLibraryVersion() {
3425
+ return version;
3426
+ }
3427
+ getCustomUserAgent() {
3428
+ return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
3429
+ }
3430
+ enable() {
3431
+ return super.optIn();
3432
+ }
3433
+ disable() {
3434
+ return super.optOut();
3435
+ }
3436
+ debug(enabled = true) {
3437
+ super.debug(enabled);
3438
+ this.featureFlagsPoller?.debug(enabled);
3439
+ }
3440
+ capture(props) {
3441
+ if (typeof props == "string")
3442
+ this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
3443
+ if (props.event === "$exception" && !props._originatedFromCaptureException)
3444
+ this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");
3445
+ this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
3446
+ timestamp: options.timestamp,
3447
+ disableGeoip: options.disableGeoip,
3448
+ uuid: options.uuid
3449
+ })).catch((err) => {
3450
+ if (err)
3451
+ console.error(err);
3452
+ }));
3453
+ }
3454
+ async captureImmediate(props) {
3455
+ if (typeof props == "string")
3456
+ this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
3457
+ if (props.event === "$exception" && !props._originatedFromCaptureException)
3458
+ this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");
3459
+ return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
3460
+ timestamp: options.timestamp,
3461
+ disableGeoip: options.disableGeoip,
3462
+ uuid: options.uuid
3463
+ })).catch((err) => {
3464
+ if (err)
3465
+ console.error(err);
3466
+ }));
3467
+ }
3468
+ identify({ distinctId, properties = {}, disableGeoip }) {
3469
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
3470
+ const setProps = $set || rest;
3471
+ const setOnceProps = $set_once || {};
3472
+ const eventProperties = {
3473
+ $set: setProps,
3474
+ $set_once: setOnceProps,
3475
+ $anon_distinct_id: $anon_distinct_id ?? undefined
3476
+ };
3477
+ super.identifyStateless(distinctId, eventProperties, {
3478
+ disableGeoip
3479
+ });
3480
+ }
3481
+ async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
3482
+ const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
3483
+ const setProps = $set || rest;
3484
+ const setOnceProps = $set_once || {};
3485
+ const eventProperties = {
3486
+ $set: setProps,
3487
+ $set_once: setOnceProps,
3488
+ $anon_distinct_id: $anon_distinct_id ?? undefined
3489
+ };
3490
+ super.identifyStatelessImmediate(distinctId, eventProperties, {
3491
+ disableGeoip
3492
+ });
3493
+ }
3494
+ alias(data) {
3495
+ super.aliasStateless(data.alias, data.distinctId, undefined, {
3496
+ disableGeoip: data.disableGeoip
3497
+ });
3498
+ }
3499
+ async aliasImmediate(data) {
3500
+ await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
3501
+ disableGeoip: data.disableGeoip
3502
+ });
3503
+ }
3504
+ isLocalEvaluationReady() {
3505
+ return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
3506
+ }
3507
+ async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
3508
+ if (this.isLocalEvaluationReady())
3509
+ return true;
3510
+ if (this.featureFlagsPoller === undefined)
3511
+ return false;
3512
+ return new Promise((resolve) => {
3513
+ const timeout = setTimeout(() => {
3514
+ cleanup();
3515
+ resolve(false);
3516
+ }, timeoutMs);
3517
+ const cleanup = this._events.on("localEvaluationFlagsLoaded", (count) => {
3518
+ clearTimeout(timeout);
3519
+ cleanup();
3520
+ resolve(count > 0);
3521
+ });
3522
+ });
3523
+ }
3524
+ _resolveDistinctId(distinctIdOrOptions, options) {
3525
+ if (typeof distinctIdOrOptions == "string")
3526
+ return {
3527
+ distinctId: distinctIdOrOptions,
3528
+ options
3529
+ };
3530
+ return {
3531
+ distinctId: this.context?.get()?.distinctId,
3532
+ options: distinctIdOrOptions
3533
+ };
3534
+ }
3535
+ async _getFeatureFlagResult(key, distinctId, options = {}, matchValue) {
3536
+ const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true;
3537
+ if (this._flagOverrides !== undefined && key in this._flagOverrides) {
3538
+ const overrideValue = this._flagOverrides[key];
3539
+ if (overrideValue === undefined)
3540
+ return;
3541
+ const overridePayload = this._payloadOverrides?.[key];
3542
+ return {
3543
+ key,
3544
+ enabled: overrideValue !== false,
3545
+ variant: typeof overrideValue == "string" ? overrideValue : undefined,
3546
+ payload: overridePayload
3547
+ };
3548
+ }
3549
+ const { groups, disableGeoip } = options;
3550
+ let { onlyEvaluateLocally, personProperties, groupProperties } = options;
3551
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
3552
+ personProperties = adjustedProperties.allPersonProperties;
3553
+ groupProperties = adjustedProperties.allGroupProperties;
3554
+ const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties);
3555
+ if (onlyEvaluateLocally == undefined)
3556
+ onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
3557
+ let result;
3558
+ let flagWasLocallyEvaluated = false;
3559
+ let requestId;
3560
+ let evaluatedAt;
3561
+ let featureFlagError;
3562
+ let flagId;
3563
+ let flagVersion;
3564
+ let flagReason;
3565
+ const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
3566
+ if (localEvaluationEnabled) {
3567
+ await this.featureFlagsPoller?.loadFeatureFlags();
3568
+ const flag = this.featureFlagsPoller?.featureFlagsByKey[key];
3569
+ if (flag)
3570
+ try {
3571
+ const localResult = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, evaluationContext, {
3572
+ matchValue
3573
+ });
3574
+ if (localResult) {
3575
+ flagWasLocallyEvaluated = true;
3576
+ const value = localResult.value;
3577
+ flagId = flag.id;
3578
+ flagReason = "Evaluated locally";
3579
+ result = {
3580
+ key,
3581
+ enabled: value !== false,
3582
+ variant: typeof value == "string" ? value : undefined,
3583
+ payload: localResult.payload ?? undefined
3584
+ };
3585
+ }
3586
+ } catch (e) {
3587
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError)
3588
+ this._logger?.info(`${e.name} when computing flag locally: ${key}: ${e.message}`);
3589
+ else
3590
+ throw e;
3591
+ }
3592
+ }
3593
+ if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
3594
+ const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, [
3595
+ key
3596
+ ]);
3597
+ if (flagsResponse === undefined)
3598
+ featureFlagError = FeatureFlagError2.UNKNOWN_ERROR;
3599
+ else {
3600
+ requestId = flagsResponse.requestId;
3601
+ evaluatedAt = flagsResponse.evaluatedAt;
3602
+ const errors = [];
3603
+ if (flagsResponse.errorsWhileComputingFlags)
3604
+ errors.push(FeatureFlagError2.ERRORS_WHILE_COMPUTING);
3605
+ if (flagsResponse.quotaLimited?.includes("feature_flags"))
3606
+ errors.push(FeatureFlagError2.QUOTA_LIMITED);
3607
+ const flagDetail = flagsResponse.flags[key];
3608
+ if (flagDetail === undefined)
3609
+ errors.push(FeatureFlagError2.FLAG_MISSING);
3610
+ else {
3611
+ flagId = flagDetail.metadata?.id;
3612
+ flagVersion = flagDetail.metadata?.version;
3613
+ flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
3614
+ let parsedPayload;
3615
+ if (flagDetail.metadata?.payload !== undefined)
3616
+ try {
3617
+ parsedPayload = JSON.parse(flagDetail.metadata.payload);
3618
+ } catch {
3619
+ parsedPayload = flagDetail.metadata.payload;
3620
+ }
3621
+ result = {
3622
+ key,
3623
+ enabled: flagDetail.enabled,
3624
+ variant: flagDetail.variant,
3625
+ payload: parsedPayload
3626
+ };
3627
+ }
3628
+ if (errors.length > 0)
3629
+ featureFlagError = errors.join(",");
3630
+ }
3631
+ }
3632
+ if (sendFeatureFlagEvents) {
3633
+ const response = result === undefined ? undefined : result.enabled === false ? false : result.variant ?? true;
3634
+ const featureFlagReportedKey = `${key}_${response}`;
3635
+ if (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey)) {
3636
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize)
3637
+ this.distinctIdHasSentFlagCalls = {};
3638
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId]))
3639
+ this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
3640
+ else
3641
+ this.distinctIdHasSentFlagCalls[distinctId] = [
3642
+ featureFlagReportedKey
3643
+ ];
3644
+ const properties = {
3645
+ $feature_flag: key,
3646
+ $feature_flag_response: response,
3647
+ $feature_flag_id: flagId,
3648
+ $feature_flag_version: flagVersion,
3649
+ $feature_flag_reason: flagReason,
3650
+ locally_evaluated: flagWasLocallyEvaluated,
3651
+ [`$feature/${key}`]: response,
3652
+ $feature_flag_request_id: requestId,
3653
+ $feature_flag_evaluated_at: evaluatedAt
3654
+ };
3655
+ if (featureFlagError)
3656
+ properties.$feature_flag_error = featureFlagError;
3657
+ this.capture({
3658
+ distinctId,
3659
+ event: "$feature_flag_called",
3660
+ properties,
3661
+ groups,
3662
+ disableGeoip
3663
+ });
3664
+ }
3665
+ }
3666
+ if (result !== undefined && this._payloadOverrides !== undefined && key in this._payloadOverrides)
3667
+ result = {
3668
+ ...result,
3669
+ payload: this._payloadOverrides[key]
3670
+ };
3671
+ return result;
3672
+ }
3673
+ async getFeatureFlag(key, distinctId, options) {
3674
+ const result = await this._getFeatureFlagResult(key, distinctId, {
3675
+ ...options,
3676
+ sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true
3677
+ });
3678
+ if (result === undefined)
3679
+ return;
3680
+ if (result.enabled === false)
3681
+ return false;
3682
+ return result.variant ?? true;
3683
+ }
3684
+ async getFeatureFlagPayload(key, distinctId, matchValue, options) {
3685
+ if (this._payloadOverrides !== undefined && key in this._payloadOverrides)
3686
+ return this._payloadOverrides[key];
3687
+ const result = await this._getFeatureFlagResult(key, distinctId, {
3688
+ ...options,
3689
+ sendFeatureFlagEvents: false
3690
+ }, matchValue);
3691
+ if (result === undefined)
3692
+ return;
3693
+ return result.payload ?? null;
3694
+ }
3695
+ async getFeatureFlagResult(key, distinctIdOrOptions, options) {
3696
+ const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);
3697
+ if (!resolvedDistinctId)
3698
+ return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");
3699
+ return this._getFeatureFlagResult(key, resolvedDistinctId, {
3700
+ ...resolvedOptions,
3701
+ sendFeatureFlagEvents: resolvedOptions?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true
3702
+ });
3703
+ }
3704
+ async getRemoteConfigPayload(flagKey) {
3705
+ if (!this.options.personalApiKey)
3706
+ throw new Error("Personal API key is required for remote config payload decryption");
3707
+ const response = await this._requestRemoteConfigPayload(flagKey);
3708
+ if (!response)
3709
+ return;
3710
+ const parsed = await response.json();
3711
+ if (typeof parsed == "string")
3712
+ try {
3713
+ return JSON.parse(parsed);
3714
+ } catch (e) {}
3715
+ return parsed;
3716
+ }
3717
+ async isFeatureEnabled(key, distinctId, options) {
3718
+ const feat = await this.getFeatureFlag(key, distinctId, options);
3719
+ if (feat === undefined)
3720
+ return;
3721
+ return !!feat || false;
3722
+ }
3723
+ async getAllFlags(distinctIdOrOptions, options) {
3724
+ const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);
3725
+ if (!resolvedDistinctId) {
3726
+ this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()");
3727
+ return {};
3728
+ }
3729
+ const response = await this.getAllFlagsAndPayloads(resolvedDistinctId, resolvedOptions);
3730
+ return response.featureFlags || {};
3731
+ }
3732
+ async getAllFlagsAndPayloads(distinctIdOrOptions, options) {
3733
+ const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);
3734
+ if (!resolvedDistinctId) {
3735
+ this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()");
3736
+ return {
3737
+ featureFlags: {},
3738
+ featureFlagPayloads: {}
3739
+ };
3740
+ }
3741
+ const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
3742
+ let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
3743
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
3744
+ personProperties = adjustedProperties.allPersonProperties;
3745
+ groupProperties = adjustedProperties.allGroupProperties;
3746
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
3747
+ if (onlyEvaluateLocally == undefined)
3748
+ onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
3749
+ const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
3750
+ let featureFlags = {};
3751
+ let featureFlagPayloads = {};
3752
+ let fallbackToFlags = true;
3753
+ if (localEvaluationResult) {
3754
+ featureFlags = localEvaluationResult.response;
3755
+ featureFlagPayloads = localEvaluationResult.payloads;
3756
+ fallbackToFlags = localEvaluationResult.fallbackToFlags;
3757
+ }
3758
+ if (fallbackToFlags && !onlyEvaluateLocally) {
3759
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
3760
+ featureFlags = {
3761
+ ...featureFlags,
3762
+ ...remoteEvaluationResult.flags || {}
3763
+ };
3764
+ featureFlagPayloads = {
3765
+ ...featureFlagPayloads,
3766
+ ...remoteEvaluationResult.payloads || {}
3767
+ };
3768
+ }
3769
+ if (this._flagOverrides !== undefined)
3770
+ featureFlags = {
3771
+ ...featureFlags,
3772
+ ...this._flagOverrides
3773
+ };
3774
+ if (this._payloadOverrides !== undefined)
3775
+ featureFlagPayloads = {
3776
+ ...featureFlagPayloads,
3777
+ ...this._payloadOverrides
3778
+ };
3779
+ return {
3780
+ featureFlags,
3781
+ featureFlagPayloads
3782
+ };
3783
+ }
3784
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
3785
+ super.groupIdentifyStateless(groupType, groupKey, properties, {
3786
+ disableGeoip
3787
+ }, distinctId);
3788
+ }
3789
+ async reloadFeatureFlags() {
3790
+ await this.featureFlagsPoller?.loadFeatureFlags(true);
3791
+ }
3792
+ overrideFeatureFlags(overrides) {
3793
+ const flagArrayToRecord = (flags) => Object.fromEntries(flags.map((f) => [
3794
+ f,
3795
+ true
3796
+ ]));
3797
+ if (overrides === false) {
3798
+ this._flagOverrides = undefined;
3799
+ this._payloadOverrides = undefined;
3800
+ return;
3801
+ }
3802
+ if (Array.isArray(overrides)) {
3803
+ this._flagOverrides = flagArrayToRecord(overrides);
3804
+ return;
3805
+ }
3806
+ if (this._isFeatureFlagOverrideOptions(overrides)) {
3807
+ if ("flags" in overrides) {
3808
+ if (overrides.flags === false)
3809
+ this._flagOverrides = undefined;
3810
+ else if (Array.isArray(overrides.flags))
3811
+ this._flagOverrides = flagArrayToRecord(overrides.flags);
3812
+ else if (overrides.flags !== undefined)
3813
+ this._flagOverrides = {
3814
+ ...overrides.flags
3815
+ };
3816
+ }
3817
+ if ("payloads" in overrides) {
3818
+ if (overrides.payloads === false)
3819
+ this._payloadOverrides = undefined;
3820
+ else if (overrides.payloads !== undefined)
3821
+ this._payloadOverrides = {
3822
+ ...overrides.payloads
3823
+ };
3824
+ }
3825
+ return;
3826
+ }
3827
+ this._flagOverrides = {
3828
+ ...overrides
3829
+ };
3830
+ }
3831
+ _isFeatureFlagOverrideOptions(overrides) {
3832
+ if (typeof overrides != "object" || overrides === null || Array.isArray(overrides))
3833
+ return false;
3834
+ const obj = overrides;
3835
+ if ("flags" in obj) {
3836
+ const flagsValue = obj["flags"];
3837
+ if (flagsValue === false || Array.isArray(flagsValue) || typeof flagsValue == "object" && flagsValue !== null)
3838
+ return true;
3839
+ }
3840
+ if ("payloads" in obj) {
3841
+ const payloadsValue = obj["payloads"];
3842
+ if (payloadsValue === false || typeof payloadsValue == "object" && payloadsValue !== null)
3843
+ return true;
3844
+ }
3845
+ return false;
3846
+ }
3847
+ withContext(data, fn, options) {
3848
+ if (!this.context)
3849
+ return fn();
3850
+ return this.context.run(data, fn, options);
3851
+ }
3852
+ getContext() {
3853
+ return this.context?.get();
3854
+ }
3855
+ enterContext(data, options) {
3856
+ this.context?.enter(data, options);
3857
+ }
3858
+ async _shutdown(shutdownTimeoutMs) {
3859
+ this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
3860
+ this.errorTracking.shutdown();
3861
+ return super._shutdown(shutdownTimeoutMs);
3862
+ }
3863
+ async _requestRemoteConfigPayload(flagKey) {
3864
+ if (!this.options.personalApiKey)
3865
+ return;
3866
+ const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
3867
+ const options = {
3868
+ method: "GET",
3869
+ headers: {
3870
+ ...this.getCustomHeaders(),
3871
+ "Content-Type": "application/json",
3872
+ Authorization: `Bearer ${this.options.personalApiKey}`
3873
+ }
3874
+ };
3875
+ let abortTimeout = null;
3876
+ if (this.options.requestTimeout && typeof this.options.requestTimeout == "number") {
3877
+ const controller = new AbortController;
3878
+ abortTimeout = safeSetTimeout(() => {
3879
+ controller.abort();
3880
+ }, this.options.requestTimeout);
3881
+ options.signal = controller.signal;
3882
+ }
3883
+ try {
3884
+ return await this.fetch(url, options);
3885
+ } catch (error) {
3886
+ this._events.emit("error", error);
3887
+ return;
3888
+ } finally {
3889
+ if (abortTimeout)
3890
+ clearTimeout(abortTimeout);
3891
+ }
3892
+ }
3893
+ extractPropertiesFromEvent(eventProperties, groups) {
3894
+ if (!eventProperties)
3895
+ return {
3896
+ personProperties: {},
3897
+ groupProperties: {}
3898
+ };
3899
+ const personProperties = {};
3900
+ const groupProperties = {};
3901
+ for (const [key, value] of Object.entries(eventProperties))
3902
+ if (isPlainObject(value) && groups && key in groups) {
3903
+ const groupProps = {};
3904
+ for (const [groupKey, groupValue] of Object.entries(value))
3905
+ groupProps[String(groupKey)] = String(groupValue);
3906
+ groupProperties[String(key)] = groupProps;
3907
+ } else
3908
+ personProperties[String(key)] = String(value);
3909
+ return {
3910
+ personProperties,
3911
+ groupProperties
3912
+ };
3913
+ }
3914
+ async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {
3915
+ const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};
3916
+ const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};
3917
+ const flagKeys = sendFeatureFlagsOptions?.flagKeys;
3918
+ const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? this.options.strictLocalEvaluation ?? false;
3919
+ if (onlyEvaluateLocally)
3920
+ if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0))
3921
+ return {};
3922
+ else {
3923
+ const groupsWithStringValues = {};
3924
+ for (const [key, value] of Object.entries(groups || {}))
3925
+ groupsWithStringValues[key] = String(value);
3926
+ return await this.getAllFlags(distinctId, {
3927
+ groups: groupsWithStringValues,
3928
+ personProperties: finalPersonProperties,
3929
+ groupProperties: finalGroupProperties,
3930
+ disableGeoip,
3931
+ onlyEvaluateLocally: true,
3932
+ flagKeys
3933
+ });
3934
+ }
3935
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3936
+ const groupsWithStringValues = {};
3937
+ for (const [key, value] of Object.entries(groups || {}))
3938
+ groupsWithStringValues[key] = String(value);
3939
+ return await this.getAllFlags(distinctId, {
3940
+ groups: groupsWithStringValues,
3941
+ personProperties: finalPersonProperties,
3942
+ groupProperties: finalGroupProperties,
3943
+ disableGeoip,
3944
+ onlyEvaluateLocally: true,
3945
+ flagKeys
3946
+ });
3947
+ }
3948
+ return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;
3949
+ }
3950
+ addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3951
+ const allPersonProperties = {
3952
+ distinct_id: distinctId,
3953
+ ...personProperties || {}
3954
+ };
3955
+ const allGroupProperties = {};
3956
+ if (groups)
3957
+ for (const groupName of Object.keys(groups))
3958
+ allGroupProperties[groupName] = {
3959
+ $group_key: groups[groupName],
3960
+ ...groupProperties?.[groupName] || {}
3961
+ };
3962
+ return {
3963
+ allPersonProperties,
3964
+ allGroupProperties
3965
+ };
3966
+ }
3967
+ createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {
3968
+ return {
3969
+ distinctId,
3970
+ groups: groups || {},
3971
+ personProperties: personProperties || {},
3972
+ groupProperties: groupProperties || {},
3973
+ evaluationCache: {}
3974
+ };
3975
+ }
3976
+ captureException(error, distinctId, additionalProperties, uuid) {
3977
+ if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3978
+ const syntheticException = new Error("PostHog syntheticException");
3979
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3980
+ syntheticException
3981
+ }, distinctId, additionalProperties).then((msg) => this.capture({
3982
+ ...msg,
3983
+ uuid
3984
+ })));
3985
+ }
3986
+ }
3987
+ async captureExceptionImmediate(error, distinctId, additionalProperties) {
3988
+ if (!ErrorTracking.isPreviouslyCapturedError(error)) {
3989
+ const syntheticException = new Error("PostHog syntheticException");
3990
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3991
+ syntheticException
3992
+ }, distinctId, additionalProperties).then((msg) => this.captureImmediate(msg)));
3993
+ }
3994
+ }
3995
+ async prepareEventMessage(props) {
3996
+ const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
3997
+ const contextData = this.context?.get();
3998
+ let mergedDistinctId = distinctId || contextData?.distinctId;
3999
+ const mergedProperties = {
4000
+ ...this.props,
4001
+ ...contextData?.properties || {},
4002
+ ...properties || {}
4003
+ };
4004
+ if (!mergedDistinctId) {
4005
+ mergedDistinctId = uuidv7();
4006
+ mergedProperties.$process_person_profile = false;
4007
+ }
4008
+ if (contextData?.sessionId && !mergedProperties.$session_id)
4009
+ mergedProperties.$session_id = contextData.sessionId;
4010
+ const eventMessage = this._runBeforeSend({
4011
+ distinctId: mergedDistinctId,
4012
+ event,
4013
+ properties: mergedProperties,
4014
+ groups,
4015
+ sendFeatureFlags,
4016
+ timestamp,
4017
+ disableGeoip,
4018
+ uuid
4019
+ });
4020
+ if (!eventMessage)
4021
+ return Promise.reject(null);
4022
+ const eventProperties = await Promise.resolve().then(async () => {
4023
+ if (sendFeatureFlags) {
4024
+ const sendFeatureFlagsOptions = typeof sendFeatureFlags == "object" ? sendFeatureFlags : undefined;
4025
+ return await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
4026
+ }
4027
+ eventMessage.event;
4028
+ return {};
4029
+ }).then((flags) => {
4030
+ const additionalProperties = {};
4031
+ if (flags)
4032
+ for (const [feature, variant] of Object.entries(flags))
4033
+ additionalProperties[`$feature/${feature}`] = variant;
4034
+ const activeFlags = Object.keys(flags || {}).filter((flag) => flags?.[flag] !== false).sort();
4035
+ if (activeFlags.length > 0)
4036
+ additionalProperties["$active_feature_flags"] = activeFlags;
4037
+ return additionalProperties;
4038
+ }).catch(() => ({})).then((additionalProperties) => {
4039
+ const props2 = {
4040
+ ...additionalProperties,
4041
+ ...eventMessage.properties || {},
4042
+ $groups: eventMessage.groups || groups
4043
+ };
4044
+ return props2;
4045
+ });
4046
+ if (eventMessage.event === "$pageview" && this.options.__preview_capture_bot_pageviews && typeof eventProperties.$raw_user_agent == "string") {
4047
+ if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
4048
+ eventMessage.event = "$bot_pageview";
4049
+ eventProperties.$browser_type = "bot";
4050
+ }
4051
+ }
4052
+ return {
4053
+ distinctId: eventMessage.distinctId,
4054
+ event: eventMessage.event,
4055
+ properties: eventProperties,
4056
+ options: {
4057
+ timestamp: eventMessage.timestamp,
4058
+ disableGeoip: eventMessage.disableGeoip,
4059
+ uuid: eventMessage.uuid
4060
+ }
4061
+ };
4062
+ }
4063
+ _runBeforeSend(eventMessage) {
4064
+ const beforeSend = this.options.before_send;
4065
+ if (!beforeSend)
4066
+ return eventMessage;
4067
+ const fns = Array.isArray(beforeSend) ? beforeSend : [
4068
+ beforeSend
4069
+ ];
4070
+ let result = eventMessage;
4071
+ for (const fn of fns) {
4072
+ result = fn(result);
4073
+ if (!result) {
4074
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
4075
+ return null;
4076
+ }
4077
+ if (!result.properties || Object.keys(result.properties).length === 0) {
4078
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
4079
+ this._logger.warn(message);
4080
+ }
4081
+ }
4082
+ return result;
4083
+ }
4084
+ }
4085
+
4086
+ // node_modules/posthog-node/dist/extensions/context/context.mjs
4087
+ import { AsyncLocalStorage } from "async_hooks";
4088
+
4089
+ class PostHogContext {
4090
+ constructor() {
4091
+ this.storage = new AsyncLocalStorage;
4092
+ }
4093
+ get() {
4094
+ return this.storage.getStore();
4095
+ }
4096
+ run(context, fn, options) {
4097
+ return this.storage.run(this.resolve(context, options), fn);
4098
+ }
4099
+ enter(context, options) {
4100
+ this.storage.enterWith(this.resolve(context, options));
4101
+ }
4102
+ resolve(context, options) {
4103
+ if (options?.fresh === true)
4104
+ return context;
4105
+ const current = this.get() || {};
4106
+ return {
4107
+ distinctId: context.distinctId ?? current.distinctId,
4108
+ sessionId: context.sessionId ?? current.sessionId,
4109
+ properties: {
4110
+ ...current.properties || {},
4111
+ ...context.properties || {}
4112
+ }
4113
+ };
4114
+ }
4115
+ }
4116
+
4117
+ // node_modules/posthog-node/dist/extensions/sentry-integration.mjs
4118
+ var NAME = "posthog-node";
4119
+ function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
4120
+ "error"
4121
+ ], sendExceptionsToPostHog = true } = {}) {
4122
+ return (event) => {
4123
+ const shouldProcessLevel = severityAllowList === "*" || severityAllowList.includes(event.level);
4124
+ if (!shouldProcessLevel)
4125
+ return event;
4126
+ if (!event.tags)
4127
+ event.tags = {};
4128
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
4129
+ if (userId === undefined)
4130
+ return event;
4131
+ const uiHost = _posthog.options.host ?? "https://us.i.posthog.com";
4132
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
4133
+ event.tags["PostHog Person URL"] = personUrl;
4134
+ const exceptions = event.exception?.values || [];
4135
+ const exceptionList = exceptions.map((exception) => ({
4136
+ ...exception,
4137
+ stacktrace: exception.stacktrace ? {
4138
+ ...exception.stacktrace,
4139
+ type: "raw",
4140
+ frames: (exception.stacktrace.frames || []).map((frame) => ({
4141
+ ...frame,
4142
+ platform: "node:javascript"
4143
+ }))
4144
+ } : undefined
4145
+ }));
4146
+ const properties = {
4147
+ $exception_message: exceptions[0]?.value || event.message,
4148
+ $exception_type: exceptions[0]?.type,
4149
+ $exception_level: event.level,
4150
+ $exception_list: exceptionList,
4151
+ $sentry_event_id: event.event_id,
4152
+ $sentry_exception: event.exception,
4153
+ $sentry_exception_message: exceptions[0]?.value || event.message,
4154
+ $sentry_exception_type: exceptions[0]?.type,
4155
+ $sentry_tags: event.tags
4156
+ };
4157
+ if (organization && projectId)
4158
+ properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
4159
+ if (sendExceptionsToPostHog)
4160
+ _posthog.capture({
4161
+ event: "$exception",
4162
+ distinctId: userId,
4163
+ properties
4164
+ });
4165
+ return event;
4166
+ };
4167
+ }
4168
+ class PostHogSentryIntegration {
4169
+ static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
4170
+ constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
4171
+ this.name = NAME;
4172
+ this.name = NAME;
4173
+ this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {
4174
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
4175
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
4176
+ organization,
4177
+ projectId,
4178
+ prefix,
4179
+ severityAllowList,
4180
+ sendExceptionsToPostHog: sendExceptionsToPostHog ?? true
4181
+ }));
4182
+ };
4183
+ }
4184
+ }
4185
+ // node_modules/posthog-node/dist/entrypoints/index.node.mjs
4186
+ ErrorTracking.errorPropertiesBuilder = new exports_error_tracking.ErrorPropertiesBuilder([
4187
+ new exports_error_tracking.EventCoercer,
4188
+ new exports_error_tracking.ErrorCoercer,
4189
+ new exports_error_tracking.ObjectCoercer,
4190
+ new exports_error_tracking.StringCoercer,
4191
+ new exports_error_tracking.PrimitiveCoercer
4192
+ ], exports_error_tracking.createStackParser("node:javascript", exports_error_tracking.nodeStackLineParser), [
4193
+ createModulerModifier(),
4194
+ addSourceContext
4195
+ ]);
4196
+
4197
+ class PostHog extends PostHogBackendClient {
4198
+ getLibraryId() {
4199
+ return "posthog-node";
4200
+ }
4201
+ initializeContext() {
4202
+ return new PostHogContext;
4203
+ }
4204
+ }
4205
+
4206
+ // src/analytics.ts
4207
+ var POSTHOG_API_KEY = process.env.VITE_PUBLIC_POSTHOG_KEY ?? "";
4208
+ var POSTHOG_HOST = process.env.VITE_PUBLIC_POSTHOG_HOST ?? "https://us.i.posthog.com";
4209
+ var client = null;
4210
+ var distinctId = os.hostname();
4211
+ function initAnalytics() {
4212
+ if (!POSTHOG_API_KEY)
4213
+ return;
4214
+ client = new PostHog(POSTHOG_API_KEY, { host: POSTHOG_HOST });
4215
+ client.on("error", (err) => {
4216
+ console.error("[ctrl-daemon] PostHog error:", err);
4217
+ });
4218
+ }
4219
+ function trackEvent(event, properties) {
4220
+ if (!client)
4221
+ return;
4222
+ client.capture({ distinctId, event, properties });
4223
+ }
4224
+ function trackException(error, properties) {
4225
+ if (!client)
4226
+ return;
4227
+ client.captureException(error, distinctId, properties);
4228
+ }
4229
+ async function shutdownAnalytics() {
4230
+ if (!client)
4231
+ return;
4232
+ await client.shutdown();
4233
+ }
4234
+
5
4235
  // src/projectScanner.ts
6
4236
  import * as fs2 from "fs";
7
4237
  import * as path2 from "path";
@@ -631,6 +4861,20 @@ function resolveProjectsRoot(claudeHome) {
631
4861
  return path3.join(home, "projects");
632
4862
  }
633
4863
  function main() {
4864
+ initAnalytics();
4865
+ process.on("uncaughtException", async (err) => {
4866
+ console.error("[ctrl-daemon] Uncaught exception:", err);
4867
+ trackException(err);
4868
+ await shutdownAnalytics();
4869
+ process.exit(1);
4870
+ });
4871
+ process.on("unhandledRejection", async (reason) => {
4872
+ const err = reason instanceof Error ? reason : new Error(String(reason));
4873
+ console.error("[ctrl-daemon] Unhandled rejection:", err);
4874
+ trackException(err);
4875
+ await shutdownAnalytics();
4876
+ process.exit(1);
4877
+ });
634
4878
  const { projectDir, port, host } = parseArgs();
635
4879
  const claudeHome = process.env.CLAUDE_HOME;
636
4880
  let scanDirs;
@@ -650,9 +4894,15 @@ function main() {
650
4894
  const waitingTimers = new Map;
651
4895
  const permissionTimers = new Map;
652
4896
  const server = createServer({ port, host, agents });
4897
+ trackEvent("daemon_started", {
4898
+ distinct_id: distinctId,
4899
+ port,
4900
+ host,
4901
+ mode: projectDir ? "single" : "all"
4902
+ });
653
4903
  const scanAll = !projectDir;
654
4904
  const scanner = startProjectScanner(scanDirs[0], scanAll, agents, fileWatchers, pollingTimers, waitingTimers, permissionTimers, server.broadcast);
655
- process.on("SIGINT", () => {
4905
+ async function shutdown() {
656
4906
  console.log(`
657
4907
  [ctrl-daemon] Shutting down...`);
658
4908
  scanner.stop();
@@ -665,7 +4915,10 @@ function main() {
665
4915
  clearTimeout(timer);
666
4916
  for (const timer of permissionTimers.values())
667
4917
  clearTimeout(timer);
4918
+ await shutdownAnalytics();
668
4919
  process.exit(0);
669
- });
4920
+ }
4921
+ process.on("SIGINT", () => void shutdown());
4922
+ process.on("SIGTERM", () => void shutdown());
670
4923
  }
671
4924
  main();