@rpcbase/server 0.449.0 → 0.451.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,11 +4,14 @@ import MongoStore from "connect-mongo";
4
4
  import { createClient } from "redis";
5
5
  import env from "@rpcbase/env";
6
6
  import { initApiClient, SsrErrorFallback, SSR_ERROR_STATE_GLOBAL_KEY, serializeSsrErrorState } from "@rpcbase/client";
7
- import assert from "assert";
7
+ import { dirname, posix, sep } from "path";
8
+ import { createReadStream, readFileSync } from "node:fs";
9
+ import { createInterface } from "node:readline";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
11
+ import assert$1 from "assert";
8
12
  import { hkdfSync, scrypt } from "crypto";
9
13
  import { createProxyMiddleware } from "http-proxy-middleware";
10
14
  import fs from "node:fs/promises";
11
- import { readFileSync } from "node:fs";
12
15
  import { Transform } from "node:stream";
13
16
  import { StrictMode, createElement } from "react";
14
17
  import { renderToPipeableStream, renderToStaticMarkup } from "react-dom/server";
@@ -186,8 +189,3068 @@ function requireLib() {
186
189
  }
187
190
  var libExports = requireLib();
188
191
  const requestIp = /* @__PURE__ */ getDefaultExportFromCjs(libExports);
192
+ function createModulerModifier() {
193
+ const getModuleFromFileName = createGetModuleFromFilename();
194
+ return async (frames) => {
195
+ for (const frame of frames) frame.module = getModuleFromFileName(frame.filename);
196
+ return frames;
197
+ };
198
+ }
199
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = "\\" === sep) {
200
+ const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
201
+ return (filename) => {
202
+ if (!filename) return;
203
+ const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;
204
+ let { dir, base: file, ext } = posix.parse(normalizedFilename);
205
+ if (".js" === ext || ".mjs" === ext || ".cjs" === ext) file = file.slice(0, -1 * ext.length);
206
+ const decodedFile = decodeURIComponent(file);
207
+ if (!dir) dir = ".";
208
+ const n = dir.lastIndexOf("/node_modules");
209
+ if (n > -1) return `${dir.slice(n + 14).replace(/\//g, ".")}:${decodedFile}`;
210
+ if (dir.startsWith(normalizedBase)) {
211
+ const moduleName = dir.slice(normalizedBase.length + 1).replace(/\//g, ".");
212
+ return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;
213
+ }
214
+ return decodedFile;
215
+ };
216
+ }
217
+ function normalizeWindowsPath(path) {
218
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
219
+ }
220
+ const normalizeFlagsResponse = (flagsResponse) => {
221
+ if ("flags" in flagsResponse) {
222
+ const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
223
+ const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);
224
+ return {
225
+ ...flagsResponse,
226
+ featureFlags,
227
+ featureFlagPayloads
228
+ };
229
+ }
230
+ {
231
+ const featureFlags = flagsResponse.featureFlags ?? {};
232
+ const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v]) => [
233
+ k,
234
+ parsePayload(v)
235
+ ]));
236
+ const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value]) => [
237
+ key,
238
+ getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])
239
+ ]));
240
+ return {
241
+ ...flagsResponse,
242
+ featureFlags,
243
+ featureFlagPayloads,
244
+ flags
245
+ };
246
+ }
247
+ };
248
+ function getFlagDetailFromFlagAndPayload(key, value, payload) {
249
+ return {
250
+ key,
251
+ enabled: "string" == typeof value ? true : value,
252
+ variant: "string" == typeof value ? value : void 0,
253
+ reason: void 0,
254
+ metadata: {
255
+ id: void 0,
256
+ version: void 0,
257
+ payload: payload ? JSON.stringify(payload) : void 0,
258
+ description: void 0
259
+ }
260
+ };
261
+ }
262
+ const getFlagValuesFromFlags = (flags) => Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail]) => [
263
+ key,
264
+ getFeatureFlagValue(detail)
265
+ ]).filter(([, value]) => void 0 !== value));
266
+ const getPayloadsFromFlags = (flags) => {
267
+ const safeFlags = flags ?? {};
268
+ return Object.fromEntries(Object.keys(safeFlags).filter((flag) => {
269
+ const details = safeFlags[flag];
270
+ return details.enabled && details.metadata && void 0 !== details.metadata.payload;
271
+ }).map((flag) => {
272
+ const payload = safeFlags[flag].metadata?.payload;
273
+ return [
274
+ flag,
275
+ payload ? parsePayload(payload) : void 0
276
+ ];
277
+ }));
278
+ };
279
+ const getFeatureFlagValue = (detail) => void 0 === detail ? void 0 : detail.variant ?? detail.enabled;
280
+ const parsePayload = (response) => {
281
+ if ("string" != typeof response) return response;
282
+ try {
283
+ return JSON.parse(response);
284
+ } catch {
285
+ return response;
286
+ }
287
+ };
288
+ const DIGITS = "0123456789abcdef";
289
+ class UUID {
290
+ constructor(bytes) {
291
+ this.bytes = bytes;
292
+ }
293
+ static ofInner(bytes) {
294
+ if (16 === bytes.length) return new UUID(bytes);
295
+ throw new TypeError("not 128-bit length");
296
+ }
297
+ static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {
298
+ 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) throw new RangeError("invalid field value");
299
+ const bytes = new Uint8Array(16);
300
+ bytes[0] = unixTsMs / 2 ** 40;
301
+ bytes[1] = unixTsMs / 2 ** 32;
302
+ bytes[2] = unixTsMs / 2 ** 24;
303
+ bytes[3] = unixTsMs / 2 ** 16;
304
+ bytes[4] = unixTsMs / 256;
305
+ bytes[5] = unixTsMs;
306
+ bytes[6] = 112 | randA >>> 8;
307
+ bytes[7] = randA;
308
+ bytes[8] = 128 | randBHi >>> 24;
309
+ bytes[9] = randBHi >>> 16;
310
+ bytes[10] = randBHi >>> 8;
311
+ bytes[11] = randBHi;
312
+ bytes[12] = randBLo >>> 24;
313
+ bytes[13] = randBLo >>> 16;
314
+ bytes[14] = randBLo >>> 8;
315
+ bytes[15] = randBLo;
316
+ return new UUID(bytes);
317
+ }
318
+ static parse(uuid) {
319
+ let hex;
320
+ switch (uuid.length) {
321
+ case 32:
322
+ hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];
323
+ break;
324
+ case 36:
325
+ 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("");
326
+ break;
327
+ case 38:
328
+ 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("");
329
+ break;
330
+ case 45:
331
+ 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("");
332
+ break;
333
+ }
334
+ if (hex) {
335
+ const inner = new Uint8Array(16);
336
+ for (let i = 0; i < 16; i += 4) {
337
+ const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);
338
+ inner[i + 0] = n >>> 24;
339
+ inner[i + 1] = n >>> 16;
340
+ inner[i + 2] = n >>> 8;
341
+ inner[i + 3] = n;
342
+ }
343
+ return new UUID(inner);
344
+ }
345
+ throw new SyntaxError("could not parse UUID string");
346
+ }
347
+ toString() {
348
+ let text = "";
349
+ for (let i = 0; i < this.bytes.length; i++) {
350
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
351
+ text += DIGITS.charAt(15 & this.bytes[i]);
352
+ if (3 === i || 5 === i || 7 === i || 9 === i) text += "-";
353
+ }
354
+ return text;
355
+ }
356
+ toHex() {
357
+ let text = "";
358
+ for (let i = 0; i < this.bytes.length; i++) {
359
+ text += DIGITS.charAt(this.bytes[i] >>> 4);
360
+ text += DIGITS.charAt(15 & this.bytes[i]);
361
+ }
362
+ return text;
363
+ }
364
+ toJSON() {
365
+ return this.toString();
366
+ }
367
+ getVariant() {
368
+ const n = this.bytes[8] >>> 4;
369
+ if (n < 0) throw new Error("unreachable");
370
+ if (n <= 7) return this.bytes.every((e) => 0 === e) ? "NIL" : "VAR_0";
371
+ if (n <= 11) return "VAR_10";
372
+ if (n <= 13) return "VAR_110";
373
+ if (n <= 15) return this.bytes.every((e) => 255 === e) ? "MAX" : "VAR_RESERVED";
374
+ else throw new Error("unreachable");
375
+ }
376
+ getVersion() {
377
+ return "VAR_10" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;
378
+ }
379
+ clone() {
380
+ return new UUID(this.bytes.slice(0));
381
+ }
382
+ equals(other) {
383
+ return 0 === this.compareTo(other);
384
+ }
385
+ compareTo(other) {
386
+ for (let i = 0; i < 16; i++) {
387
+ const diff = this.bytes[i] - other.bytes[i];
388
+ if (0 !== diff) return Math.sign(diff);
389
+ }
390
+ return 0;
391
+ }
392
+ }
393
+ class V7Generator {
394
+ constructor(randomNumberGenerator) {
395
+ this.timestamp = 0;
396
+ this.counter = 0;
397
+ this.random = randomNumberGenerator ?? getDefaultRandom();
398
+ }
399
+ generate() {
400
+ return this.generateOrResetCore(Date.now(), 1e4);
401
+ }
402
+ generateOrAbort() {
403
+ return this.generateOrAbortCore(Date.now(), 1e4);
404
+ }
405
+ generateOrResetCore(unixTsMs, rollbackAllowance) {
406
+ let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
407
+ if (void 0 === value) {
408
+ this.timestamp = 0;
409
+ value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);
410
+ }
411
+ return value;
412
+ }
413
+ generateOrAbortCore(unixTsMs, rollbackAllowance) {
414
+ const MAX_COUNTER = 4398046511103;
415
+ if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 281474976710655) throw new RangeError("`unixTsMs` must be a 48-bit positive integer");
416
+ if (rollbackAllowance < 0 || rollbackAllowance > 281474976710655) throw new RangeError("`rollbackAllowance` out of reasonable range");
417
+ if (unixTsMs > this.timestamp) {
418
+ this.timestamp = unixTsMs;
419
+ this.resetCounter();
420
+ } else {
421
+ if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;
422
+ this.counter++;
423
+ if (this.counter > MAX_COUNTER) {
424
+ this.timestamp++;
425
+ this.resetCounter();
426
+ }
427
+ }
428
+ return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());
429
+ }
430
+ resetCounter() {
431
+ this.counter = 1024 * this.random.nextUint32() + (1023 & this.random.nextUint32());
432
+ }
433
+ generateV4() {
434
+ const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);
435
+ bytes[6] = 64 | bytes[6] >>> 4;
436
+ bytes[8] = 128 | bytes[8] >>> 2;
437
+ return UUID.ofInner(bytes);
438
+ }
439
+ }
440
+ const getDefaultRandom = () => ({
441
+ nextUint32: () => 65536 * Math.trunc(65536 * Math.random()) + Math.trunc(65536 * Math.random())
442
+ });
443
+ let defaultGenerator;
444
+ const uuidv7 = () => uuidv7obj().toString();
445
+ const uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator())).generate();
446
+ const DEFAULT_BLOCKED_UA_STRS = [
447
+ "amazonbot",
448
+ "amazonproductbot",
449
+ "app.hypefactors.com",
450
+ "applebot",
451
+ "archive.org_bot",
452
+ "awariobot",
453
+ "backlinksextendedbot",
454
+ "baiduspider",
455
+ "bingbot",
456
+ "bingpreview",
457
+ "chrome-lighthouse",
458
+ "dataforseobot",
459
+ "deepscan",
460
+ "duckduckbot",
461
+ "facebookexternal",
462
+ "facebookcatalog",
463
+ "http://yandex.com/bots",
464
+ "hubspot",
465
+ "ia_archiver",
466
+ "leikibot",
467
+ "linkedinbot",
468
+ "meta-externalagent",
469
+ "mj12bot",
470
+ "msnbot",
471
+ "nessus",
472
+ "petalbot",
473
+ "pinterest",
474
+ "prerender",
475
+ "rogerbot",
476
+ "screaming frog",
477
+ "sebot-wa",
478
+ "sitebulb",
479
+ "slackbot",
480
+ "slurp",
481
+ "trendictionbot",
482
+ "turnitin",
483
+ "twitterbot",
484
+ "vercel-screenshot",
485
+ "vercelbot",
486
+ "yahoo! slurp",
487
+ "yandexbot",
488
+ "zoombot",
489
+ "bot.htm",
490
+ "bot.php",
491
+ "(bot;",
492
+ "bot/",
493
+ "crawler",
494
+ "ahrefsbot",
495
+ "ahrefssiteaudit",
496
+ "semrushbot",
497
+ "siteauditbot",
498
+ "splitsignalbot",
499
+ "gptbot",
500
+ "oai-searchbot",
501
+ "chatgpt-user",
502
+ "perplexitybot",
503
+ "better uptime bot",
504
+ "sentryuptimebot",
505
+ "uptimerobot",
506
+ "headlesschrome",
507
+ "cypress",
508
+ "google-hoteladsverifier",
509
+ "adsbot-google",
510
+ "apis-google",
511
+ "duplexweb-google",
512
+ "feedfetcher-google",
513
+ "google favicon",
514
+ "google web preview",
515
+ "google-read-aloud",
516
+ "googlebot",
517
+ "googleother",
518
+ "google-cloudvertexbot",
519
+ "googleweblight",
520
+ "mediapartners-google",
521
+ "storebot-google",
522
+ "google-inspectiontool",
523
+ "bytespider"
524
+ ];
525
+ const isBlockedUA = function(ua, customBlockedUserAgents = []) {
526
+ if (!ua) return false;
527
+ const uaLower = ua.toLowerCase();
528
+ return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA) => {
529
+ const blockedUaLower = blockedUA.toLowerCase();
530
+ return -1 !== uaLower.indexOf(blockedUaLower);
531
+ });
532
+ };
533
+ var types_PostHogPersistedProperty = /* @__PURE__ */ (function(PostHogPersistedProperty) {
534
+ PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
535
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
536
+ PostHogPersistedProperty["Props"] = "props";
537
+ PostHogPersistedProperty["FeatureFlagDetails"] = "feature_flag_details";
538
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
539
+ PostHogPersistedProperty["FeatureFlagPayloads"] = "feature_flag_payloads";
540
+ PostHogPersistedProperty["BootstrapFeatureFlagDetails"] = "bootstrap_feature_flag_details";
541
+ PostHogPersistedProperty["BootstrapFeatureFlags"] = "bootstrap_feature_flags";
542
+ PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
543
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
544
+ PostHogPersistedProperty["Queue"] = "queue";
545
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
546
+ PostHogPersistedProperty["SessionId"] = "session_id";
547
+ PostHogPersistedProperty["SessionStartTimestamp"] = "session_start_timestamp";
548
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
549
+ PostHogPersistedProperty["PersonProperties"] = "person_properties";
550
+ PostHogPersistedProperty["GroupProperties"] = "group_properties";
551
+ PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
552
+ PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
553
+ PostHogPersistedProperty["SessionReplay"] = "session_replay";
554
+ PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
555
+ PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
556
+ PostHogPersistedProperty["Surveys"] = "surveys";
557
+ PostHogPersistedProperty["RemoteConfig"] = "remote_config";
558
+ PostHogPersistedProperty["FlagsEndpointWasHit"] = "flags_endpoint_was_hit";
559
+ return PostHogPersistedProperty;
560
+ })({});
561
+ const nativeIsArray = Array.isArray;
562
+ const ObjProto = Object.prototype;
563
+ const type_utils_toString = ObjProto.toString;
564
+ const isArray = nativeIsArray || function(obj) {
565
+ return "[object Array]" === type_utils_toString.call(obj);
566
+ };
567
+ const isUndefined = (x) => void 0 === x;
568
+ const isString = (x) => "[object String]" == type_utils_toString.call(x);
569
+ const isEmptyString = (x) => isString(x) && 0 === x.trim().length;
570
+ const isNumber = (x) => "[object Number]" == type_utils_toString.call(x);
571
+ const isPlainError = (x) => x instanceof Error;
572
+ function isInstanceOf(candidate, base) {
573
+ try {
574
+ return candidate instanceof base;
575
+ } catch {
576
+ return false;
577
+ }
578
+ }
579
+ function isPrimitive(value) {
580
+ return null === value || "object" != typeof value;
581
+ }
582
+ function isBuiltin(candidate, className) {
583
+ return Object.prototype.toString.call(candidate) === `[object ${className}]`;
584
+ }
585
+ function isEvent(candidate) {
586
+ return !isUndefined(Event) && isInstanceOf(candidate, Event);
587
+ }
588
+ function isPlainObject(candidate) {
589
+ return isBuiltin(candidate, "Object");
590
+ }
591
+ function clampToRange(value, min, max, logger, fallbackValue) {
592
+ if (min > max) {
593
+ logger.warn("min cannot be greater than max.");
594
+ min = max;
595
+ }
596
+ if (isNumber(value)) if (value > max) {
597
+ logger.warn(" cannot be greater than max: " + max + ". Using max value instead.");
598
+ return max;
599
+ } else {
600
+ if (!(value < min)) return value;
601
+ logger.warn(" cannot be less than min: " + min + ". Using min value instead.");
602
+ return min;
603
+ }
604
+ logger.warn(" must be a number. using max or fallback. max: " + max + ", fallback: " + fallbackValue);
605
+ return clampToRange(max, min, max, logger);
606
+ }
607
+ const ONE_DAY_IN_MS = 864e5;
608
+ class BucketedRateLimiter {
609
+ constructor(options) {
610
+ this._buckets = {};
611
+ this._onBucketRateLimited = options._onBucketRateLimited;
612
+ this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);
613
+ this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);
614
+ this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);
615
+ }
616
+ _applyRefill(bucket, now) {
617
+ const elapsedMs = now - bucket.lastAccess;
618
+ const refillIntervals = Math.floor(elapsedMs / this._refillInterval);
619
+ if (refillIntervals > 0) {
620
+ const tokensToAdd = refillIntervals * this._refillRate;
621
+ bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);
622
+ bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;
623
+ }
624
+ }
625
+ consumeRateLimit(key) {
626
+ const now = Date.now();
627
+ const keyStr = String(key);
628
+ let bucket = this._buckets[keyStr];
629
+ if (bucket) this._applyRefill(bucket, now);
630
+ else {
631
+ bucket = {
632
+ tokens: this._bucketSize,
633
+ lastAccess: now
634
+ };
635
+ this._buckets[keyStr] = bucket;
636
+ }
637
+ if (0 === bucket.tokens) return true;
638
+ bucket.tokens--;
639
+ if (0 === bucket.tokens) this._onBucketRateLimited?.(key);
640
+ return 0 === bucket.tokens;
641
+ }
642
+ stop() {
643
+ this._buckets = {};
644
+ }
645
+ }
646
+ class PromiseQueue {
647
+ add(promise) {
648
+ const promiseUUID = uuidv7();
649
+ this.promiseByIds[promiseUUID] = promise;
650
+ promise.catch(() => {
651
+ }).finally(() => {
652
+ delete this.promiseByIds[promiseUUID];
653
+ });
654
+ return promise;
655
+ }
656
+ async join() {
657
+ let promises = Object.values(this.promiseByIds);
658
+ let length = promises.length;
659
+ while (length > 0) {
660
+ await Promise.all(promises);
661
+ promises = Object.values(this.promiseByIds);
662
+ length = promises.length;
663
+ }
664
+ }
665
+ get length() {
666
+ return Object.keys(this.promiseByIds).length;
667
+ }
668
+ constructor() {
669
+ this.promiseByIds = {};
670
+ }
671
+ }
672
+ function createConsole(consoleLike = console) {
673
+ const lockedMethods = {
674
+ log: consoleLike.log.bind(consoleLike),
675
+ warn: consoleLike.warn.bind(consoleLike),
676
+ error: consoleLike.error.bind(consoleLike),
677
+ debug: consoleLike.debug.bind(consoleLike)
678
+ };
679
+ return lockedMethods;
680
+ }
681
+ const _createLogger = (prefix, maybeCall, consoleLike) => {
682
+ function _log(level, ...args) {
683
+ maybeCall(() => {
684
+ const consoleMethod = consoleLike[level];
685
+ consoleMethod(prefix, ...args);
686
+ });
687
+ }
688
+ const logger = {
689
+ info: (...args) => {
690
+ _log("log", ...args);
691
+ },
692
+ warn: (...args) => {
693
+ _log("warn", ...args);
694
+ },
695
+ error: (...args) => {
696
+ _log("error", ...args);
697
+ },
698
+ critical: (...args) => {
699
+ consoleLike["error"](prefix, ...args);
700
+ },
701
+ createLogger: (additionalPrefix) => _createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)
702
+ };
703
+ return logger;
704
+ };
705
+ const passThrough = (fn) => fn();
706
+ function createLogger(prefix, maybeCall = passThrough) {
707
+ return _createLogger(prefix, maybeCall, createConsole());
708
+ }
709
+ const STRING_FORMAT = "utf8";
710
+ function assert(truthyValue, message) {
711
+ if (!truthyValue || "string" != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);
712
+ }
713
+ function isEmpty(truthyValue) {
714
+ if (0 === truthyValue.trim().length) return true;
715
+ return false;
716
+ }
717
+ function removeTrailingSlash(url) {
718
+ return url?.replace(/\/+$/, "");
719
+ }
720
+ async function retriable(fn, props) {
721
+ let lastError = null;
722
+ for (let i = 0; i < props.retryCount + 1; i++) {
723
+ if (i > 0) await new Promise((r) => setTimeout(r, props.retryDelay));
724
+ try {
725
+ const res = await fn();
726
+ return res;
727
+ } catch (e) {
728
+ lastError = e;
729
+ if (!props.retryCheck(e)) throw e;
730
+ }
731
+ }
732
+ throw lastError;
733
+ }
734
+ function currentISOTime() {
735
+ return (/* @__PURE__ */ new Date()).toISOString();
736
+ }
737
+ function safeSetTimeout(fn, timeout) {
738
+ const t = setTimeout(fn, timeout);
739
+ t?.unref && t?.unref();
740
+ return t;
741
+ }
742
+ const isError = (x) => x instanceof Error;
743
+ function allSettled(promises) {
744
+ return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
745
+ status: "fulfilled",
746
+ value
747
+ }), (reason) => ({
748
+ status: "rejected",
749
+ reason
750
+ }))));
751
+ }
752
+ class SimpleEventEmitter {
753
+ constructor() {
754
+ this.events = {};
755
+ this.events = {};
756
+ }
757
+ on(event, listener) {
758
+ if (!this.events[event]) this.events[event] = [];
759
+ this.events[event].push(listener);
760
+ return () => {
761
+ this.events[event] = this.events[event].filter((x) => x !== listener);
762
+ };
763
+ }
764
+ emit(event, payload) {
765
+ for (const listener of this.events[event] || []) listener(payload);
766
+ for (const listener of this.events["*"] || []) listener(event, payload);
767
+ }
768
+ }
769
+ function isGzipSupported() {
770
+ return "CompressionStream" in globalThis;
771
+ }
772
+ async function gzipCompress(input, isDebug = true) {
773
+ try {
774
+ const dataStream = new Blob([
775
+ input
776
+ ], {
777
+ type: "text/plain"
778
+ }).stream();
779
+ const compressedStream = dataStream.pipeThrough(new CompressionStream("gzip"));
780
+ return await new Response(compressedStream).blob();
781
+ } catch (error) {
782
+ if (isDebug) console.error("Failed to gzip compress data", error);
783
+ return null;
784
+ }
785
+ }
786
+ class PostHogFetchHttpError extends Error {
787
+ constructor(response, reqByteLength) {
788
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
789
+ }
790
+ get status() {
791
+ return this.response.status;
792
+ }
793
+ get text() {
794
+ return this.response.text();
795
+ }
796
+ get json() {
797
+ return this.response.json();
798
+ }
799
+ }
800
+ class PostHogFetchNetworkError extends Error {
801
+ constructor(error) {
802
+ super("Network error while fetching PostHog", error instanceof Error ? {
803
+ cause: error
804
+ } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
805
+ }
806
+ }
807
+ async function logFlushError(err) {
808
+ if (err instanceof PostHogFetchHttpError) {
809
+ let text = "";
810
+ try {
811
+ text = await err.text;
812
+ } catch {
813
+ }
814
+ console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
815
+ } else console.error("Error while flushing PostHog", err);
816
+ return Promise.resolve();
817
+ }
818
+ function isPostHogFetchError(err) {
819
+ return "object" == typeof err && (err instanceof PostHogFetchHttpError || err instanceof PostHogFetchNetworkError);
820
+ }
821
+ function isPostHogFetchContentTooLargeError(err) {
822
+ return "object" == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
823
+ }
824
+ class PostHogCoreStateless {
825
+ constructor(apiKey, options = {}) {
826
+ this.flushPromise = null;
827
+ this.shutdownPromise = null;
828
+ this.promiseQueue = new PromiseQueue();
829
+ this._events = new SimpleEventEmitter();
830
+ this._isInitialized = false;
831
+ assert(apiKey, "You must pass your PostHog project's api key.");
832
+ this.apiKey = apiKey;
833
+ this.host = removeTrailingSlash(options.host || "https://us.i.posthog.com");
834
+ this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;
835
+ this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);
836
+ this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1e3);
837
+ this.flushInterval = options.flushInterval ?? 1e4;
838
+ this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;
839
+ this.defaultOptIn = options.defaultOptIn ?? true;
840
+ this.disableSurveys = options.disableSurveys ?? false;
841
+ this._retryOptions = {
842
+ retryCount: options.fetchRetryCount ?? 3,
843
+ retryDelay: options.fetchRetryDelay ?? 3e3,
844
+ retryCheck: isPostHogFetchError
845
+ };
846
+ this.requestTimeout = options.requestTimeout ?? 1e4;
847
+ this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3e3;
848
+ this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3e3;
849
+ this.disableGeoip = options.disableGeoip ?? true;
850
+ this.disabled = options.disabled ?? false;
851
+ this.historicalMigration = options?.historicalMigration ?? false;
852
+ this.evaluationEnvironments = options?.evaluationEnvironments;
853
+ this._initPromise = Promise.resolve();
854
+ this._isInitialized = true;
855
+ this._logger = createLogger("[PostHog]", this.logMsgIfDebug.bind(this));
856
+ this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);
857
+ }
858
+ logMsgIfDebug(fn) {
859
+ if (this.isDebug) fn();
860
+ }
861
+ wrap(fn) {
862
+ if (this.disabled) return void this._logger.warn("The client is disabled");
863
+ if (this._isInitialized) return fn();
864
+ this._initPromise.then(() => fn());
865
+ }
866
+ getCommonEventProperties() {
867
+ return {
868
+ $lib: this.getLibraryId(),
869
+ $lib_version: this.getLibraryVersion()
870
+ };
871
+ }
872
+ get optedOut() {
873
+ return this.getPersistedProperty(types_PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;
874
+ }
875
+ async optIn() {
876
+ this.wrap(() => {
877
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, false);
878
+ });
879
+ }
880
+ async optOut() {
881
+ this.wrap(() => {
882
+ this.setPersistedProperty(types_PostHogPersistedProperty.OptedOut, true);
883
+ });
884
+ }
885
+ on(event, cb) {
886
+ return this._events.on(event, cb);
887
+ }
888
+ debug(enabled = true) {
889
+ this.removeDebugCallback?.();
890
+ if (enabled) {
891
+ const removeDebugCallback = this.on("*", (event, payload) => this._logger.info(event, payload));
892
+ this.removeDebugCallback = () => {
893
+ removeDebugCallback();
894
+ this.removeDebugCallback = void 0;
895
+ };
896
+ }
897
+ }
898
+ get isDebug() {
899
+ return !!this.removeDebugCallback;
900
+ }
901
+ get isDisabled() {
902
+ return this.disabled;
903
+ }
904
+ buildPayload(payload) {
905
+ return {
906
+ distinct_id: payload.distinct_id,
907
+ event: payload.event,
908
+ properties: {
909
+ ...payload.properties || {},
910
+ ...this.getCommonEventProperties()
911
+ }
912
+ };
913
+ }
914
+ addPendingPromise(promise) {
915
+ return this.promiseQueue.add(promise);
916
+ }
917
+ identifyStateless(distinctId, properties, options) {
918
+ this.wrap(() => {
919
+ const payload = {
920
+ ...this.buildPayload({
921
+ distinct_id: distinctId,
922
+ event: "$identify",
923
+ properties
924
+ })
925
+ };
926
+ this.enqueue("identify", payload, options);
927
+ });
928
+ }
929
+ async identifyStatelessImmediate(distinctId, properties, options) {
930
+ const payload = {
931
+ ...this.buildPayload({
932
+ distinct_id: distinctId,
933
+ event: "$identify",
934
+ properties
935
+ })
936
+ };
937
+ await this.sendImmediate("identify", payload, options);
938
+ }
939
+ captureStateless(distinctId, event, properties, options) {
940
+ this.wrap(() => {
941
+ const payload = this.buildPayload({
942
+ distinct_id: distinctId,
943
+ event,
944
+ properties
945
+ });
946
+ this.enqueue("capture", payload, options);
947
+ });
948
+ }
949
+ async captureStatelessImmediate(distinctId, event, properties, options) {
950
+ const payload = this.buildPayload({
951
+ distinct_id: distinctId,
952
+ event,
953
+ properties
954
+ });
955
+ await this.sendImmediate("capture", payload, options);
956
+ }
957
+ aliasStateless(alias, distinctId, properties, options) {
958
+ this.wrap(() => {
959
+ const payload = this.buildPayload({
960
+ event: "$create_alias",
961
+ distinct_id: distinctId,
962
+ properties: {
963
+ ...properties || {},
964
+ distinct_id: distinctId,
965
+ alias
966
+ }
967
+ });
968
+ this.enqueue("alias", payload, options);
969
+ });
970
+ }
971
+ async aliasStatelessImmediate(alias, distinctId, properties, options) {
972
+ const payload = this.buildPayload({
973
+ event: "$create_alias",
974
+ distinct_id: distinctId,
975
+ properties: {
976
+ ...properties || {},
977
+ distinct_id: distinctId,
978
+ alias
979
+ }
980
+ });
981
+ await this.sendImmediate("alias", payload, options);
982
+ }
983
+ groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
984
+ this.wrap(() => {
985
+ const payload = this.buildPayload({
986
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
987
+ event: "$groupidentify",
988
+ properties: {
989
+ $group_type: groupType,
990
+ $group_key: groupKey,
991
+ $group_set: groupProperties || {},
992
+ ...eventProperties || {}
993
+ }
994
+ });
995
+ this.enqueue("capture", payload, options);
996
+ });
997
+ }
998
+ async getRemoteConfig() {
999
+ await this._initPromise;
1000
+ let host = this.host;
1001
+ if ("https://us.i.posthog.com" === host) host = "https://us-assets.i.posthog.com";
1002
+ else if ("https://eu.i.posthog.com" === host) host = "https://eu-assets.i.posthog.com";
1003
+ const url = `${host}/array/${this.apiKey}/config`;
1004
+ const fetchOptions = {
1005
+ method: "GET",
1006
+ headers: {
1007
+ ...this.getCustomHeaders(),
1008
+ "Content-Type": "application/json"
1009
+ }
1010
+ };
1011
+ return this.fetchWithRetry(url, fetchOptions, {
1012
+ retryCount: 0
1013
+ }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
1014
+ this._logger.error("Remote config could not be loaded", error);
1015
+ this._events.emit("error", error);
1016
+ });
1017
+ }
1018
+ async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = true) {
1019
+ await this._initPromise;
1020
+ const configParam = fetchConfig ? "&config=true" : "";
1021
+ const url = `${this.host}/flags/?v=2${configParam}`;
1022
+ const requestData = {
1023
+ token: this.apiKey,
1024
+ distinct_id: distinctId,
1025
+ groups,
1026
+ person_properties: personProperties,
1027
+ group_properties: groupProperties,
1028
+ ...extraPayload
1029
+ };
1030
+ if (this.evaluationEnvironments && this.evaluationEnvironments.length > 0) requestData.evaluation_environments = this.evaluationEnvironments;
1031
+ const fetchOptions = {
1032
+ method: "POST",
1033
+ headers: {
1034
+ ...this.getCustomHeaders(),
1035
+ "Content-Type": "application/json"
1036
+ },
1037
+ body: JSON.stringify(requestData)
1038
+ };
1039
+ this._logger.info("Flags URL", url);
1040
+ return this.fetchWithRetry(url, fetchOptions, {
1041
+ retryCount: 0
1042
+ }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => normalizeFlagsResponse(response)).catch((error) => {
1043
+ this._events.emit("error", error);
1044
+ });
1045
+ }
1046
+ async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1047
+ await this._initPromise;
1048
+ const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
1049
+ if (void 0 === flagDetailResponse) return {
1050
+ response: void 0,
1051
+ requestId: void 0
1052
+ };
1053
+ let response = getFeatureFlagValue(flagDetailResponse.response);
1054
+ if (void 0 === response) response = false;
1055
+ return {
1056
+ response,
1057
+ requestId: flagDetailResponse.requestId
1058
+ };
1059
+ }
1060
+ async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1061
+ await this._initPromise;
1062
+ const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1063
+ key
1064
+ ]);
1065
+ if (void 0 === flagsResponse) return;
1066
+ const featureFlags = flagsResponse.flags;
1067
+ const flagDetail = featureFlags[key];
1068
+ return {
1069
+ response: flagDetail,
1070
+ requestId: flagsResponse.requestId,
1071
+ evaluatedAt: flagsResponse.evaluatedAt
1072
+ };
1073
+ }
1074
+ async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {
1075
+ await this._initPromise;
1076
+ const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [
1077
+ key
1078
+ ]);
1079
+ if (!payloads) return;
1080
+ const response = payloads[key];
1081
+ if (void 0 === response) return null;
1082
+ return response;
1083
+ }
1084
+ async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1085
+ await this._initPromise;
1086
+ const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;
1087
+ return payloads;
1088
+ }
1089
+ async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1090
+ await this._initPromise;
1091
+ return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1092
+ }
1093
+ async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1094
+ await this._initPromise;
1095
+ const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);
1096
+ if (!featureFlagDetails) return {
1097
+ flags: void 0,
1098
+ payloads: void 0,
1099
+ requestId: void 0
1100
+ };
1101
+ return {
1102
+ flags: featureFlagDetails.featureFlags,
1103
+ payloads: featureFlagDetails.featureFlagPayloads,
1104
+ requestId: featureFlagDetails.requestId
1105
+ };
1106
+ }
1107
+ async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
1108
+ await this._initPromise;
1109
+ const extraPayload = {};
1110
+ if (disableGeoip ?? this.disableGeoip) extraPayload["geoip_disable"] = true;
1111
+ if (flagKeysToEvaluate) extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
1112
+ const flagsResponse = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
1113
+ if (void 0 === flagsResponse) return;
1114
+ if (flagsResponse.errorsWhileComputingFlags) console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");
1115
+ if (flagsResponse.quotaLimited?.includes("feature_flags")) {
1116
+ 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");
1117
+ return {
1118
+ flags: {},
1119
+ featureFlags: {},
1120
+ featureFlagPayloads: {},
1121
+ requestId: flagsResponse?.requestId
1122
+ };
1123
+ }
1124
+ return flagsResponse;
1125
+ }
1126
+ async getSurveysStateless() {
1127
+ await this._initPromise;
1128
+ if (true === this.disableSurveys) {
1129
+ this._logger.info("Loading surveys is disabled.");
1130
+ return [];
1131
+ }
1132
+ const url = `${this.host}/api/surveys/?token=${this.apiKey}`;
1133
+ const fetchOptions = {
1134
+ method: "GET",
1135
+ headers: {
1136
+ ...this.getCustomHeaders(),
1137
+ "Content-Type": "application/json"
1138
+ }
1139
+ };
1140
+ const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
1141
+ if (200 !== response2.status || !response2.json) {
1142
+ const msg = `Surveys API could not be loaded: ${response2.status}`;
1143
+ const error = new Error(msg);
1144
+ this._logger.error(error);
1145
+ this._events.emit("error", new Error(msg));
1146
+ return;
1147
+ }
1148
+ return response2.json();
1149
+ }).catch((error) => {
1150
+ this._logger.error("Surveys API could not be loaded", error);
1151
+ this._events.emit("error", error);
1152
+ });
1153
+ const newSurveys = response?.surveys;
1154
+ if (newSurveys) this._logger.info("Surveys fetched from API: ", JSON.stringify(newSurveys));
1155
+ return newSurveys ?? [];
1156
+ }
1157
+ get props() {
1158
+ if (!this._props) this._props = this.getPersistedProperty(types_PostHogPersistedProperty.Props);
1159
+ return this._props || {};
1160
+ }
1161
+ set props(val) {
1162
+ this._props = val;
1163
+ }
1164
+ async register(properties) {
1165
+ this.wrap(() => {
1166
+ this.props = {
1167
+ ...this.props,
1168
+ ...properties
1169
+ };
1170
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1171
+ });
1172
+ }
1173
+ async unregister(property) {
1174
+ this.wrap(() => {
1175
+ delete this.props[property];
1176
+ this.setPersistedProperty(types_PostHogPersistedProperty.Props, this.props);
1177
+ });
1178
+ }
1179
+ enqueue(type, _message, options) {
1180
+ this.wrap(() => {
1181
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1182
+ const message = this.prepareMessage(type, _message, options);
1183
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1184
+ if (queue.length >= this.maxQueueSize) {
1185
+ queue.shift();
1186
+ this._logger.info("Queue is full, the oldest event is dropped.");
1187
+ }
1188
+ queue.push({
1189
+ message
1190
+ });
1191
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
1192
+ this._events.emit(type, message);
1193
+ if (queue.length >= this.flushAt) this.flushBackground();
1194
+ if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
1195
+ });
1196
+ }
1197
+ async sendImmediate(type, _message, options) {
1198
+ if (this.disabled) return void this._logger.warn("The client is disabled");
1199
+ if (!this._isInitialized) await this._initPromise;
1200
+ if (this.optedOut) return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
1201
+ const data = {
1202
+ api_key: this.apiKey,
1203
+ batch: [
1204
+ this.prepareMessage(type, _message, options)
1205
+ ],
1206
+ sent_at: currentISOTime()
1207
+ };
1208
+ if (this.historicalMigration) data.historical_migration = true;
1209
+ const payload = JSON.stringify(data);
1210
+ const url = `${this.host}/batch/`;
1211
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1212
+ const fetchOptions = {
1213
+ method: "POST",
1214
+ headers: {
1215
+ ...this.getCustomHeaders(),
1216
+ "Content-Type": "application/json",
1217
+ ...null !== gzippedPayload && {
1218
+ "Content-Encoding": "gzip"
1219
+ }
1220
+ },
1221
+ body: gzippedPayload || payload
1222
+ };
1223
+ try {
1224
+ await this.fetchWithRetry(url, fetchOptions);
1225
+ } catch (err) {
1226
+ this._events.emit("error", err);
1227
+ }
1228
+ }
1229
+ prepareMessage(type, _message, options) {
1230
+ const message = {
1231
+ ..._message,
1232
+ type,
1233
+ library: this.getLibraryId(),
1234
+ library_version: this.getLibraryVersion(),
1235
+ timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
1236
+ uuid: options?.uuid ? options.uuid : uuidv7()
1237
+ };
1238
+ const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
1239
+ if (addGeoipDisableProperty) {
1240
+ if (!message.properties) message.properties = {};
1241
+ message["properties"]["$geoip_disable"] = true;
1242
+ }
1243
+ if (message.distinctId) {
1244
+ message.distinct_id = message.distinctId;
1245
+ delete message.distinctId;
1246
+ }
1247
+ return message;
1248
+ }
1249
+ clearFlushTimer() {
1250
+ if (this._flushTimer) {
1251
+ clearTimeout(this._flushTimer);
1252
+ this._flushTimer = void 0;
1253
+ }
1254
+ }
1255
+ flushBackground() {
1256
+ this.flush().catch(async (err) => {
1257
+ await logFlushError(err);
1258
+ });
1259
+ }
1260
+ async flush() {
1261
+ const nextFlushPromise = allSettled([
1262
+ this.flushPromise
1263
+ ]).then(() => this._flush());
1264
+ this.flushPromise = nextFlushPromise;
1265
+ this.addPendingPromise(nextFlushPromise);
1266
+ allSettled([
1267
+ nextFlushPromise
1268
+ ]).then(() => {
1269
+ if (this.flushPromise === nextFlushPromise) this.flushPromise = null;
1270
+ });
1271
+ return nextFlushPromise;
1272
+ }
1273
+ getCustomHeaders() {
1274
+ const customUserAgent = this.getCustomUserAgent();
1275
+ const headers = {};
1276
+ if (customUserAgent && "" !== customUserAgent) headers["User-Agent"] = customUserAgent;
1277
+ return headers;
1278
+ }
1279
+ async _flush() {
1280
+ this.clearFlushTimer();
1281
+ await this._initPromise;
1282
+ let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1283
+ if (!queue.length) return;
1284
+ const sentMessages = [];
1285
+ const originalQueueLength = queue.length;
1286
+ while (queue.length > 0 && sentMessages.length < originalQueueLength) {
1287
+ const batchItems = queue.slice(0, this.maxBatchSize);
1288
+ const batchMessages = batchItems.map((item) => item.message);
1289
+ const persistQueueChange = () => {
1290
+ const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1291
+ const newQueue = refreshedQueue.slice(batchItems.length);
1292
+ this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
1293
+ queue = newQueue;
1294
+ };
1295
+ const data = {
1296
+ api_key: this.apiKey,
1297
+ batch: batchMessages,
1298
+ sent_at: currentISOTime()
1299
+ };
1300
+ if (this.historicalMigration) data.historical_migration = true;
1301
+ const payload = JSON.stringify(data);
1302
+ const url = `${this.host}/batch/`;
1303
+ const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
1304
+ const fetchOptions = {
1305
+ method: "POST",
1306
+ headers: {
1307
+ ...this.getCustomHeaders(),
1308
+ "Content-Type": "application/json",
1309
+ ...null !== gzippedPayload && {
1310
+ "Content-Encoding": "gzip"
1311
+ }
1312
+ },
1313
+ body: gzippedPayload || payload
1314
+ };
1315
+ const retryOptions = {
1316
+ retryCheck: (err) => {
1317
+ if (isPostHogFetchContentTooLargeError(err)) return false;
1318
+ return isPostHogFetchError(err);
1319
+ }
1320
+ };
1321
+ try {
1322
+ await this.fetchWithRetry(url, fetchOptions, retryOptions);
1323
+ } catch (err) {
1324
+ if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
1325
+ this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
1326
+ this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);
1327
+ continue;
1328
+ }
1329
+ if (!(err instanceof PostHogFetchNetworkError)) persistQueueChange();
1330
+ this._events.emit("error", err);
1331
+ throw err;
1332
+ }
1333
+ persistQueueChange();
1334
+ sentMessages.push(...batchMessages);
1335
+ }
1336
+ this._events.emit("flush", sentMessages);
1337
+ }
1338
+ async fetchWithRetry(url, options, retryOptions, requestTimeout) {
1339
+ AbortSignal.timeout ??= function(ms) {
1340
+ const ctrl = new AbortController();
1341
+ setTimeout(() => ctrl.abort(), ms);
1342
+ return ctrl.signal;
1343
+ };
1344
+ const body = options.body ? options.body : "";
1345
+ let reqByteLength = -1;
1346
+ try {
1347
+ reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
1348
+ } catch {
1349
+ if (body instanceof Blob) reqByteLength = body.size;
1350
+ else {
1351
+ const encoded = new TextEncoder().encode(body);
1352
+ reqByteLength = encoded.length;
1353
+ }
1354
+ }
1355
+ return await retriable(async () => {
1356
+ let res = null;
1357
+ try {
1358
+ res = await this.fetch(url, {
1359
+ signal: AbortSignal.timeout(requestTimeout ?? this.requestTimeout),
1360
+ ...options
1361
+ });
1362
+ } catch (e) {
1363
+ throw new PostHogFetchNetworkError(e);
1364
+ }
1365
+ const isNoCors = "no-cors" === options.mode;
1366
+ if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);
1367
+ return res;
1368
+ }, {
1369
+ ...this._retryOptions,
1370
+ ...retryOptions
1371
+ });
1372
+ }
1373
+ async _shutdown(shutdownTimeoutMs = 3e4) {
1374
+ await this._initPromise;
1375
+ let hasTimedOut = false;
1376
+ this.clearFlushTimer();
1377
+ const doShutdown = async () => {
1378
+ try {
1379
+ await this.promiseQueue.join();
1380
+ while (true) {
1381
+ const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
1382
+ if (0 === queue.length) break;
1383
+ await this.flush();
1384
+ if (hasTimedOut) break;
1385
+ }
1386
+ } catch (e) {
1387
+ if (!isPostHogFetchError(e)) throw e;
1388
+ await logFlushError(e);
1389
+ }
1390
+ };
1391
+ return Promise.race([
1392
+ new Promise((_, reject) => {
1393
+ safeSetTimeout(() => {
1394
+ this._logger.error("Timed out while shutting down PostHog");
1395
+ hasTimedOut = true;
1396
+ reject("Timeout while shutting down PostHog. Some events may not have been sent.");
1397
+ }, shutdownTimeoutMs);
1398
+ }),
1399
+ doShutdown()
1400
+ ]);
1401
+ }
1402
+ async shutdown(shutdownTimeoutMs = 3e4) {
1403
+ if (this.shutdownPromise) 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");
1404
+ else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(() => {
1405
+ this.shutdownPromise = null;
1406
+ });
1407
+ return this.shutdownPromise;
1408
+ }
1409
+ }
1410
+ let parsedStackResults;
1411
+ let lastKeysCount;
1412
+ let cachedFilenameChunkIds;
1413
+ function getFilenameToChunkIdMap(stackParser) {
1414
+ const chunkIdMap = globalThis._posthogChunkIds;
1415
+ if (!chunkIdMap) return;
1416
+ const chunkIdKeys = Object.keys(chunkIdMap);
1417
+ if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;
1418
+ lastKeysCount = chunkIdKeys.length;
1419
+ cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey) => {
1420
+ if (!parsedStackResults) parsedStackResults = {};
1421
+ const result = parsedStackResults[stackKey];
1422
+ if (result) acc[result[0]] = result[1];
1423
+ else {
1424
+ const parsedStack = stackParser(stackKey);
1425
+ for (let i = parsedStack.length - 1; i >= 0; i--) {
1426
+ const stackFrame = parsedStack[i];
1427
+ const filename = stackFrame?.filename;
1428
+ const chunkId = chunkIdMap[stackKey];
1429
+ if (filename && chunkId) {
1430
+ acc[filename] = chunkId;
1431
+ parsedStackResults[stackKey] = [
1432
+ filename,
1433
+ chunkId
1434
+ ];
1435
+ break;
1436
+ }
1437
+ }
1438
+ }
1439
+ return acc;
1440
+ }, {});
1441
+ return cachedFilenameChunkIds;
1442
+ }
1443
+ const MAX_CAUSE_RECURSION = 4;
1444
+ class ErrorPropertiesBuilder {
1445
+ constructor(coercers, stackParser, modifiers = []) {
1446
+ this.coercers = coercers;
1447
+ this.stackParser = stackParser;
1448
+ this.modifiers = modifiers;
1449
+ }
1450
+ buildFromUnknown(input, hint = {}) {
1451
+ const providedMechanism = hint && hint.mechanism;
1452
+ const mechanism = providedMechanism || {
1453
+ handled: true,
1454
+ type: "generic"
1455
+ };
1456
+ const coercingContext = this.buildCoercingContext(mechanism, hint, 0);
1457
+ const exceptionWithCause = coercingContext.apply(input);
1458
+ const parsingContext = this.buildParsingContext();
1459
+ const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);
1460
+ const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);
1461
+ return {
1462
+ $exception_list: exceptionList,
1463
+ $exception_level: "error"
1464
+ };
1465
+ }
1466
+ async modifyFrames(exceptionList) {
1467
+ for (const exc of exceptionList) if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);
1468
+ return exceptionList;
1469
+ }
1470
+ coerceFallback(ctx) {
1471
+ return {
1472
+ type: "Error",
1473
+ value: "Unknown error",
1474
+ stack: ctx.syntheticException?.stack,
1475
+ synthetic: true
1476
+ };
1477
+ }
1478
+ parseStacktrace(err, ctx) {
1479
+ let cause;
1480
+ if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);
1481
+ let stack;
1482
+ if ("" != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? 1 : 0), ctx.chunkIdMap);
1483
+ return {
1484
+ ...err,
1485
+ cause,
1486
+ stack
1487
+ };
1488
+ }
1489
+ applyChunkIds(frames, chunkIdMap) {
1490
+ return frames.map((frame) => {
1491
+ if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];
1492
+ return frame;
1493
+ });
1494
+ }
1495
+ applyCoercers(input, ctx) {
1496
+ for (const adapter of this.coercers) if (adapter.match(input)) return adapter.coerce(input, ctx);
1497
+ return this.coerceFallback(ctx);
1498
+ }
1499
+ async applyModifiers(frames) {
1500
+ let newFrames = frames;
1501
+ for (const modifier of this.modifiers) newFrames = await modifier(newFrames);
1502
+ return newFrames;
1503
+ }
1504
+ convertToExceptionList(exceptionWithStack, mechanism) {
1505
+ const currentException = {
1506
+ type: exceptionWithStack.type,
1507
+ value: exceptionWithStack.value,
1508
+ mechanism: {
1509
+ type: mechanism.type ?? "generic",
1510
+ handled: mechanism.handled ?? true,
1511
+ synthetic: exceptionWithStack.synthetic ?? false
1512
+ }
1513
+ };
1514
+ if (exceptionWithStack.stack) currentException.stacktrace = {
1515
+ type: "raw",
1516
+ frames: exceptionWithStack.stack
1517
+ };
1518
+ const exceptionList = [
1519
+ currentException
1520
+ ];
1521
+ if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {
1522
+ ...mechanism,
1523
+ handled: true
1524
+ }));
1525
+ return exceptionList;
1526
+ }
1527
+ buildParsingContext() {
1528
+ const context = {
1529
+ chunkIdMap: getFilenameToChunkIdMap(this.stackParser)
1530
+ };
1531
+ return context;
1532
+ }
1533
+ buildCoercingContext(mechanism, hint, depth = 0) {
1534
+ const coerce = (input, depth2) => {
1535
+ if (!(depth2 <= MAX_CAUSE_RECURSION)) return;
1536
+ {
1537
+ const ctx = this.buildCoercingContext(mechanism, hint, depth2);
1538
+ return this.applyCoercers(input, ctx);
1539
+ }
1540
+ };
1541
+ const context = {
1542
+ ...hint,
1543
+ syntheticException: 0 == depth ? hint.syntheticException : void 0,
1544
+ mechanism,
1545
+ apply: (input) => coerce(input, depth),
1546
+ next: (input) => coerce(input, depth + 1)
1547
+ };
1548
+ return context;
1549
+ }
1550
+ }
1551
+ const UNKNOWN_FUNCTION = "?";
1552
+ const FILENAME_MATCH = /^\s*[-]{4,}$/;
1553
+ const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
1554
+ const nodeStackLineParser = (line, platform) => {
1555
+ const lineMatch = line.match(FULL_MATCH);
1556
+ if (lineMatch) {
1557
+ let object;
1558
+ let method;
1559
+ let functionName;
1560
+ let typeName;
1561
+ let methodName;
1562
+ if (lineMatch[1]) {
1563
+ functionName = lineMatch[1];
1564
+ let methodStart = functionName.lastIndexOf(".");
1565
+ if ("." === functionName[methodStart - 1]) methodStart--;
1566
+ if (methodStart > 0) {
1567
+ object = functionName.slice(0, methodStart);
1568
+ method = functionName.slice(methodStart + 1);
1569
+ const objectEnd = object.indexOf(".Module");
1570
+ if (objectEnd > 0) {
1571
+ functionName = functionName.slice(objectEnd + 1);
1572
+ object = object.slice(0, objectEnd);
1573
+ }
1574
+ }
1575
+ typeName = void 0;
1576
+ }
1577
+ if (method) {
1578
+ typeName = object;
1579
+ methodName = method;
1580
+ }
1581
+ if ("<anonymous>" === method) {
1582
+ methodName = void 0;
1583
+ functionName = void 0;
1584
+ }
1585
+ if (void 0 === functionName) {
1586
+ methodName = methodName || UNKNOWN_FUNCTION;
1587
+ functionName = typeName ? `${typeName}.${methodName}` : methodName;
1588
+ }
1589
+ let filename = lineMatch[2]?.startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
1590
+ const isNative = "native" === lineMatch[5];
1591
+ if (filename?.match(/\/[A-Z]:/)) filename = filename.slice(1);
1592
+ if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];
1593
+ return {
1594
+ filename: filename ? decodeURI(filename) : void 0,
1595
+ module: void 0,
1596
+ function: functionName,
1597
+ lineno: _parseIntOrUndefined(lineMatch[3]),
1598
+ colno: _parseIntOrUndefined(lineMatch[4]),
1599
+ in_app: filenameIsInApp(filename || "", isNative),
1600
+ platform
1601
+ };
1602
+ }
1603
+ if (line.match(FILENAME_MATCH)) return {
1604
+ filename: line,
1605
+ platform
1606
+ };
1607
+ };
1608
+ function filenameIsInApp(filename, isNative = false) {
1609
+ const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
1610
+ return !isInternal && void 0 !== filename && !filename.includes("node_modules/");
1611
+ }
1612
+ function _parseIntOrUndefined(input) {
1613
+ return parseInt(input || "", 10) || void 0;
1614
+ }
1615
+ const WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1616
+ const STACKTRACE_FRAME_LIMIT = 50;
1617
+ function reverseAndStripFrames(stack) {
1618
+ if (!stack.length) return [];
1619
+ const localStack = Array.from(stack);
1620
+ localStack.reverse();
1621
+ return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
1622
+ ...frame,
1623
+ filename: frame.filename || getLastStackFrame(localStack).filename,
1624
+ function: frame.function || UNKNOWN_FUNCTION
1625
+ }));
1626
+ }
1627
+ function getLastStackFrame(arr) {
1628
+ return arr[arr.length - 1] || {};
1629
+ }
1630
+ function createStackParser(platform, ...parsers) {
1631
+ return (stack, skipFirstLines = 0) => {
1632
+ const frames = [];
1633
+ const lines = stack.split("\n");
1634
+ for (let i = skipFirstLines; i < lines.length; i++) {
1635
+ const line = lines[i];
1636
+ if (line.length > 1024) continue;
1637
+ const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
1638
+ if (!cleanedLine.match(/\S*Error: /)) {
1639
+ for (const parser of parsers) {
1640
+ const frame = parser(cleanedLine, platform);
1641
+ if (frame) {
1642
+ frames.push(frame);
1643
+ break;
1644
+ }
1645
+ }
1646
+ if (frames.length >= STACKTRACE_FRAME_LIMIT) break;
1647
+ }
1648
+ }
1649
+ return reverseAndStripFrames(frames);
1650
+ };
1651
+ }
1652
+ class ErrorCoercer {
1653
+ match(err) {
1654
+ return isPlainError(err);
1655
+ }
1656
+ coerce(err, ctx) {
1657
+ return {
1658
+ type: this.getType(err),
1659
+ value: this.getMessage(err, ctx),
1660
+ stack: this.getStack(err),
1661
+ cause: err.cause ? ctx.next(err.cause) : void 0,
1662
+ synthetic: false
1663
+ };
1664
+ }
1665
+ getType(err) {
1666
+ return err.name || err.constructor.name;
1667
+ }
1668
+ getMessage(err, _ctx) {
1669
+ const message = err.message;
1670
+ if (message.error && "string" == typeof message.error.message) return String(message.error.message);
1671
+ return String(message);
1672
+ }
1673
+ getStack(err) {
1674
+ return err.stacktrace || err.stack || void 0;
1675
+ }
1676
+ }
1677
+ const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1678
+ class StringCoercer {
1679
+ match(input) {
1680
+ return "string" == typeof input;
1681
+ }
1682
+ coerce(input, ctx) {
1683
+ const [type, value] = this.getInfos(input);
1684
+ return {
1685
+ type: type ?? "Error",
1686
+ value: value ?? input,
1687
+ stack: ctx.syntheticException?.stack,
1688
+ synthetic: true
1689
+ };
1690
+ }
1691
+ getInfos(candidate) {
1692
+ let type = "Error";
1693
+ let value = candidate;
1694
+ const groups = candidate.match(ERROR_TYPES_PATTERN);
1695
+ if (groups) {
1696
+ type = groups[1];
1697
+ value = groups[2];
1698
+ }
1699
+ return [
1700
+ type,
1701
+ value
1702
+ ];
1703
+ }
1704
+ }
1705
+ const severityLevels = [
1706
+ "fatal",
1707
+ "error",
1708
+ "warning",
1709
+ "log",
1710
+ "info",
1711
+ "debug"
1712
+ ];
1713
+ function extractExceptionKeysForMessage(err, maxLength = 40) {
1714
+ const keys = Object.keys(err);
1715
+ keys.sort();
1716
+ if (!keys.length) return "[object has no keys]";
1717
+ for (let i = keys.length; i > 0; i--) {
1718
+ const serialized = keys.slice(0, i).join(", ");
1719
+ if (!(serialized.length > maxLength)) {
1720
+ if (i === keys.length) return serialized;
1721
+ return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;
1722
+ }
1723
+ }
1724
+ return "";
1725
+ }
1726
+ class ObjectCoercer {
1727
+ match(candidate) {
1728
+ return "object" == typeof candidate && null !== candidate;
1729
+ }
1730
+ coerce(candidate, ctx) {
1731
+ const errorProperty = this.getErrorPropertyFromObject(candidate);
1732
+ if (errorProperty) return ctx.apply(errorProperty);
1733
+ return {
1734
+ type: this.getType(candidate),
1735
+ value: this.getValue(candidate),
1736
+ stack: ctx.syntheticException?.stack,
1737
+ level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1738
+ synthetic: true
1739
+ };
1740
+ }
1741
+ getType(err) {
1742
+ return isEvent(err) ? err.constructor.name : "Error";
1743
+ }
1744
+ getValue(err) {
1745
+ if ("name" in err && "string" == typeof err.name) {
1746
+ let message = `'${err.name}' captured as exception`;
1747
+ if ("message" in err && "string" == typeof err.message) message += ` with message: '${err.message}'`;
1748
+ return message;
1749
+ }
1750
+ if ("message" in err && "string" == typeof err.message) return err.message;
1751
+ const className = this.getObjectClassName(err);
1752
+ const keys = extractExceptionKeysForMessage(err);
1753
+ return `${className && "Object" !== className ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
1754
+ }
1755
+ isSeverityLevel(x) {
1756
+ return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1757
+ }
1758
+ getErrorPropertyFromObject(obj) {
1759
+ for (const prop in obj) if (Object.prototype.hasOwnProperty.call(obj, prop)) {
1760
+ const value = obj[prop];
1761
+ if (isError(value)) return value;
1762
+ }
1763
+ }
1764
+ getObjectClassName(obj) {
1765
+ try {
1766
+ const prototype = Object.getPrototypeOf(obj);
1767
+ return prototype ? prototype.constructor.name : void 0;
1768
+ } catch (e) {
1769
+ return;
1770
+ }
1771
+ }
1772
+ }
1773
+ class EventCoercer {
1774
+ match(err) {
1775
+ return isEvent(err);
1776
+ }
1777
+ coerce(evt, ctx) {
1778
+ const constructorName = evt.constructor.name;
1779
+ return {
1780
+ type: constructorName,
1781
+ value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,
1782
+ stack: ctx.syntheticException?.stack,
1783
+ synthetic: true
1784
+ };
1785
+ }
1786
+ }
1787
+ class PrimitiveCoercer {
1788
+ match(candidate) {
1789
+ return isPrimitive(candidate);
1790
+ }
1791
+ coerce(value, ctx) {
1792
+ return {
1793
+ type: "Error",
1794
+ value: `Primitive value captured as exception: ${String(value)}`,
1795
+ stack: ctx.syntheticException?.stack,
1796
+ synthetic: true
1797
+ };
1798
+ }
1799
+ }
1800
+ class ReduceableCache {
1801
+ constructor(_maxSize) {
1802
+ this._maxSize = _maxSize;
1803
+ this._cache = /* @__PURE__ */ new Map();
1804
+ }
1805
+ get(key) {
1806
+ const value = this._cache.get(key);
1807
+ if (void 0 === value) return;
1808
+ this._cache.delete(key);
1809
+ this._cache.set(key, value);
1810
+ return value;
1811
+ }
1812
+ set(key, value) {
1813
+ this._cache.set(key, value);
1814
+ }
1815
+ reduce() {
1816
+ while (this._cache.size >= this._maxSize) {
1817
+ const value = this._cache.keys().next().value;
1818
+ if (value) this._cache.delete(value);
1819
+ }
1820
+ }
1821
+ }
1822
+ const LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
1823
+ const LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
1824
+ const DEFAULT_LINES_OF_CONTEXT = 7;
1825
+ const MAX_CONTEXTLINES_COLNO = 1e3;
1826
+ const MAX_CONTEXTLINES_LINENO = 1e4;
1827
+ async function addSourceContext(frames) {
1828
+ const filesToLines = {};
1829
+ for (let i = frames.length - 1; i >= 0; i--) {
1830
+ const frame = frames[i];
1831
+ const filename = frame?.filename;
1832
+ if (!frame || "string" != typeof filename || "number" != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;
1833
+ const filesToLinesOutput = filesToLines[filename];
1834
+ if (!filesToLinesOutput) filesToLines[filename] = [];
1835
+ filesToLines[filename].push(frame.lineno);
1836
+ }
1837
+ const files = Object.keys(filesToLines);
1838
+ if (0 == files.length) return frames;
1839
+ const readlinePromises = [];
1840
+ for (const file of files) {
1841
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) continue;
1842
+ const filesToLineRanges = filesToLines[file];
1843
+ if (!filesToLineRanges) continue;
1844
+ filesToLineRanges.sort((a, b) => a - b);
1845
+ const ranges = makeLineReaderRanges(filesToLineRanges);
1846
+ if (ranges.every((r) => rangeExistsInContentCache(file, r))) continue;
1847
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
1848
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
1849
+ }
1850
+ await Promise.all(readlinePromises).catch(() => {
1851
+ });
1852
+ if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
1853
+ LRU_FILE_CONTENTS_CACHE.reduce();
1854
+ return frames;
1855
+ }
1856
+ function getContextLinesFromFile(path, ranges, output) {
1857
+ return new Promise((resolve) => {
1858
+ const stream = createReadStream(path);
1859
+ const lineReaded = createInterface({
1860
+ input: stream
1861
+ });
1862
+ function destroyStreamAndResolve() {
1863
+ stream.destroy();
1864
+ resolve();
1865
+ }
1866
+ let lineNumber = 0;
1867
+ let currentRangeIndex = 0;
1868
+ const range = ranges[currentRangeIndex];
1869
+ if (void 0 === range) return void destroyStreamAndResolve();
1870
+ let rangeStart = range[0];
1871
+ let rangeEnd = range[1];
1872
+ function onStreamError() {
1873
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
1874
+ lineReaded.close();
1875
+ lineReaded.removeAllListeners();
1876
+ destroyStreamAndResolve();
1877
+ }
1878
+ stream.on("error", onStreamError);
1879
+ lineReaded.on("error", onStreamError);
1880
+ lineReaded.on("close", destroyStreamAndResolve);
1881
+ lineReaded.on("line", (line) => {
1882
+ lineNumber++;
1883
+ if (lineNumber < rangeStart) return;
1884
+ output[lineNumber] = snipLine(line, 0);
1885
+ if (lineNumber >= rangeEnd) {
1886
+ if (currentRangeIndex === ranges.length - 1) {
1887
+ lineReaded.close();
1888
+ lineReaded.removeAllListeners();
1889
+ return;
1890
+ }
1891
+ currentRangeIndex++;
1892
+ const range2 = ranges[currentRangeIndex];
1893
+ if (void 0 === range2) {
1894
+ lineReaded.close();
1895
+ lineReaded.removeAllListeners();
1896
+ return;
1897
+ }
1898
+ rangeStart = range2[0];
1899
+ rangeEnd = range2[1];
1900
+ }
1901
+ });
1902
+ });
1903
+ }
1904
+ function addSourceContextToFrames(frames, cache) {
1905
+ for (const frame of frames) if (frame.filename && void 0 === frame.context_line && "number" == typeof frame.lineno) {
1906
+ const contents = cache.get(frame.filename);
1907
+ if (void 0 === contents) continue;
1908
+ addContextToFrame(frame.lineno, frame, contents);
1909
+ }
1910
+ }
1911
+ function addContextToFrame(lineno, frame, contents) {
1912
+ if (void 0 === frame.lineno || void 0 === contents) return;
1913
+ frame.pre_context = [];
1914
+ for (let i = makeRangeStart(lineno); i < lineno; i++) {
1915
+ const line = contents[i];
1916
+ if (void 0 === line) return void clearLineContext(frame);
1917
+ frame.pre_context.push(line);
1918
+ }
1919
+ if (void 0 === contents[lineno]) return void clearLineContext(frame);
1920
+ frame.context_line = contents[lineno];
1921
+ const end = makeRangeEnd(lineno);
1922
+ frame.post_context = [];
1923
+ for (let i = lineno + 1; i <= end; i++) {
1924
+ const line = contents[i];
1925
+ if (void 0 === line) break;
1926
+ frame.post_context.push(line);
1927
+ }
1928
+ }
1929
+ function clearLineContext(frame) {
1930
+ delete frame.pre_context;
1931
+ delete frame.context_line;
1932
+ delete frame.post_context;
1933
+ }
1934
+ function shouldSkipContextLinesForFile(path) {
1935
+ return path.startsWith("node:") || path.endsWith(".min.js") || path.endsWith(".min.cjs") || path.endsWith(".min.mjs") || path.startsWith("data:");
1936
+ }
1937
+ function shouldSkipContextLinesForFrame(frame) {
1938
+ if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;
1939
+ if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;
1940
+ return false;
1941
+ }
1942
+ function rangeExistsInContentCache(file, range) {
1943
+ const contents = LRU_FILE_CONTENTS_CACHE.get(file);
1944
+ if (void 0 === contents) return false;
1945
+ for (let i = range[0]; i <= range[1]; i++) if (void 0 === contents[i]) return false;
1946
+ return true;
1947
+ }
1948
+ function makeLineReaderRanges(lines) {
1949
+ if (!lines.length) return [];
1950
+ let i = 0;
1951
+ const line = lines[0];
1952
+ if ("number" != typeof line) return [];
1953
+ let current = makeContextRange(line);
1954
+ const out = [];
1955
+ while (true) {
1956
+ if (i === lines.length - 1) {
1957
+ out.push(current);
1958
+ break;
1959
+ }
1960
+ const next = lines[i + 1];
1961
+ if ("number" != typeof next) break;
1962
+ if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;
1963
+ else {
1964
+ out.push(current);
1965
+ current = makeContextRange(next);
1966
+ }
1967
+ i++;
1968
+ }
1969
+ return out;
1970
+ }
1971
+ function makeContextRange(line) {
1972
+ return [
1973
+ makeRangeStart(line),
1974
+ makeRangeEnd(line)
1975
+ ];
1976
+ }
1977
+ function makeRangeStart(line) {
1978
+ return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);
1979
+ }
1980
+ function makeRangeEnd(line) {
1981
+ return line + DEFAULT_LINES_OF_CONTEXT;
1982
+ }
1983
+ function emplace(map, key, contents) {
1984
+ const value = map.get(key);
1985
+ if (void 0 === value) {
1986
+ map.set(key, contents);
1987
+ return contents;
1988
+ }
1989
+ return value;
1990
+ }
1991
+ function snipLine(line, colno) {
1992
+ let newLine = line;
1993
+ const lineLength = newLine.length;
1994
+ if (lineLength <= 150) return newLine;
1995
+ if (colno > lineLength) colno = lineLength;
1996
+ let start = Math.max(colno - 60, 0);
1997
+ if (start < 5) start = 0;
1998
+ let end = Math.min(start + 140, lineLength);
1999
+ if (end > lineLength - 5) end = lineLength;
2000
+ if (end === lineLength) start = Math.max(end - 140, 0);
2001
+ newLine = newLine.slice(start, end);
2002
+ if (start > 0) newLine = `...${newLine}`;
2003
+ if (end < lineLength) newLine += "...";
2004
+ return newLine;
2005
+ }
2006
+ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
2007
+ let calledFatalError = false;
2008
+ return Object.assign((error) => {
2009
+ const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => "domainUncaughtExceptionClear" !== listener.name && true !== listener._posthogErrorHandler).length;
2010
+ const processWouldExit = 0 === userProvidedListenersCount;
2011
+ captureFn(error, {
2012
+ mechanism: {
2013
+ type: "onuncaughtexception",
2014
+ handled: false
2015
+ }
2016
+ });
2017
+ if (!calledFatalError && processWouldExit) {
2018
+ calledFatalError = true;
2019
+ onFatalFn(error);
2020
+ }
2021
+ }, {
2022
+ _posthogErrorHandler: true
2023
+ });
2024
+ }
2025
+ function addUncaughtExceptionListener(captureFn, onFatalFn) {
2026
+ globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
2027
+ }
2028
+ function addUnhandledRejectionListener(captureFn) {
2029
+ globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
2030
+ mechanism: {
2031
+ type: "onunhandledrejection",
2032
+ handled: false
2033
+ }
2034
+ }));
2035
+ }
2036
+ const SHUTDOWN_TIMEOUT = 2e3;
2037
+ class ErrorTracking {
2038
+ constructor(client2, options, _logger) {
2039
+ this.client = client2;
2040
+ this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
2041
+ this._logger = _logger;
2042
+ this._rateLimiter = new BucketedRateLimiter({
2043
+ refillRate: 1,
2044
+ bucketSize: 10,
2045
+ refillInterval: 1e4,
2046
+ _logger: this._logger
2047
+ });
2048
+ this.startAutocaptureIfEnabled();
2049
+ }
2050
+ static async buildEventMessage(error, hint, distinctId, additionalProperties) {
2051
+ const properties = {
2052
+ ...additionalProperties
2053
+ };
2054
+ if (!distinctId) properties.$process_person_profile = false;
2055
+ const exceptionProperties = this.errorPropertiesBuilder.buildFromUnknown(error, hint);
2056
+ exceptionProperties.$exception_list = await this.errorPropertiesBuilder.modifyFrames(exceptionProperties.$exception_list);
2057
+ return {
2058
+ event: "$exception",
2059
+ distinctId: distinctId || uuidv7(),
2060
+ properties: {
2061
+ ...exceptionProperties,
2062
+ ...properties
2063
+ }
2064
+ };
2065
+ }
2066
+ startAutocaptureIfEnabled() {
2067
+ if (this.isEnabled()) {
2068
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
2069
+ addUnhandledRejectionListener(this.onException.bind(this));
2070
+ }
2071
+ }
2072
+ onException(exception, hint) {
2073
+ this.client.addPendingPromise((async () => {
2074
+ const eventMessage = await ErrorTracking.buildEventMessage(exception, hint);
2075
+ const exceptionProperties = eventMessage.properties;
2076
+ const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
2077
+ const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
2078
+ if (isRateLimited) return void this._logger.info("Skipping exception capture because of client rate limiting.", {
2079
+ exception: exceptionType
2080
+ });
2081
+ return this.client.capture(eventMessage);
2082
+ })());
2083
+ }
2084
+ async onFatalError(exception) {
2085
+ console.error(exception);
2086
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
2087
+ process.exit(1);
2088
+ }
2089
+ isEnabled() {
2090
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
2091
+ }
2092
+ shutdown() {
2093
+ this._rateLimiter.stop();
2094
+ }
2095
+ }
2096
+ const version = "5.17.2";
2097
+ async function hashSHA1(text) {
2098
+ const subtle = globalThis.crypto?.subtle;
2099
+ if (!subtle) throw new Error("SubtleCrypto API not available");
2100
+ const hashBuffer = await subtle.digest("SHA-1", new TextEncoder().encode(text));
2101
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
2102
+ return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
2103
+ }
2104
+ const SIXTY_SECONDS = 6e4;
2105
+ const LONG_SCALE = 1152921504606847e3;
2106
+ const NULL_VALUES_ALLOWED_OPERATORS = [
2107
+ "is_not"
2108
+ ];
2109
+ class ClientError extends Error {
2110
+ constructor(message) {
2111
+ super();
2112
+ Error.captureStackTrace(this, this.constructor);
2113
+ this.name = "ClientError";
2114
+ this.message = message;
2115
+ Object.setPrototypeOf(this, ClientError.prototype);
2116
+ }
2117
+ }
2118
+ class InconclusiveMatchError extends Error {
2119
+ constructor(message) {
2120
+ super(message);
2121
+ this.name = this.constructor.name;
2122
+ Error.captureStackTrace(this, this.constructor);
2123
+ Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
2124
+ }
2125
+ }
2126
+ class RequiresServerEvaluation extends Error {
2127
+ constructor(message) {
2128
+ super(message);
2129
+ this.name = this.constructor.name;
2130
+ Error.captureStackTrace(this, this.constructor);
2131
+ Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
2132
+ }
2133
+ }
2134
+ class FeatureFlagsPoller {
2135
+ constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }) {
2136
+ this.debugMode = false;
2137
+ this.shouldBeginExponentialBackoff = false;
2138
+ this.backOffCount = 0;
2139
+ this.pollingInterval = pollingInterval;
2140
+ this.personalApiKey = personalApiKey;
2141
+ this.featureFlags = [];
2142
+ this.featureFlagsByKey = {};
2143
+ this.groupTypeMapping = {};
2144
+ this.cohorts = {};
2145
+ this.loadedSuccessfullyOnce = false;
2146
+ this.timeout = timeout;
2147
+ this.projectApiKey = projectApiKey;
2148
+ this.host = host;
2149
+ this.poller = void 0;
2150
+ this.fetch = options.fetch || fetch;
2151
+ this.onError = options.onError;
2152
+ this.customHeaders = customHeaders;
2153
+ this.onLoad = options.onLoad;
2154
+ this.cacheProvider = options.cacheProvider;
2155
+ this.loadFeatureFlags();
2156
+ }
2157
+ debug(enabled = true) {
2158
+ this.debugMode = enabled;
2159
+ }
2160
+ logMsgIfDebug(fn) {
2161
+ if (this.debugMode) fn();
2162
+ }
2163
+ async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {
2164
+ await this.loadFeatureFlags();
2165
+ let response;
2166
+ let featureFlag;
2167
+ if (!this.loadedSuccessfullyOnce) return response;
2168
+ featureFlag = this.featureFlagsByKey[key];
2169
+ if (void 0 !== featureFlag) try {
2170
+ const result = await this.computeFlagAndPayloadLocally(featureFlag, distinctId, groups, personProperties, groupProperties);
2171
+ response = result.value;
2172
+ this.logMsgIfDebug(() => console.debug(`Successfully computed flag locally: ${key} -> ${response}`));
2173
+ } catch (e) {
2174
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));
2175
+ else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));
2176
+ }
2177
+ return response;
2178
+ }
2179
+ async getAllFlagsAndPayloads(distinctId, groups = {}, personProperties = {}, groupProperties = {}, flagKeysToExplicitlyEvaluate) {
2180
+ await this.loadFeatureFlags();
2181
+ const response = {};
2182
+ const payloads = {};
2183
+ let fallbackToFlags = 0 == this.featureFlags.length;
2184
+ const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key) => this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;
2185
+ const sharedEvaluationCache = {};
2186
+ await Promise.all(flagsToEvaluate.map(async (flag) => {
2187
+ try {
2188
+ const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, distinctId, groups, personProperties, groupProperties, void 0, sharedEvaluationCache);
2189
+ response[flag.key] = matchValue;
2190
+ if (matchPayload) payloads[flag.key] = matchPayload;
2191
+ } catch (e) {
2192
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(() => console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));
2193
+ else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));
2194
+ fallbackToFlags = true;
2195
+ }
2196
+ }));
2197
+ return {
2198
+ response,
2199
+ payloads,
2200
+ fallbackToFlags
2201
+ };
2202
+ }
2203
+ async computeFlagAndPayloadLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}, matchValue, evaluationCache, skipLoadCheck = false) {
2204
+ if (!skipLoadCheck) await this.loadFeatureFlags();
2205
+ if (!this.loadedSuccessfullyOnce) return {
2206
+ value: false,
2207
+ payload: null
2208
+ };
2209
+ let flagValue;
2210
+ flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, distinctId, groups, personProperties, groupProperties, evaluationCache);
2211
+ const payload = this.getFeatureFlagPayload(flag.key, flagValue);
2212
+ return {
2213
+ value: flagValue,
2214
+ payload
2215
+ };
2216
+ }
2217
+ async computeFlagValueLocally(flag, distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {
2218
+ if (flag.ensure_experience_continuity) throw new InconclusiveMatchError("Flag has experience continuity enabled");
2219
+ if (!flag.active) return false;
2220
+ const flagFilters = flag.filters || {};
2221
+ const aggregation_group_type_index = flagFilters.aggregation_group_type_index;
2222
+ if (void 0 == aggregation_group_type_index) return await this.matchFeatureFlagProperties(flag, distinctId, personProperties, evaluationCache);
2223
+ {
2224
+ const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];
2225
+ if (!groupName) {
2226
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));
2227
+ throw new InconclusiveMatchError("Flag has unknown group type index");
2228
+ }
2229
+ if (!(groupName in groups)) {
2230
+ this.logMsgIfDebug(() => console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));
2231
+ return false;
2232
+ }
2233
+ const focusedGroupProperties = groupProperties[groupName];
2234
+ return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationCache);
2235
+ }
2236
+ }
2237
+ getFeatureFlagPayload(key, flagValue) {
2238
+ let payload = null;
2239
+ if (false !== flagValue && null != flagValue) {
2240
+ if ("boolean" == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;
2241
+ else if ("string" == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;
2242
+ if (null != payload) {
2243
+ if ("object" == typeof payload) return payload;
2244
+ if ("string" == typeof payload) try {
2245
+ return JSON.parse(payload);
2246
+ } catch {
2247
+ }
2248
+ return payload;
2249
+ }
2250
+ }
2251
+ return null;
2252
+ }
2253
+ async evaluateFlagDependency(property, distinctId, properties, evaluationCache) {
2254
+ const targetFlagKey = property.key;
2255
+ if (!this.featureFlagsByKey) throw new InconclusiveMatchError("Feature flags not available for dependency evaluation");
2256
+ if (!("dependency_chain" in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);
2257
+ const dependencyChain = property.dependency_chain;
2258
+ if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);
2259
+ if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);
2260
+ for (const depFlagKey of dependencyChain) {
2261
+ if (!(depFlagKey in evaluationCache)) {
2262
+ const depFlag = this.featureFlagsByKey[depFlagKey];
2263
+ if (depFlag) if (depFlag.active) try {
2264
+ const depResult = await this.matchFeatureFlagProperties(depFlag, distinctId, properties, evaluationCache);
2265
+ evaluationCache[depFlagKey] = depResult;
2266
+ } catch (error) {
2267
+ throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);
2268
+ }
2269
+ else evaluationCache[depFlagKey] = false;
2270
+ else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);
2271
+ }
2272
+ const cachedResult = evaluationCache[depFlagKey];
2273
+ if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);
2274
+ }
2275
+ const targetFlagValue = evaluationCache[targetFlagKey];
2276
+ return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);
2277
+ }
2278
+ flagEvaluatesToExpectedValue(expectedValue, flagValue) {
2279
+ if ("boolean" == typeof expectedValue) return expectedValue === flagValue || "string" == typeof flagValue && "" !== flagValue && true === expectedValue;
2280
+ if ("string" == typeof expectedValue) return flagValue === expectedValue;
2281
+ return false;
2282
+ }
2283
+ async matchFeatureFlagProperties(flag, distinctId, properties, evaluationCache = {}) {
2284
+ const flagFilters = flag.filters || {};
2285
+ const flagConditions = flagFilters.groups || [];
2286
+ let isInconclusive = false;
2287
+ let result;
2288
+ for (const condition of flagConditions) try {
2289
+ if (await this.isConditionMatch(flag, distinctId, condition, properties, evaluationCache)) {
2290
+ const variantOverride = condition.variant;
2291
+ const flagVariants = flagFilters.multivariate?.variants || [];
2292
+ result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, distinctId) || true;
2293
+ break;
2294
+ }
2295
+ } catch (e) {
2296
+ if (e instanceof RequiresServerEvaluation) throw e;
2297
+ if (e instanceof InconclusiveMatchError) isInconclusive = true;
2298
+ else throw e;
2299
+ }
2300
+ if (void 0 !== result) return result;
2301
+ if (isInconclusive) throw new InconclusiveMatchError("Can't determine if feature flag is enabled or not with given properties");
2302
+ return false;
2303
+ }
2304
+ async isConditionMatch(flag, distinctId, condition, properties, evaluationCache = {}) {
2305
+ const rolloutPercentage = condition.rollout_percentage;
2306
+ const warnFunction = (msg) => {
2307
+ this.logMsgIfDebug(() => console.warn(msg));
2308
+ };
2309
+ if ((condition.properties || []).length > 0) {
2310
+ for (const prop of condition.properties) {
2311
+ const propertyType = prop.type;
2312
+ let matches = false;
2313
+ matches = "cohort" === propertyType ? matchCohort(prop, properties, this.cohorts, this.debugMode) : "flag" === propertyType ? await this.evaluateFlagDependency(prop, distinctId, properties, evaluationCache) : matchProperty(prop, properties, warnFunction);
2314
+ if (!matches) return false;
2315
+ }
2316
+ if (void 0 == rolloutPercentage) return true;
2317
+ }
2318
+ if (void 0 != rolloutPercentage && await _hash(flag.key, distinctId) > rolloutPercentage / 100) return false;
2319
+ return true;
2320
+ }
2321
+ async getMatchingVariant(flag, distinctId) {
2322
+ const hashValue = await _hash(flag.key, distinctId, "variant");
2323
+ const matchingVariant = this.variantLookupTable(flag).find((variant) => hashValue >= variant.valueMin && hashValue < variant.valueMax);
2324
+ if (matchingVariant) return matchingVariant.key;
2325
+ }
2326
+ variantLookupTable(flag) {
2327
+ const lookupTable = [];
2328
+ let valueMin = 0;
2329
+ let valueMax = 0;
2330
+ const flagFilters = flag.filters || {};
2331
+ const multivariates = flagFilters.multivariate?.variants || [];
2332
+ multivariates.forEach((variant) => {
2333
+ valueMax = valueMin + variant.rollout_percentage / 100;
2334
+ lookupTable.push({
2335
+ valueMin,
2336
+ valueMax,
2337
+ key: variant.key
2338
+ });
2339
+ valueMin = valueMax;
2340
+ });
2341
+ return lookupTable;
2342
+ }
2343
+ updateFlagState(flagData) {
2344
+ this.featureFlags = flagData.flags;
2345
+ this.featureFlagsByKey = flagData.flags.reduce((acc, curr) => (acc[curr.key] = curr, acc), {});
2346
+ this.groupTypeMapping = flagData.groupTypeMapping;
2347
+ this.cohorts = flagData.cohorts;
2348
+ this.loadedSuccessfullyOnce = true;
2349
+ }
2350
+ async loadFromCache(debugMessage) {
2351
+ if (!this.cacheProvider) return false;
2352
+ try {
2353
+ const cached = await this.cacheProvider.getFlagDefinitions();
2354
+ if (cached) {
2355
+ this.updateFlagState(cached);
2356
+ this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));
2357
+ this.onLoad?.(this.featureFlags.length);
2358
+ return true;
2359
+ }
2360
+ return false;
2361
+ } catch (err) {
2362
+ this.onError?.(new Error(`Failed to load from cache: ${err}`));
2363
+ return false;
2364
+ }
2365
+ }
2366
+ async loadFeatureFlags(forceReload = false) {
2367
+ if (this.loadedSuccessfullyOnce && !forceReload) return;
2368
+ if (!this.loadingPromise) this.loadingPromise = this._loadFeatureFlags().catch((err) => this.logMsgIfDebug(() => console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(() => {
2369
+ this.loadingPromise = void 0;
2370
+ });
2371
+ return this.loadingPromise;
2372
+ }
2373
+ isLocalEvaluationReady() {
2374
+ return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;
2375
+ }
2376
+ getPollingInterval() {
2377
+ if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;
2378
+ return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);
2379
+ }
2380
+ async _loadFeatureFlags() {
2381
+ if (this.poller) {
2382
+ clearTimeout(this.poller);
2383
+ this.poller = void 0;
2384
+ }
2385
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
2386
+ try {
2387
+ let shouldFetch = true;
2388
+ if (this.cacheProvider) try {
2389
+ shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();
2390
+ } catch (err) {
2391
+ this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));
2392
+ }
2393
+ if (!shouldFetch) {
2394
+ const loaded = await this.loadFromCache("Loaded flags from cache (skipped fetch)");
2395
+ if (loaded) return;
2396
+ if (this.loadedSuccessfullyOnce) return;
2397
+ }
2398
+ const res = await this._requestFeatureFlagDefinitions();
2399
+ if (!res) return;
2400
+ switch (res.status) {
2401
+ case 304:
2402
+ this.logMsgIfDebug(() => console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data"));
2403
+ this.flagsEtag = res.headers?.get("ETag") ?? this.flagsEtag;
2404
+ this.loadedSuccessfullyOnce = true;
2405
+ this.shouldBeginExponentialBackoff = false;
2406
+ this.backOffCount = 0;
2407
+ return;
2408
+ case 401:
2409
+ this.shouldBeginExponentialBackoff = true;
2410
+ this.backOffCount += 1;
2411
+ 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`);
2412
+ case 402:
2413
+ 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");
2414
+ this.featureFlags = [];
2415
+ this.featureFlagsByKey = {};
2416
+ this.groupTypeMapping = {};
2417
+ this.cohorts = {};
2418
+ return;
2419
+ case 403:
2420
+ this.shouldBeginExponentialBackoff = true;
2421
+ this.backOffCount += 1;
2422
+ 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`);
2423
+ case 429:
2424
+ this.shouldBeginExponentialBackoff = true;
2425
+ this.backOffCount += 1;
2426
+ 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`);
2427
+ case 200: {
2428
+ const responseJson = await res.json() ?? {};
2429
+ if (!("flags" in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));
2430
+ this.flagsEtag = res.headers?.get("ETag") ?? void 0;
2431
+ const flagData = {
2432
+ flags: responseJson.flags ?? [],
2433
+ groupTypeMapping: responseJson.group_type_mapping || {},
2434
+ cohorts: responseJson.cohorts || {}
2435
+ };
2436
+ this.updateFlagState(flagData);
2437
+ this.shouldBeginExponentialBackoff = false;
2438
+ this.backOffCount = 0;
2439
+ if (this.cacheProvider && shouldFetch) try {
2440
+ await this.cacheProvider.onFlagDefinitionsReceived(flagData);
2441
+ } catch (err) {
2442
+ this.onError?.(new Error(`Failed to store in cache: ${err}`));
2443
+ }
2444
+ this.onLoad?.(this.featureFlags.length);
2445
+ break;
2446
+ }
2447
+ default:
2448
+ return;
2449
+ }
2450
+ } catch (err) {
2451
+ if (err instanceof ClientError) this.onError?.(err);
2452
+ }
2453
+ }
2454
+ getPersonalApiKeyRequestOptions(method = "GET", etag) {
2455
+ const headers = {
2456
+ ...this.customHeaders,
2457
+ "Content-Type": "application/json",
2458
+ Authorization: `Bearer ${this.personalApiKey}`
2459
+ };
2460
+ if (etag) headers["If-None-Match"] = etag;
2461
+ return {
2462
+ method,
2463
+ headers
2464
+ };
2465
+ }
2466
+ _requestFeatureFlagDefinitions() {
2467
+ const url = `${this.host}/api/feature_flag/local_evaluation?token=${this.projectApiKey}&send_cohorts`;
2468
+ const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
2469
+ let abortTimeout = null;
2470
+ if (this.timeout && "number" == typeof this.timeout) {
2471
+ const controller = new AbortController();
2472
+ abortTimeout = safeSetTimeout(() => {
2473
+ controller.abort();
2474
+ }, this.timeout);
2475
+ options.signal = controller.signal;
2476
+ }
2477
+ try {
2478
+ const fetch1 = this.fetch;
2479
+ return fetch1(url, options);
2480
+ } finally {
2481
+ clearTimeout(abortTimeout);
2482
+ }
2483
+ }
2484
+ async stopPoller(timeoutMs = 3e4) {
2485
+ clearTimeout(this.poller);
2486
+ if (this.cacheProvider) try {
2487
+ const shutdownResult = this.cacheProvider.shutdown();
2488
+ if (shutdownResult instanceof Promise) await Promise.race([
2489
+ shutdownResult,
2490
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
2491
+ ]);
2492
+ } catch (err) {
2493
+ this.onError?.(new Error(`Error during cache shutdown: ${err}`));
2494
+ }
2495
+ }
2496
+ }
2497
+ async function _hash(key, distinctId, salt = "") {
2498
+ const hashString = await hashSHA1(`${key}.${distinctId}${salt}`);
2499
+ return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;
2500
+ }
2501
+ function matchProperty(property, propertyValues, warnFunction) {
2502
+ const key = property.key;
2503
+ const value = property.value;
2504
+ const operator = property.operator || "exact";
2505
+ if (key in propertyValues) {
2506
+ if ("is_not_set" === operator) throw new InconclusiveMatchError("Operator is_not_set is not supported");
2507
+ } else throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);
2508
+ const overrideValue = propertyValues[key];
2509
+ if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {
2510
+ if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
2511
+ return false;
2512
+ }
2513
+ function computeExactMatch(value2, overrideValue2) {
2514
+ if (Array.isArray(value2)) return value2.map((val) => String(val).toLowerCase()).includes(String(overrideValue2).toLowerCase());
2515
+ return String(value2).toLowerCase() === String(overrideValue2).toLowerCase();
2516
+ }
2517
+ function compare(lhs, rhs, operator2) {
2518
+ if ("gt" === operator2) return lhs > rhs;
2519
+ if ("gte" === operator2) return lhs >= rhs;
2520
+ if ("lt" === operator2) return lhs < rhs;
2521
+ if ("lte" === operator2) return lhs <= rhs;
2522
+ throw new Error(`Invalid operator: ${operator2}`);
2523
+ }
2524
+ switch (operator) {
2525
+ case "exact":
2526
+ return computeExactMatch(value, overrideValue);
2527
+ case "is_not":
2528
+ return !computeExactMatch(value, overrideValue);
2529
+ case "is_set":
2530
+ return key in propertyValues;
2531
+ case "icontains":
2532
+ return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2533
+ case "not_icontains":
2534
+ return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
2535
+ case "regex":
2536
+ return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));
2537
+ case "not_regex":
2538
+ return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));
2539
+ case "gt":
2540
+ case "gte":
2541
+ case "lt":
2542
+ case "lte": {
2543
+ let parsedValue = "number" == typeof value ? value : null;
2544
+ if ("string" == typeof value) try {
2545
+ parsedValue = parseFloat(value);
2546
+ } catch (err) {
2547
+ }
2548
+ if (null == parsedValue || null == overrideValue) return compare(String(overrideValue), String(value), operator);
2549
+ if ("string" == typeof overrideValue) return compare(overrideValue, String(value), operator);
2550
+ return compare(overrideValue, parsedValue, operator);
2551
+ }
2552
+ case "is_date_after":
2553
+ case "is_date_before": {
2554
+ if ("boolean" == typeof value) throw new InconclusiveMatchError("Date operations cannot be performed on boolean values");
2555
+ let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));
2556
+ if (null == parsedDate) parsedDate = convertToDateTime(value);
2557
+ if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);
2558
+ const overrideDate = convertToDateTime(overrideValue);
2559
+ if ([
2560
+ "is_date_before"
2561
+ ].includes(operator)) return overrideDate < parsedDate;
2562
+ return overrideDate > parsedDate;
2563
+ }
2564
+ default:
2565
+ throw new InconclusiveMatchError(`Unknown operator: ${operator}`);
2566
+ }
2567
+ }
2568
+ function checkCohortExists(cohortId, cohortProperties) {
2569
+ if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);
2570
+ }
2571
+ function matchCohort(property, propertyValues, cohortProperties, debugMode = false) {
2572
+ const cohortId = String(property.value);
2573
+ checkCohortExists(cohortId, cohortProperties);
2574
+ const propertyGroup = cohortProperties[cohortId];
2575
+ return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode);
2576
+ }
2577
+ function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false) {
2578
+ if (!propertyGroup) return true;
2579
+ const propertyGroupType = propertyGroup.type;
2580
+ const properties = propertyGroup.values;
2581
+ if (!properties || 0 === properties.length) return true;
2582
+ let errorMatchingLocally = false;
2583
+ if ("values" in properties[0]) {
2584
+ for (const prop of properties) try {
2585
+ const matches = matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode);
2586
+ if ("AND" === propertyGroupType) {
2587
+ if (!matches) return false;
2588
+ } else if (matches) return true;
2589
+ } catch (err) {
2590
+ if (err instanceof RequiresServerEvaluation) throw err;
2591
+ if (err instanceof InconclusiveMatchError) {
2592
+ if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);
2593
+ errorMatchingLocally = true;
2594
+ } else throw err;
2595
+ }
2596
+ if (errorMatchingLocally) throw new InconclusiveMatchError("Can't match cohort without a given cohort property value");
2597
+ return "AND" === propertyGroupType;
2598
+ }
2599
+ for (const prop of properties) try {
2600
+ let matches;
2601
+ if ("cohort" === prop.type) matches = matchCohort(prop, propertyValues, cohortProperties, debugMode);
2602
+ else if ("flag" === prop.type) {
2603
+ if (debugMode) console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${prop.key || "unknown"}'`);
2604
+ continue;
2605
+ } else matches = matchProperty(prop, propertyValues);
2606
+ const negation = prop.negation || false;
2607
+ if ("AND" === propertyGroupType) {
2608
+ if (!matches && !negation) return false;
2609
+ if (matches && negation) return false;
2610
+ } else {
2611
+ if (matches && !negation) return true;
2612
+ if (!matches && negation) return true;
2613
+ }
2614
+ } catch (err) {
2615
+ if (err instanceof RequiresServerEvaluation) throw err;
2616
+ if (err instanceof InconclusiveMatchError) {
2617
+ if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);
2618
+ errorMatchingLocally = true;
2619
+ } else throw err;
2620
+ }
2621
+ if (errorMatchingLocally) throw new InconclusiveMatchError("can't match cohort without a given cohort property value");
2622
+ return "AND" === propertyGroupType;
2623
+ }
2624
+ function isValidRegex(regex) {
2625
+ try {
2626
+ new RegExp(regex);
2627
+ return true;
2628
+ } catch (err) {
2629
+ return false;
2630
+ }
2631
+ }
2632
+ function convertToDateTime(value) {
2633
+ if (value instanceof Date) return value;
2634
+ if ("string" == typeof value || "number" == typeof value) {
2635
+ const date = new Date(value);
2636
+ if (!isNaN(date.valueOf())) return date;
2637
+ throw new InconclusiveMatchError(`${value} is in an invalid date format`);
2638
+ }
2639
+ throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);
2640
+ }
2641
+ function relativeDateParseForFeatureFlagMatching(value) {
2642
+ const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;
2643
+ const match = value.match(regex);
2644
+ const parsedDt = new Date((/* @__PURE__ */ new Date()).toISOString());
2645
+ if (!match) return null;
2646
+ {
2647
+ if (!match.groups) return null;
2648
+ const number = parseInt(match.groups["number"]);
2649
+ if (number >= 1e4) return null;
2650
+ const interval = match.groups["interval"];
2651
+ if ("h" == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);
2652
+ else if ("d" == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);
2653
+ else if ("w" == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);
2654
+ else if ("m" == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);
2655
+ else {
2656
+ if ("y" != interval) return null;
2657
+ parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);
2658
+ }
2659
+ return parsedDt;
2660
+ }
2661
+ }
2662
+ class PostHogMemoryStorage {
2663
+ getProperty(key) {
2664
+ return this._memoryStorage[key];
2665
+ }
2666
+ setProperty(key, value) {
2667
+ this._memoryStorage[key] = null !== value ? value : void 0;
2668
+ }
2669
+ constructor() {
2670
+ this._memoryStorage = {};
2671
+ }
2672
+ }
2673
+ const MINIMUM_POLLING_INTERVAL = 100;
2674
+ const THIRTY_SECONDS = 3e4;
2675
+ const MAX_CACHE_SIZE = 5e4;
2676
+ class PostHogBackendClient extends PostHogCoreStateless {
2677
+ constructor(apiKey, options = {}) {
2678
+ super(apiKey, options), this._memoryStorage = new PostHogMemoryStorage();
2679
+ this.options = options;
2680
+ this.context = this.initializeContext();
2681
+ this.options.featureFlagsPollingInterval = "number" == typeof options.featureFlagsPollingInterval ? Math.max(options.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
2682
+ if (options.personalApiKey) {
2683
+ if (options.personalApiKey.includes("phc_")) throw new Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');
2684
+ const shouldEnableLocalEvaluation = false !== options.enableLocalEvaluation;
2685
+ if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({
2686
+ pollingInterval: this.options.featureFlagsPollingInterval,
2687
+ personalApiKey: options.personalApiKey,
2688
+ projectApiKey: apiKey,
2689
+ timeout: options.requestTimeout ?? 1e4,
2690
+ host: this.host,
2691
+ fetch: options.fetch,
2692
+ onError: (err) => {
2693
+ this._events.emit("error", err);
2694
+ },
2695
+ onLoad: (count) => {
2696
+ this._events.emit("localEvaluationFlagsLoaded", count);
2697
+ },
2698
+ customHeaders: this.getCustomHeaders(),
2699
+ cacheProvider: options.flagDefinitionCacheProvider
2700
+ });
2701
+ }
2702
+ this.errorTracking = new ErrorTracking(this, options, this._logger);
2703
+ this.distinctIdHasSentFlagCalls = {};
2704
+ this.maxCacheSize = options.maxCacheSize || MAX_CACHE_SIZE;
2705
+ }
2706
+ getPersistedProperty(key) {
2707
+ return this._memoryStorage.getProperty(key);
2708
+ }
2709
+ setPersistedProperty(key, value) {
2710
+ return this._memoryStorage.setProperty(key, value);
2711
+ }
2712
+ fetch(url, options) {
2713
+ return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
2714
+ }
2715
+ getLibraryVersion() {
2716
+ return version;
2717
+ }
2718
+ getCustomUserAgent() {
2719
+ return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
2720
+ }
2721
+ enable() {
2722
+ return super.optIn();
2723
+ }
2724
+ disable() {
2725
+ return super.optOut();
2726
+ }
2727
+ debug(enabled = true) {
2728
+ super.debug(enabled);
2729
+ this.featureFlagsPoller?.debug(enabled);
2730
+ }
2731
+ capture(props) {
2732
+ if ("string" == typeof props) this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
2733
+ this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
2734
+ timestamp: options.timestamp,
2735
+ disableGeoip: options.disableGeoip,
2736
+ uuid: options.uuid
2737
+ })).catch((err) => {
2738
+ if (err) console.error(err);
2739
+ }));
2740
+ }
2741
+ async captureImmediate(props) {
2742
+ if ("string" == typeof props) this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
2743
+ return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
2744
+ timestamp: options.timestamp,
2745
+ disableGeoip: options.disableGeoip,
2746
+ uuid: options.uuid
2747
+ })).catch((err) => {
2748
+ if (err) console.error(err);
2749
+ }));
2750
+ }
2751
+ identify({ distinctId, properties, disableGeoip }) {
2752
+ const userPropsOnce = properties?.$set_once;
2753
+ delete properties?.$set_once;
2754
+ const userProps = properties?.$set || properties;
2755
+ super.identifyStateless(distinctId, {
2756
+ $set: userProps,
2757
+ $set_once: userPropsOnce
2758
+ }, {
2759
+ disableGeoip
2760
+ });
2761
+ }
2762
+ async identifyImmediate({ distinctId, properties, disableGeoip }) {
2763
+ const userPropsOnce = properties?.$set_once;
2764
+ delete properties?.$set_once;
2765
+ const userProps = properties?.$set || properties;
2766
+ await super.identifyStatelessImmediate(distinctId, {
2767
+ $set: userProps,
2768
+ $set_once: userPropsOnce
2769
+ }, {
2770
+ disableGeoip
2771
+ });
2772
+ }
2773
+ alias(data) {
2774
+ super.aliasStateless(data.alias, data.distinctId, void 0, {
2775
+ disableGeoip: data.disableGeoip
2776
+ });
2777
+ }
2778
+ async aliasImmediate(data) {
2779
+ await super.aliasStatelessImmediate(data.alias, data.distinctId, void 0, {
2780
+ disableGeoip: data.disableGeoip
2781
+ });
2782
+ }
2783
+ isLocalEvaluationReady() {
2784
+ return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;
2785
+ }
2786
+ async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
2787
+ if (this.isLocalEvaluationReady()) return true;
2788
+ if (void 0 === this.featureFlagsPoller) return false;
2789
+ return new Promise((resolve) => {
2790
+ const timeout = setTimeout(() => {
2791
+ cleanup();
2792
+ resolve(false);
2793
+ }, timeoutMs);
2794
+ const cleanup = this._events.on("localEvaluationFlagsLoaded", (count) => {
2795
+ clearTimeout(timeout);
2796
+ cleanup();
2797
+ resolve(count > 0);
2798
+ });
2799
+ });
2800
+ }
2801
+ async getFeatureFlag(key, distinctId, options) {
2802
+ const { groups, disableGeoip } = options || {};
2803
+ let { onlyEvaluateLocally, sendFeatureFlagEvents, personProperties, groupProperties } = options || {};
2804
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
2805
+ personProperties = adjustedProperties.allPersonProperties;
2806
+ groupProperties = adjustedProperties.allGroupProperties;
2807
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
2808
+ if (void 0 == sendFeatureFlagEvents) sendFeatureFlagEvents = this.options.sendFeatureFlagEvent ?? true;
2809
+ let response = await this.featureFlagsPoller?.getFeatureFlag(key, distinctId, groups, personProperties, groupProperties);
2810
+ const flagWasLocallyEvaluated = void 0 !== response;
2811
+ let requestId;
2812
+ let evaluatedAt;
2813
+ let flagDetail;
2814
+ if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
2815
+ const remoteResponse = await super.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
2816
+ if (void 0 === remoteResponse) return;
2817
+ flagDetail = remoteResponse.response;
2818
+ response = getFeatureFlagValue(flagDetail);
2819
+ requestId = remoteResponse?.requestId;
2820
+ evaluatedAt = remoteResponse?.evaluatedAt;
2821
+ }
2822
+ const featureFlagReportedKey = `${key}_${response}`;
2823
+ if (sendFeatureFlagEvents && (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey))) {
2824
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};
2825
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
2826
+ else this.distinctIdHasSentFlagCalls[distinctId] = [
2827
+ featureFlagReportedKey
2828
+ ];
2829
+ this.capture({
2830
+ distinctId,
2831
+ event: "$feature_flag_called",
2832
+ properties: {
2833
+ $feature_flag: key,
2834
+ $feature_flag_response: response,
2835
+ $feature_flag_id: flagDetail?.metadata?.id,
2836
+ $feature_flag_version: flagDetail?.metadata?.version,
2837
+ $feature_flag_reason: flagDetail?.reason?.description ?? flagDetail?.reason?.code,
2838
+ locally_evaluated: flagWasLocallyEvaluated,
2839
+ [`$feature/${key}`]: response,
2840
+ $feature_flag_request_id: requestId,
2841
+ $feature_flag_evaluated_at: evaluatedAt
2842
+ },
2843
+ groups,
2844
+ disableGeoip
2845
+ });
2846
+ }
2847
+ return response;
2848
+ }
2849
+ async getFeatureFlagPayload(key, distinctId, matchValue, options) {
2850
+ const { groups, disableGeoip } = options || {};
2851
+ let { onlyEvaluateLocally, personProperties, groupProperties } = options || {};
2852
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
2853
+ personProperties = adjustedProperties.allPersonProperties;
2854
+ groupProperties = adjustedProperties.allGroupProperties;
2855
+ let response;
2856
+ const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;
2857
+ if (localEvaluationEnabled) {
2858
+ await this.featureFlagsPoller?.loadFeatureFlags();
2859
+ const flag = this.featureFlagsPoller?.featureFlagsByKey[key];
2860
+ if (flag) try {
2861
+ const result = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, distinctId, groups, personProperties, groupProperties, matchValue);
2862
+ if (result) {
2863
+ matchValue = result.value;
2864
+ response = result.payload;
2865
+ }
2866
+ } catch (e) {
2867
+ if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`);
2868
+ else throw e;
2869
+ }
2870
+ }
2871
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
2872
+ const payloadWasLocallyEvaluated = void 0 !== response;
2873
+ if (!payloadWasLocallyEvaluated && !onlyEvaluateLocally) response = await super.getFeatureFlagPayloadStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);
2874
+ return response;
2875
+ }
2876
+ async getRemoteConfigPayload(flagKey) {
2877
+ if (!this.options.personalApiKey) throw new Error("Personal API key is required for remote config payload decryption");
2878
+ const response = await this._requestRemoteConfigPayload(flagKey);
2879
+ if (!response) return;
2880
+ const parsed = await response.json();
2881
+ if ("string" == typeof parsed) try {
2882
+ return JSON.parse(parsed);
2883
+ } catch (e) {
2884
+ }
2885
+ return parsed;
2886
+ }
2887
+ async isFeatureEnabled(key, distinctId, options) {
2888
+ const feat = await this.getFeatureFlag(key, distinctId, options);
2889
+ if (void 0 === feat) return;
2890
+ return !!feat || false;
2891
+ }
2892
+ async getAllFlags(distinctId, options) {
2893
+ const response = await this.getAllFlagsAndPayloads(distinctId, options);
2894
+ return response.featureFlags || {};
2895
+ }
2896
+ async getAllFlagsAndPayloads(distinctId, options) {
2897
+ const { groups, disableGeoip, flagKeys } = options || {};
2898
+ let { onlyEvaluateLocally, personProperties, groupProperties } = options || {};
2899
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
2900
+ personProperties = adjustedProperties.allPersonProperties;
2901
+ groupProperties = adjustedProperties.allGroupProperties;
2902
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = false;
2903
+ const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(distinctId, groups, personProperties, groupProperties, flagKeys);
2904
+ let featureFlags = {};
2905
+ let featureFlagPayloads = {};
2906
+ let fallbackToFlags = true;
2907
+ if (localEvaluationResult) {
2908
+ featureFlags = localEvaluationResult.response;
2909
+ featureFlagPayloads = localEvaluationResult.payloads;
2910
+ fallbackToFlags = localEvaluationResult.fallbackToFlags;
2911
+ }
2912
+ if (fallbackToFlags && !onlyEvaluateLocally) {
2913
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeys);
2914
+ featureFlags = {
2915
+ ...featureFlags,
2916
+ ...remoteEvaluationResult.flags || {}
2917
+ };
2918
+ featureFlagPayloads = {
2919
+ ...featureFlagPayloads,
2920
+ ...remoteEvaluationResult.payloads || {}
2921
+ };
2922
+ }
2923
+ return {
2924
+ featureFlags,
2925
+ featureFlagPayloads
2926
+ };
2927
+ }
2928
+ groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
2929
+ super.groupIdentifyStateless(groupType, groupKey, properties, {
2930
+ disableGeoip
2931
+ }, distinctId);
2932
+ }
2933
+ async reloadFeatureFlags() {
2934
+ await this.featureFlagsPoller?.loadFeatureFlags(true);
2935
+ }
2936
+ withContext(data, fn, options) {
2937
+ if (!this.context) return fn();
2938
+ return this.context.run(data, fn, options);
2939
+ }
2940
+ getContext() {
2941
+ return this.context?.get();
2942
+ }
2943
+ async _shutdown(shutdownTimeoutMs) {
2944
+ this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
2945
+ this.errorTracking.shutdown();
2946
+ return super._shutdown(shutdownTimeoutMs);
2947
+ }
2948
+ async _requestRemoteConfigPayload(flagKey) {
2949
+ if (!this.options.personalApiKey) return;
2950
+ const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;
2951
+ const options = {
2952
+ method: "GET",
2953
+ headers: {
2954
+ ...this.getCustomHeaders(),
2955
+ "Content-Type": "application/json",
2956
+ Authorization: `Bearer ${this.options.personalApiKey}`
2957
+ }
2958
+ };
2959
+ let abortTimeout = null;
2960
+ if (this.options.requestTimeout && "number" == typeof this.options.requestTimeout) {
2961
+ const controller = new AbortController();
2962
+ abortTimeout = safeSetTimeout(() => {
2963
+ controller.abort();
2964
+ }, this.options.requestTimeout);
2965
+ options.signal = controller.signal;
2966
+ }
2967
+ try {
2968
+ return await this.fetch(url, options);
2969
+ } catch (error) {
2970
+ this._events.emit("error", error);
2971
+ return;
2972
+ } finally {
2973
+ if (abortTimeout) clearTimeout(abortTimeout);
2974
+ }
2975
+ }
2976
+ extractPropertiesFromEvent(eventProperties, groups) {
2977
+ if (!eventProperties) return {
2978
+ personProperties: {},
2979
+ groupProperties: {}
2980
+ };
2981
+ const personProperties = {};
2982
+ const groupProperties = {};
2983
+ for (const [key, value] of Object.entries(eventProperties)) if (isPlainObject(value) && groups && key in groups) {
2984
+ const groupProps = {};
2985
+ for (const [groupKey, groupValue] of Object.entries(value)) groupProps[String(groupKey)] = String(groupValue);
2986
+ groupProperties[String(key)] = groupProps;
2987
+ } else personProperties[String(key)] = String(value);
2988
+ return {
2989
+ personProperties,
2990
+ groupProperties
2991
+ };
2992
+ }
2993
+ async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {
2994
+ const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};
2995
+ const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};
2996
+ const flagKeys = sendFeatureFlagsOptions?.flagKeys;
2997
+ const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? false;
2998
+ if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};
2999
+ else {
3000
+ const groupsWithStringValues = {};
3001
+ for (const [key, value] of Object.entries(groups || {})) groupsWithStringValues[key] = String(value);
3002
+ return await this.getAllFlags(distinctId, {
3003
+ groups: groupsWithStringValues,
3004
+ personProperties: finalPersonProperties,
3005
+ groupProperties: finalGroupProperties,
3006
+ disableGeoip,
3007
+ onlyEvaluateLocally: true,
3008
+ flagKeys
3009
+ });
3010
+ }
3011
+ if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {
3012
+ const groupsWithStringValues = {};
3013
+ for (const [key, value] of Object.entries(groups || {})) groupsWithStringValues[key] = String(value);
3014
+ return await this.getAllFlags(distinctId, {
3015
+ groups: groupsWithStringValues,
3016
+ personProperties: finalPersonProperties,
3017
+ groupProperties: finalGroupProperties,
3018
+ disableGeoip,
3019
+ onlyEvaluateLocally: true,
3020
+ flagKeys
3021
+ });
3022
+ }
3023
+ return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;
3024
+ }
3025
+ addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
3026
+ const allPersonProperties = {
3027
+ distinct_id: distinctId,
3028
+ ...personProperties || {}
3029
+ };
3030
+ const allGroupProperties = {};
3031
+ if (groups) for (const groupName of Object.keys(groups)) allGroupProperties[groupName] = {
3032
+ $group_key: groups[groupName],
3033
+ ...groupProperties?.[groupName] || {}
3034
+ };
3035
+ return {
3036
+ allPersonProperties,
3037
+ allGroupProperties
3038
+ };
3039
+ }
3040
+ captureException(error, distinctId, additionalProperties) {
3041
+ const syntheticException = new Error("PostHog syntheticException");
3042
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3043
+ syntheticException
3044
+ }, distinctId, additionalProperties).then((msg) => this.capture(msg)));
3045
+ }
3046
+ async captureExceptionImmediate(error, distinctId, additionalProperties) {
3047
+ const syntheticException = new Error("PostHog syntheticException");
3048
+ this.addPendingPromise(ErrorTracking.buildEventMessage(error, {
3049
+ syntheticException
3050
+ }, distinctId, additionalProperties).then((msg) => this.captureImmediate(msg)));
3051
+ }
3052
+ async prepareEventMessage(props) {
3053
+ const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
3054
+ const contextData = this.context?.get();
3055
+ let mergedDistinctId = distinctId || contextData?.distinctId;
3056
+ const mergedProperties = {
3057
+ ...contextData?.properties || {},
3058
+ ...properties || {}
3059
+ };
3060
+ if (!mergedDistinctId) {
3061
+ mergedDistinctId = uuidv7();
3062
+ mergedProperties.$process_person_profile = false;
3063
+ }
3064
+ if (contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;
3065
+ const eventMessage = this._runBeforeSend({
3066
+ distinctId: mergedDistinctId,
3067
+ event,
3068
+ properties: mergedProperties,
3069
+ groups,
3070
+ sendFeatureFlags,
3071
+ timestamp,
3072
+ disableGeoip,
3073
+ uuid
3074
+ });
3075
+ if (!eventMessage) return Promise.reject(null);
3076
+ const eventProperties = await Promise.resolve().then(async () => {
3077
+ if (sendFeatureFlags) {
3078
+ const sendFeatureFlagsOptions = "object" == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
3079
+ return await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
3080
+ }
3081
+ eventMessage.event;
3082
+ return {};
3083
+ }).then((flags) => {
3084
+ const additionalProperties = {};
3085
+ if (flags) for (const [feature, variant] of Object.entries(flags)) additionalProperties[`$feature/${feature}`] = variant;
3086
+ const activeFlags = Object.keys(flags || {}).filter((flag) => flags?.[flag] !== false).sort();
3087
+ if (activeFlags.length > 0) additionalProperties["$active_feature_flags"] = activeFlags;
3088
+ return additionalProperties;
3089
+ }).catch(() => ({})).then((additionalProperties) => {
3090
+ const props2 = {
3091
+ ...additionalProperties,
3092
+ ...eventMessage.properties || {},
3093
+ $groups: eventMessage.groups || groups
3094
+ };
3095
+ return props2;
3096
+ });
3097
+ if ("$pageview" === eventMessage.event && this.options.__preview_capture_bot_pageviews && "string" == typeof eventProperties.$raw_user_agent) {
3098
+ if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
3099
+ eventMessage.event = "$bot_pageview";
3100
+ eventProperties.$browser_type = "bot";
3101
+ }
3102
+ }
3103
+ return {
3104
+ distinctId: eventMessage.distinctId,
3105
+ event: eventMessage.event,
3106
+ properties: eventProperties,
3107
+ options: {
3108
+ timestamp: eventMessage.timestamp,
3109
+ disableGeoip: eventMessage.disableGeoip,
3110
+ uuid: eventMessage.uuid
3111
+ }
3112
+ };
3113
+ }
3114
+ _runBeforeSend(eventMessage) {
3115
+ const beforeSend = this.options.before_send;
3116
+ if (!beforeSend) return eventMessage;
3117
+ const fns = Array.isArray(beforeSend) ? beforeSend : [
3118
+ beforeSend
3119
+ ];
3120
+ let result = eventMessage;
3121
+ for (const fn of fns) {
3122
+ result = fn(result);
3123
+ if (!result) {
3124
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
3125
+ return null;
3126
+ }
3127
+ if (!result.properties || 0 === Object.keys(result.properties).length) {
3128
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
3129
+ this._logger.warn(message);
3130
+ }
3131
+ }
3132
+ return result;
3133
+ }
3134
+ }
3135
+ class PostHogContext {
3136
+ constructor() {
3137
+ this.storage = new AsyncLocalStorage();
3138
+ }
3139
+ get() {
3140
+ return this.storage.getStore();
3141
+ }
3142
+ run(context, fn, options) {
3143
+ const fresh = options?.fresh === true;
3144
+ if (fresh) return this.storage.run(context, fn);
3145
+ {
3146
+ const currentContext = this.get() || {};
3147
+ const mergedContext = {
3148
+ distinctId: context.distinctId ?? currentContext.distinctId,
3149
+ sessionId: context.sessionId ?? currentContext.sessionId,
3150
+ properties: {
3151
+ ...currentContext.properties || {},
3152
+ ...context.properties || {}
3153
+ }
3154
+ };
3155
+ return this.storage.run(mergedContext, fn);
3156
+ }
3157
+ }
3158
+ }
3159
+ function setupExpressErrorHandler(_posthog, app) {
3160
+ app.use(posthogErrorHandler(_posthog));
3161
+ }
3162
+ function posthogErrorHandler(posthog) {
3163
+ return (error, req, res, next) => {
3164
+ const sessionId = req.headers["x-posthog-session-id"];
3165
+ const distinctId = req.headers["x-posthog-distinct-id"];
3166
+ const syntheticException = new Error("Synthetic exception");
3167
+ const hint = {
3168
+ mechanism: {
3169
+ type: "middleware",
3170
+ handled: false
3171
+ },
3172
+ syntheticException
3173
+ };
3174
+ posthog.addPendingPromise(ErrorTracking.buildEventMessage(error, hint, distinctId, {
3175
+ $session_id: sessionId,
3176
+ $current_url: req.url,
3177
+ $request_method: req.method,
3178
+ $request_path: req.path,
3179
+ $user_agent: req.headers["user-agent"],
3180
+ $response_status_code: res.statusCode,
3181
+ $ip: req.headers["x-forwarded-for"] || req?.socket?.remoteAddress
3182
+ }).then((msg) => {
3183
+ posthog.capture(msg);
3184
+ }));
3185
+ next(error);
3186
+ };
3187
+ }
3188
+ ErrorTracking.errorPropertiesBuilder = new ErrorPropertiesBuilder([
3189
+ new EventCoercer(),
3190
+ new ErrorCoercer(),
3191
+ new ObjectCoercer(),
3192
+ new StringCoercer(),
3193
+ new PrimitiveCoercer()
3194
+ ], createStackParser("node:javascript", nodeStackLineParser), [
3195
+ createModulerModifier(),
3196
+ addSourceContext
3197
+ ]);
3198
+ class PostHog extends PostHogBackendClient {
3199
+ getLibraryId() {
3200
+ return "posthog-node";
3201
+ }
3202
+ initializeContext() {
3203
+ return new PostHogContext();
3204
+ }
3205
+ }
3206
+ let client;
3207
+ let shutdownHookBound = false;
3208
+ const resolveApiKey = (env2) => env2.POSTHOG_API_KEY || env2.POSTHOG_KEY || env2.POSTHOG_SERVER_KEY;
3209
+ const resolveHost = (env2) => env2.POSTHOG_HOST || env2.RB_POSTHOG_HOST || "https://eu.i.posthog.com";
3210
+ const getPosthogClient = (env2) => {
3211
+ if (client !== void 0) return client;
3212
+ const apiKey = resolveApiKey(env2);
3213
+ if (!apiKey) {
3214
+ client = null;
3215
+ return client;
3216
+ }
3217
+ client = new PostHog(apiKey, {
3218
+ host: resolveHost(env2),
3219
+ enableExceptionAutocapture: true,
3220
+ flushAt: 1,
3221
+ flushInterval: 1e3
3222
+ });
3223
+ return client;
3224
+ };
3225
+ const bindExpressErrorHandler = (app, posthog) => {
3226
+ if (!posthog) return;
3227
+ setupExpressErrorHandler(posthog, app);
3228
+ };
3229
+ const captureServerException = (error, posthog, properties) => {
3230
+ const clientToUse = posthog ?? client ?? null;
3231
+ if (!clientToUse || typeof clientToUse.captureException !== "function") return;
3232
+ clientToUse.captureException(error, "server", properties);
3233
+ };
3234
+ const shutdown = async () => {
3235
+ if (!client) return;
3236
+ try {
3237
+ await client.shutdown();
3238
+ } catch (err) {
3239
+ console.error("posthog shutdown error", err);
3240
+ }
3241
+ };
3242
+ const ensurePosthogShutdown = () => {
3243
+ if (shutdownHookBound || !client) return;
3244
+ shutdownHookBound = true;
3245
+ const stop = () => {
3246
+ void shutdown();
3247
+ };
3248
+ process.on("SIGTERM", stop);
3249
+ process.on("SIGINT", stop);
3250
+ process.on("beforeExit", shutdown);
3251
+ };
189
3252
  const getDerivedKey = (masterKey, info, length = 32, salt = "") => {
190
- assert(masterKey?.length >= 32, "MASTER_KEY must be 32 chars or longer.");
3253
+ assert$1(masterKey?.length >= 32, "MASTER_KEY must be 32 chars or longer.");
191
3254
  return Buffer.from(hkdfSync(
192
3255
  "sha256",
193
3256
  masterKey,
@@ -288,6 +3351,12 @@ const initServer = async (app, serverEnv) => {
288
3351
  next();
289
3352
  });
290
3353
  metricsIngestProxyMiddleware(app);
3354
+ const posthog = getPosthogClient(serverEnv);
3355
+ if (posthog) {
3356
+ app.locals.posthog = posthog;
3357
+ bindExpressErrorHandler(app, posthog);
3358
+ ensurePosthogShutdown();
3359
+ }
291
3360
  if (!serverEnv.MASTER_KEY) {
292
3361
  throw new Error("MASTER_KEY must be defined to derive the session secret");
293
3362
  }
@@ -517,6 +3586,8 @@ async function renderSSR(req, dataRoutes) {
517
3586
  const ABORT_DELAY_MS = 1e4;
518
3587
  const APP_HTML_PLACEHOLDER = "<!--app-html-->";
519
3588
  const DEFAULT_SERVER_ERROR_MESSAGE = "We couldn't render this page on the server. Please refresh and try again.";
3589
+ const FALLBACK_ERROR_TEMPLATE_START = `<!doctype html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1" /><title>Server error</title><style>body{margin:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0b1021;color:#eef1f7;display:flex;align-items:center;justify-content:center;min-height:100vh;}main{max-width:420px;padding:32px;background:rgba(255,255,255,0.04);border:1px solid rgba(255,255,255,0.08);border-radius:14px;box-shadow:0 25px 50px rgba(0,0,0,0.35);}h1{font-size:24px;margin:0 0 8px;}p{margin:0 0 12px;line-height:1.5;}code{background:rgba(255,255,255,0.08);padding:2px 6px;border-radius:6px;font-size:12px;}</style></head><body><main>`;
3590
+ const FALLBACK_ERROR_TEMPLATE_END = "</main></body></html>";
520
3591
  const isProduction = env.NODE_ENV === "production";
521
3592
  const templateHtml = isProduction ? readFileSync("./build/dist/client/src/client/index.html", "utf-8") : "";
522
3593
  const formatErrorDetails = (error) => {
@@ -534,22 +3605,6 @@ const formatErrorDetails = (error) => {
534
3605
  return void 0;
535
3606
  }
536
3607
  };
537
- const formatPlainErrorBody = (error) => {
538
- if (isProduction) {
539
- return "Server error";
540
- }
541
- if (error instanceof Error) {
542
- return error.stack || error.message;
543
- }
544
- if (typeof error === "string") {
545
- return error;
546
- }
547
- try {
548
- return JSON.stringify(error, null, 2);
549
- } catch {
550
- return "Unknown error";
551
- }
552
- };
553
3608
  const sendErrorResponse = ({
554
3609
  res,
555
3610
  htmlStart,
@@ -561,10 +3616,8 @@ const sendErrorResponse = ({
561
3616
  errorExtraComponent
562
3617
  }) => {
563
3618
  if (res.headersSent) return;
564
- if (!htmlStart || !htmlEnd) {
565
- res.status(status).end(formatPlainErrorBody(error));
566
- return;
567
- }
3619
+ const start = htmlStart ?? FALLBACK_ERROR_TEMPLATE_START;
3620
+ const end = htmlEnd ?? FALLBACK_ERROR_TEMPLATE_END;
568
3621
  res.status(status);
569
3622
  res.set({ "Content-Type": "text/html" });
570
3623
  const details = formatErrorDetails(error);
@@ -588,18 +3641,29 @@ const sendErrorResponse = ({
588
3641
  ...state,
589
3642
  details: isProduction ? void 0 : details
590
3643
  })};<\/script>`;
591
- res.end(`${htmlStart}${markup}${serializedState}${htmlEnd}`);
3644
+ res.end(`${start}${markup}${serializedState}${end}`);
592
3645
  };
593
3646
  const ssrMiddleware = ({
594
3647
  viteInstance,
595
3648
  dataRoutes,
596
3649
  errorExtraComponent,
597
- renderTemplateStart
3650
+ renderTemplateStart,
3651
+ posthog
598
3652
  }) => async (req, res, next) => {
599
3653
  let template;
600
3654
  let htmlStart = null;
601
3655
  let htmlEnd = null;
602
3656
  let responseCommitted = false;
3657
+ const posthogClient = posthog ?? req.app?.locals?.posthog ?? null;
3658
+ const captureException = (error, extra) => {
3659
+ if (!error) return;
3660
+ captureServerException(error, posthogClient, {
3661
+ path: req.originalUrl,
3662
+ method: req.method,
3663
+ source: "ssrMiddleware",
3664
+ ...extra
3665
+ });
3666
+ };
603
3667
  const finalizeWithErrorPage = (error, status = 500, message = DEFAULT_SERVER_ERROR_MESSAGE) => {
604
3668
  if (responseCommitted) return;
605
3669
  sendErrorResponse({
@@ -612,6 +3676,9 @@ const ssrMiddleware = ({
612
3676
  errorExtraComponent
613
3677
  });
614
3678
  responseCommitted = true;
3679
+ if (error) {
3680
+ captureException(error, { phase: "finalizeWithErrorPage" });
3681
+ }
615
3682
  };
616
3683
  try {
617
3684
  const base = "/";
@@ -647,6 +3714,7 @@ const ssrMiddleware = ({
647
3714
  viteInstance?.ssrFixStacktrace(error);
648
3715
  }
649
3716
  console.error("SSR shell error", error);
3717
+ captureException(error, { phase: "shell" });
650
3718
  finalizeWithErrorPage(error);
651
3719
  abort();
652
3720
  },
@@ -656,6 +3724,7 @@ const ssrMiddleware = ({
656
3724
  viteInstance?.ssrFixStacktrace(error);
657
3725
  }
658
3726
  console.error("SSR rendering error", error);
3727
+ captureException(error, { phase: "render" });
659
3728
  },
660
3729
  onShellReady() {
661
3730
  if (responseCommitted) {
@@ -696,6 +3765,7 @@ const ssrMiddleware = ({
696
3765
  } else {
697
3766
  console.error("Unknown SSR middleware error", err);
698
3767
  }
3768
+ captureException(err, { phase: "catch" });
699
3769
  finalizeWithErrorPage(err);
700
3770
  }
701
3771
  };