@rpcbase/server 0.630.0 → 0.632.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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["gzipCompress","PostHogPersistedProperty","gzipCompress","ErrorTracking.ReduceableCache","promises_open","isAbsolute","ErrorTracking.getInjectedReleaseId","gzipCompress","error_tracking","PostHogPersistedProperty","ErrorTracking.getInjectedReleaseId","#_","error_tracking","ErrorTracking.ErrorPropertiesBuilder","ErrorTracking.EventCoercer","ErrorTracking.ErrorCoercer","ErrorTracking.ObjectCoercer","ErrorTracking.StringCoercer","ErrorTracking.PrimitiveCoercer","ErrorTracking.createStackParser","ErrorTracking.nodeStackLineParser"],"sources":["../../../node_modules/request-ip/lib/is.js","../../../node_modules/request-ip/lib/index.js","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs","../../../node_modules/@posthog/core/dist/featureFlagUtils.mjs","../../../node_modules/@posthog/core/dist/types.mjs","../../../node_modules/@posthog/core/dist/gzip.mjs","../../../node_modules/@posthog/core/dist/utils/json-utils.mjs","../../../node_modules/@posthog/core/dist/utils/bot-detection.mjs","../../../node_modules/@posthog/core/dist/utils/string-utils.mjs","../../../node_modules/@posthog/core/dist/utils/type-utils.mjs","../../../node_modules/@posthog/core/dist/utils/number-utils.mjs","../../../node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs","../../../node_modules/@posthog/core/dist/vendor/uuidv7.mjs","../../../node_modules/@posthog/core/dist/utils/promise-queue.mjs","../../../node_modules/@posthog/core/dist/utils/logger.mjs","../../../node_modules/@posthog/core/dist/utils/user-agent-utils.mjs","../../../node_modules/@posthog/core/dist/utils/index.mjs","../../../node_modules/@posthog/core/dist/logs/logs-utils.mjs","../../../node_modules/@posthog/core/dist/metrics/metrics-utils.mjs","../../../node_modules/@posthog/core/dist/metrics/config.mjs","../../../node_modules/@posthog/core/dist/metrics/index.mjs","../../../node_modules/@posthog/core/dist/eventemitter.mjs","../../../node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs","../../../node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/types.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/utils.mjs","../../../node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs","../../../node_modules/@posthog/core/dist/error-tracking/release.mjs","../../../node_modules/@posthog/core/dist/posthog-core-stateless.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs","../../../node_modules/posthog-node/dist/version.mjs","../../../node_modules/posthog-node/dist/types.mjs","../../../node_modules/posthog-node/dist/feature-flag-evaluations.mjs","../../../node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs","../../../node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/index.mjs","../../../node_modules/posthog-node/dist/storage-memory.mjs","../../../node_modules/posthog-node/dist/capture-v1/config.mjs","../../../node_modules/posthog-node/dist/capture-v1/routing.mjs","../../../node_modules/posthog-node/dist/capture-v1/errors.mjs","../../../node_modules/posthog-node/dist/capture-v1/transform.mjs","../../../node_modules/posthog-node/dist/capture-v1/sender.mjs","../../../node_modules/posthog-node/dist/ai-capture/routing.mjs","../../../node_modules/posthog-node/dist/ai-capture/batching.mjs","../../../node_modules/posthog-node/dist/client.mjs","../../../node_modules/posthog-node/dist/extensions/context/context.mjs","../../../node_modules/posthog-node/dist/gzip.node.mjs","../../../node_modules/posthog-node/dist/extensions/sentry-integration.mjs","../../../node_modules/posthog-node/dist/extensions/tracing-headers.mjs","../../../node_modules/posthog-node/dist/extensions/url-utils.mjs","../../../node_modules/posthog-node/dist/extensions/express.mjs","../../../node_modules/posthog-node/dist/entrypoints/index.node.mjs","../src/shutdown.ts","../src/posthog.ts","../src/metricsIngestProxyMiddleware.ts","../src/checkInitReplicaSet.ts","../src/dev/coverage.ts","../src/developmentSessionMiddleware.ts","../src/serviceWorker.ts","../src/initServer.ts","../src/hashPassword.ts","../src/passwordHashStorage.ts","../src/applyRouteLoaders.ts","../src/rts/ssrHydration.ts","../src/renderSSR.tsx","../src/htmlTemplate.ts","../src/ssrMiddleware.ts","../src/accountDeletionUploads.ts","../src/accountDeletion.ts","../src/userSessionDeletion.ts"],"sourcesContent":["\"use strict\";\n\nvar regexes = {\n ipv4: /^(?:(?:\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$/,\n ipv6: /^((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|$))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})$/i\n};\n\nfunction not(func) {\n return function () {\n return !func.apply(null, Array.prototype.slice.call(arguments));\n };\n}\n\nfunction existy(value) {\n return value != null;\n}\n\nfunction ip(value) {\n return existy(value) && regexes.ipv4.test(value) || regexes.ipv6.test(value);\n}\n\nfunction object(value) {\n return Object(value) === value;\n}\n\nfunction string(value) {\n return Object.prototype.toString.call(value) === '[object String]';\n}\n\nvar is = {\n existy: existy,\n ip: ip,\n object: object,\n string: string,\n not: {\n existy: not(existy),\n ip: not(ip),\n object: not(object),\n string: not(string)\n }\n};\nmodule.exports = is;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nvar is = require('./is');\n\nfunction getClientIpFromXForwardedFor(value) {\n if (!is.existy(value)) {\n return null;\n }\n\n if (is.not.string(value)) {\n throw new TypeError(\"Expected a string, got \\\"\".concat(_typeof(value), \"\\\"\"));\n }\n\n var forwardedIps = value.split(',').map(function (e) {\n var ip = e.trim();\n\n if (ip.includes(':')) {\n var splitted = ip.split(':');\n\n if (splitted.length === 2) {\n return splitted[0];\n }\n }\n\n return ip;\n });\n\n for (var i = 0; i < forwardedIps.length; i++) {\n if (is.ip(forwardedIps[i])) {\n return forwardedIps[i];\n }\n }\n\n return null;\n}\n\nfunction getClientIp(req) {\n if (req.headers) {\n if (is.ip(req.headers['x-client-ip'])) {\n return req.headers['x-client-ip'];\n }\n\n var xForwardedFor = getClientIpFromXForwardedFor(req.headers['x-forwarded-for']);\n\n if (is.ip(xForwardedFor)) {\n return xForwardedFor;\n }\n\n if (is.ip(req.headers['cf-connecting-ip'])) {\n return req.headers['cf-connecting-ip'];\n }\n\n if (is.ip(req.headers['fastly-client-ip'])) {\n return req.headers['fastly-client-ip'];\n }\n\n if (is.ip(req.headers['true-client-ip'])) {\n return req.headers['true-client-ip'];\n }\n\n if (is.ip(req.headers['x-real-ip'])) {\n return req.headers['x-real-ip'];\n }\n\n if (is.ip(req.headers['x-cluster-client-ip'])) {\n return req.headers['x-cluster-client-ip'];\n }\n\n if (is.ip(req.headers['x-forwarded'])) {\n return req.headers['x-forwarded'];\n }\n\n if (is.ip(req.headers['forwarded-for'])) {\n return req.headers['forwarded-for'];\n }\n\n if (is.ip(req.headers.forwarded)) {\n return req.headers.forwarded;\n }\n\n if (is.ip(req.headers['x-appengine-user-ip'])) {\n return req.headers['x-appengine-user-ip'];\n }\n }\n\n if (is.existy(req.connection)) {\n if (is.ip(req.connection.remoteAddress)) {\n return req.connection.remoteAddress;\n }\n\n if (is.existy(req.connection.socket) && is.ip(req.connection.socket.remoteAddress)) {\n return req.connection.socket.remoteAddress;\n }\n }\n\n if (is.existy(req.socket) && is.ip(req.socket.remoteAddress)) {\n return req.socket.remoteAddress;\n }\n\n if (is.existy(req.info) && is.ip(req.info.remoteAddress)) {\n return req.info.remoteAddress;\n }\n\n if (is.existy(req.requestContext) && is.existy(req.requestContext.identity) && is.ip(req.requestContext.identity.sourceIp)) {\n return req.requestContext.identity.sourceIp;\n }\n\n if (req.headers) {\n if (is.ip(req.headers['Cf-Pseudo-IPv4'])) {\n return req.headers['Cf-Pseudo-IPv4'];\n }\n }\n\n if (is.existy(req.raw)) {\n return getClientIp(req.raw);\n }\n\n return null;\n}\n\nfunction mw(options) {\n var configuration = is.not.existy(options) ? {} : options;\n\n if (is.not.object(configuration)) {\n throw new TypeError('Options must be an object!');\n }\n\n var attributeName = configuration.attributeName || 'clientIp';\n return function (req, res, next) {\n var ip = getClientIp(req);\n Object.defineProperty(req, attributeName, {\n get: function get() {\n return ip;\n },\n configurable: true\n });\n next();\n };\n}\n\nmodule.exports = {\n getClientIpFromXForwardedFor: getClientIpFromXForwardedFor,\n getClientIp: getClientIp,\n mw: mw\n};","import { dirname, posix, sep } from \"path\";\nfunction createModulerModifier() {\n const getModuleFromFileName = createGetModuleFromFilename();\n return async (frames)=>{\n for (const frame of frames)frame.module = getModuleFromFileName(frame.filename);\n return frames;\n };\n}\nfunction createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = '\\\\' === sep) {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n return (filename)=>{\n if (!filename) return;\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n if ('.js' === ext || '.mjs' === ext || '.cjs' === ext) file = file.slice(0, -1 * ext.length);\n const decodedFile = decodeURIComponent(file);\n if (!dir) dir = '.';\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n return decodedFile;\n };\n}\nfunction normalizeWindowsPath(path) {\n return path.replace(/^[A-Z]:/, '').replace(/\\\\/g, '/');\n}\nexport { createModulerModifier };\n","const normalizeFlagsResponse = (flagsResponse)=>{\n if ('flags' in flagsResponse) {\n const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);\n const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads\n };\n }\n {\n const featureFlags = flagsResponse.featureFlags ?? {};\n const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v])=>[\n k,\n parsePayload(v)\n ]));\n const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value])=>[\n key,\n getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])\n ]));\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads,\n flags\n };\n }\n};\nfunction getFlagDetailFromFlagAndPayload(key, value, payload) {\n return {\n key: key,\n enabled: 'string' == typeof value ? true : value,\n variant: 'string' == typeof value ? value : void 0,\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n payload: payload ? JSON.stringify(payload) : void 0,\n description: void 0\n }\n };\n}\nconst getFlagValuesFromFlags = (flags)=>Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail])=>[\n key,\n getFeatureFlagValue(detail)\n ]).filter(([, value])=>void 0 !== value));\nconst getPayloadsFromFlags = (flags)=>{\n const safeFlags = flags ?? {};\n return Object.fromEntries(Object.keys(safeFlags).filter((flag)=>{\n const details = safeFlags[flag];\n return details.enabled && details.metadata && void 0 !== details.metadata.payload;\n }).map((flag)=>{\n const payload = safeFlags[flag].metadata?.payload;\n return [\n flag,\n payload ? parsePayload(payload) : void 0\n ];\n }));\n};\nconst getFeatureFlagValue = (detail)=>void 0 === detail ? void 0 : detail.variant ?? detail.enabled;\nconst parsePayload = (response)=>{\n if ('string' != typeof response) return response;\n try {\n return JSON.parse(response);\n } catch {\n return response;\n }\n};\nconst createFlagsResponseFromFlagsAndPayloads = (featureFlags, featureFlagPayloads)=>{\n const allKeys = [\n ...new Set([\n ...Object.keys(featureFlags ?? {}),\n ...Object.keys(featureFlagPayloads ?? {})\n ])\n ];\n const enabledFlags = allKeys.filter((flag)=>!!featureFlags[flag] || !!featureFlagPayloads[flag]).reduce((res, key)=>(res[key] = featureFlags[key] ?? true, res), {});\n const flagDetails = {\n featureFlags: enabledFlags,\n featureFlagPayloads: featureFlagPayloads ?? {}\n };\n return normalizeFlagsResponse(flagDetails);\n};\nconst updateFlagValue = (flag, value)=>({\n ...flag,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value)\n });\nfunction getEnabledFromValue(value) {\n return 'string' == typeof value ? true : value;\n}\nfunction getVariantFromValue(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst flagDetailsToResults = (flagDetails)=>Object.values(flagDetails).map((detail)=>{\n const value = detail.variant ?? detail.enabled;\n const rawPayload = detail.metadata?.payload;\n return {\n key: detail.key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n payload: void 0 !== rawPayload ? parsePayload(rawPayload) : null\n };\n });\nconst MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_content',\n 'utm_term',\n 'gad_source',\n 'mc_cid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n 'igshid',\n 'ttclid',\n 'rdt_cid',\n 'epik',\n 'qclid',\n 'sccid',\n 'irclid',\n '_kx'\n];\nconst MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [\n '$feature_flag',\n '$feature_flag_response',\n '$feature_flag_has_experiment',\n '$feature_flag_id',\n '$feature_flag_version',\n '$feature_flag_reason',\n '$feature_flag_request_id',\n '$feature_flag_evaluated_at',\n '$feature_flag_error',\n 'locally_evaluated',\n '$groups',\n '$process_person_profile',\n '$geoip_disable',\n '$current_url',\n '$pathname',\n '$referring_domain',\n ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,\n '$session_id',\n '$window_id',\n '$lib',\n '$lib_version',\n '$device_id',\n '$is_server'\n];\nconst minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{\n const minimal = {};\n const copyKey = (key)=>{\n if (void 0 !== properties[key]) minimal[key] = properties[key];\n };\n MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);\n transportKeys.forEach(copyKey);\n return minimal;\n};\nexport { MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse, parsePayload, updateFlagValue };\n","var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {\n PostHogPersistedProperty[\"AnonymousId\"] = \"anonymous_id\";\n PostHogPersistedProperty[\"DistinctId\"] = \"distinct_id\";\n PostHogPersistedProperty[\"Props\"] = \"props\";\n PostHogPersistedProperty[\"EnablePersonProcessing\"] = \"enable_person_processing\";\n PostHogPersistedProperty[\"PersonMode\"] = \"person_mode\";\n PostHogPersistedProperty[\"FeatureFlagDetails\"] = \"feature_flag_details\";\n PostHogPersistedProperty[\"FeatureFlags\"] = \"feature_flags\";\n PostHogPersistedProperty[\"FeatureFlagPayloads\"] = \"feature_flag_payloads\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagDetails\"] = \"bootstrap_feature_flag_details\";\n PostHogPersistedProperty[\"BootstrapFeatureFlags\"] = \"bootstrap_feature_flags\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagPayloads\"] = \"bootstrap_feature_flag_payloads\";\n PostHogPersistedProperty[\"OverrideFeatureFlags\"] = \"override_feature_flags\";\n PostHogPersistedProperty[\"Queue\"] = \"queue\";\n PostHogPersistedProperty[\"AiQueue\"] = \"ai_queue\";\n PostHogPersistedProperty[\"AiCaptureQueue\"] = \"ai_capture_queue\";\n PostHogPersistedProperty[\"LogsQueue\"] = \"logs_queue\";\n PostHogPersistedProperty[\"OptedOut\"] = \"opted_out\";\n PostHogPersistedProperty[\"SessionId\"] = \"session_id\";\n PostHogPersistedProperty[\"SessionStartTimestamp\"] = \"session_start_timestamp\";\n PostHogPersistedProperty[\"SessionLastTimestamp\"] = \"session_timestamp\";\n PostHogPersistedProperty[\"PersonProperties\"] = \"person_properties\";\n PostHogPersistedProperty[\"GroupProperties\"] = \"group_properties\";\n PostHogPersistedProperty[\"InstalledAppBuild\"] = \"installed_app_build\";\n PostHogPersistedProperty[\"InstalledAppVersion\"] = \"installed_app_version\";\n PostHogPersistedProperty[\"SessionReplay\"] = \"session_replay\";\n PostHogPersistedProperty[\"PushRegistered\"] = \"push_registered\";\n PostHogPersistedProperty[\"SessionReplayEventTriggerActivatedSession\"] = \"session_replay_event_trigger_activated_session\";\n PostHogPersistedProperty[\"SurveyLastSeenDate\"] = \"survey_last_seen_date\";\n PostHogPersistedProperty[\"SurveysSeen\"] = \"surveys_seen\";\n PostHogPersistedProperty[\"Surveys\"] = \"surveys\";\n PostHogPersistedProperty[\"RemoteConfig\"] = \"remote_config\";\n PostHogPersistedProperty[\"FlagsEndpointWasHit\"] = \"flags_endpoint_was_hit\";\n PostHogPersistedProperty[\"DeviceId\"] = \"device_id\";\n return PostHogPersistedProperty;\n}({});\nvar types_Compression = /*#__PURE__*/ function(Compression) {\n Compression[\"GZipJS\"] = \"gzip-js\";\n Compression[\"Base64\"] = \"base64\";\n return Compression;\n}({});\nconst FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status)=>`api_error_${status}`\n};\nconst SurveyPosition = {\n TopLeft: 'top_left',\n TopCenter: 'top_center',\n TopRight: 'top_right',\n MiddleLeft: 'middle_left',\n MiddleCenter: 'middle_center',\n MiddleRight: 'middle_right',\n Left: 'left',\n Right: 'right',\n Center: 'center'\n};\nconst SurveyWidgetType = {\n Button: 'button',\n Tab: 'tab',\n Selector: 'selector'\n};\nconst SurveyType = {\n Popover: 'popover',\n API: 'api',\n Widget: 'widget',\n ExternalSurvey: 'external_survey'\n};\nconst SurveyQuestionDescriptionContentType = {\n Html: 'html',\n Text: 'text'\n};\nconst SurveyValidationType = {\n MinLength: 'min_length',\n MaxLength: 'max_length'\n};\nconst SurveyRatingDisplay = {\n Number: 'number',\n Emoji: 'emoji'\n};\nconst SurveyQuestionType = {\n Open: 'open',\n MultipleChoice: 'multiple_choice',\n SingleChoice: 'single_choice',\n Rating: 'rating',\n Link: 'link'\n};\nconst SurveyQuestionBranchingType = {\n NextQuestion: 'next_question',\n End: 'end',\n ResponseBased: 'response_based',\n SpecificQuestion: 'specific_question'\n};\nconst SurveyMatchType = {\n Regex: 'regex',\n NotRegex: 'not_regex',\n Exact: 'exact',\n IsNot: 'is_not',\n Icontains: 'icontains',\n NotIcontains: 'not_icontains'\n};\nconst SurveySchedule = {\n Once: 'once',\n Recurring: 'recurring',\n Always: 'always'\n};\nconst ActionStepStringMatching = {\n Contains: 'contains',\n Exact: 'exact',\n Regex: 'regex'\n};\nconst knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called'\n];\nconst knownUnsafeEditableEventProperty = [\n 'token'\n];\nexport { ActionStepStringMatching, types_Compression as Compression, FeatureFlagError, types_PostHogPersistedProperty as PostHogPersistedProperty, SurveyMatchType, SurveyPosition, SurveyQuestionBranchingType, SurveyQuestionDescriptionContentType, SurveyQuestionType, SurveyRatingDisplay, SurveySchedule, SurveyType, SurveyValidationType, SurveyWidgetType, knownUnsafeEditableEvent, knownUnsafeEditableEventProperty };\n","import { Compression } from \"./types.mjs\";\nfunction isGzipSupported() {\n return 'CompressionStream' in globalThis && 'TextEncoder' in globalThis && 'Response' in globalThis && 'function' == typeof Response.prototype.blob;\n}\nconst NATIVE_GZIP_VALIDATION_ERROR = 'NativeGzipValidationError';\nconst GZIP_MAGIC_FIRST_BYTE = 0x1f;\nconst GZIP_MAGIC_SECOND_BYTE = 0x8b;\nconst GZIP_DEFLATE_METHOD = 0x08;\nconst hasGzipMagic = (bytes)=>bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;\nconst isGzipData = (body)=>{\n if (body instanceof ArrayBuffer) return hasGzipMagic(new Uint8Array(body));\n if (ArrayBuffer.isView(body)) return hasGzipMagic(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return false;\n};\nconst isGzipRequest = (compression, urlCompression)=>compression === Compression.GZipJS || urlCompression === Compression.GZipJS || 'gzip' === urlCompression;\nconst isNativeAsyncGzipReadError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return 'NotReadableError' === name;\n};\nconst isNativeAsyncGzipError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return isNativeAsyncGzipReadError(error) || name === NATIVE_GZIP_VALIDATION_ERROR;\n};\nlet crc32Table;\nconst getCrc32Table = ()=>{\n if (crc32Table) return crc32Table;\n crc32Table = [];\n for(let i = 0; i < 256; i++){\n let crc = i;\n for(let j = 0; j < 8; j++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;\n crc32Table[i] = crc >>> 0;\n }\n return crc32Table;\n};\nconst crc32 = (bytes)=>{\n const table = getCrc32Table();\n let crc = 0xffffffff;\n for(let i = 0; i < bytes.length; i++)crc = table[(crc ^ bytes[i]) & 0xff] ^ crc >>> 8;\n return (0xffffffff ^ crc) >>> 0;\n};\nconst throwNativeGzipValidationError = (reason)=>{\n const error = new Error(`Native gzip produced invalid output: ${reason}`);\n error.name = NATIVE_GZIP_VALIDATION_ERROR;\n throw error;\n};\nconst validateNativeGzip = async (compressed, inputBytes)=>{\n if (compressed.size < 18) throwNativeGzipValidationError('too-short');\n const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());\n if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD) throwNativeGzipValidationError('invalid-header');\n const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());\n if (trailer.getUint32(0, true) !== crc32(inputBytes)) throwNativeGzipValidationError('invalid-crc');\n const inputSize = inputBytes.length >>> 0;\n if (trailer.getUint32(4, true) !== inputSize) throwNativeGzipValidationError('invalid-size');\n};\nasync function gzipCompress(input, isDebug = true, options) {\n try {\n const inputBytes = new TextEncoder().encode(input);\n const compressedStream = new globalThis.CompressionStream('gzip');\n const writer = compressedStream.writable.getWriter();\n const writePromise = writer.write(inputBytes).then(()=>writer.close()).catch(async (err)=>{\n try {\n await writer.abort(err);\n } catch {}\n throw err;\n });\n const responsePromise = new Response(compressedStream.readable).blob();\n const [compressed] = await Promise.all([\n responsePromise,\n writePromise\n ]);\n await validateNativeGzip(compressed, inputBytes);\n return compressed;\n } catch (error) {\n if (options?.rethrow) throw error;\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError };\n","const MAX_JSON_SAFE_VALUE_DEPTH = 20;\nconst MAX_JSON_SAFE_VALUE_ITEMS = 1000;\nconst MAX_JSON_SAFE_VALUE_NODES = 10000;\nconst CIRCULAR_VALUE = '[Circular]';\nconst TRUNCATED_VALUE = '[Truncated]';\nconst UNSERIALIZABLE_VALUE = '[Unserializable]';\nconst FUNCTION_VALUE = '[Function]';\nconst dateGetTime = Date.prototype.getTime;\nconst dateToISOString = Date.prototype.toISOString;\nconst propertyIsEnumerable = Object.prototype.propertyIsEnumerable;\nfunction sanitizeString(value) {\n let output = '';\n for(let index = 0; index < value.length; index++){\n const codeUnit = value.charCodeAt(index);\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const nextCodeUnit = value.charCodeAt(index + 1);\n if (nextCodeUnit >= 0xdc00 && nextCodeUnit <= 0xdfff) {\n output += value[index] + value[index + 1];\n index++;\n } else output += '\\ufffd';\n } else output += codeUnit >= 0xdc00 && codeUnit <= 0xdfff ? '\\ufffd' : value[index];\n }\n return output;\n}\nfunction toJsonSafeValue(value) {\n const state = {\n ancestors: new WeakSet(),\n remainingNodes: MAX_JSON_SAFE_VALUE_NODES\n };\n const convert = (current, depth)=>{\n if (state.remainingNodes <= 0) return TRUNCATED_VALUE;\n state.remainingNodes--;\n try {\n if (null == current || 'boolean' == typeof current) return current;\n if ('string' == typeof current) return sanitizeString(current);\n if ('number' == typeof current) return Number.isFinite(current) ? current : null;\n if ('bigint' == typeof current) return current.toString();\n if ('function' == typeof current) return FUNCTION_VALUE;\n if ('symbol' == typeof current) return current.description ? `Symbol(${current.description})` : 'Symbol()';\n if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) return TRUNCATED_VALUE;\n if (state.ancestors.has(current)) return CIRCULAR_VALUE;\n state.ancestors.add(current);\n try {\n if (current instanceof Date) return Number.isFinite(dateGetTime.call(current)) ? dateToISOString.call(current) : null;\n let hasToJSONResult = false;\n let toJSONResult;\n try {\n const toJSON = current.toJSON;\n if ('function' == typeof toJSON) {\n toJSONResult = toJSON.call(current);\n hasToJSONResult = true;\n }\n } catch {\n hasToJSONResult = false;\n }\n if (hasToJSONResult) return convert(toJSONResult, depth + 1);\n if (Array.isArray(current)) {\n const itemCount = Math.min(current.length, MAX_JSON_SAFE_VALUE_ITEMS);\n const output = [];\n let index = 0;\n for(; index < itemCount && state.remainingNodes > 0; index++)output.push(convert(current[index], depth + 1));\n if (current.length > index) output.push(TRUNCATED_VALUE);\n return output;\n }\n const output = {};\n let itemCount = 0;\n let truncated = false;\n for(const key in current){\n if (!propertyIsEnumerable.call(current, key)) break;\n if (itemCount >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {\n truncated = true;\n break;\n }\n const converted = convert(current[key], depth + 1);\n Object.defineProperty(output, key, {\n value: converted,\n enumerable: true,\n configurable: true,\n writable: true\n });\n itemCount++;\n }\n if (truncated) output[TRUNCATED_VALUE] = 'Additional properties omitted';\n return output;\n } finally{\n state.ancestors.delete(current);\n }\n } catch {\n return UNSERIALIZABLE_VALUE;\n }\n };\n return convert(value, 0);\n}\nexport { CIRCULAR_VALUE, FUNCTION_VALUE, MAX_JSON_SAFE_VALUE_DEPTH, MAX_JSON_SAFE_VALUE_ITEMS, MAX_JSON_SAFE_VALUE_NODES, TRUNCATED_VALUE, UNSERIALIZABLE_VALUE, sanitizeString, toJsonSafeValue };\n","const DEFAULT_BLOCKED_UA_STRS = [\n 'amazonbot',\n 'amazonproductbot',\n 'app.hypefactors.com',\n 'applebot',\n 'archive.org_bot',\n 'awariobot',\n 'backlinksextendedbot',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'dataforseobot',\n 'deepscan',\n 'duckduckbot',\n 'facebookexternal',\n 'facebookcatalog',\n 'http://yandex.com/bots',\n 'hubspot',\n 'ia_archiver',\n 'leikibot',\n 'linkedinbot',\n 'meta-externalagent',\n 'mj12bot',\n 'msnbot',\n 'nessus',\n 'petalbot',\n 'pinterest',\n 'prerender',\n 'rogerbot',\n 'screaming frog',\n 'sebot-wa',\n 'sitebulb',\n 'slackbot',\n 'slurp',\n 'trendictionbot',\n 'turnitin',\n 'twitterbot',\n 'vercel-screenshot',\n 'vercelbot',\n 'yahoo! slurp',\n 'yandexbot',\n 'zoombot',\n 'bot.htm',\n 'bot.php',\n '(bot;',\n 'bot/',\n 'crawler',\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'semrushbot',\n 'siteauditbot',\n 'splitsignalbot',\n 'gptbot',\n 'oai-searchbot',\n 'chatgpt-user',\n 'perplexitybot',\n 'better uptime bot',\n 'sentryuptimebot',\n 'uptimerobot',\n 'headlesschrome',\n 'cypress',\n 'google-hoteladsverifier',\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleother',\n 'google-cloudvertexbot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google',\n 'google-inspectiontool',\n 'bytespider'\n];\nconst isBlockedUA = function(ua, customBlockedUserAgents = []) {\n if (!ua) return false;\n const uaLower = ua.toLowerCase();\n return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA)=>{\n const blockedUaLower = blockedUA.toLowerCase();\n return -1 !== uaLower.indexOf(blockedUaLower);\n });\n};\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA };\n","function includes(str, needle) {\n return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n return [\n 'distinct_id',\n 'distinctid'\n ].includes(value.toLowerCase());\n}\nfunction safeJsonStringify(value) {\n const ancestors = [];\n return JSON.stringify(value, function(_key, replacementValue) {\n if ('bigint' == typeof replacementValue) return replacementValue.toString();\n if ('function' == typeof replacementValue || 'symbol' == typeof replacementValue) return;\n if (replacementValue instanceof Error) return {\n name: replacementValue.name,\n message: replacementValue.message,\n stack: replacementValue.stack\n };\n if (replacementValue && 'object' == typeof replacementValue) {\n while(ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)ancestors.pop();\n if (ancestors.includes(replacementValue)) return '[Circular]';\n ancestors.push(replacementValue);\n }\n return replacementValue;\n }) ?? 'null';\n}\nfunction deepSortKeys(value) {\n if (null === value || 'object' != typeof value) return value;\n if (Array.isArray(value)) return value.map(deepSortKeys);\n return Object.keys(value).sort().reduce((acc, key)=>{\n acc[key] = deepSortKeys(value[key]);\n return acc;\n }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n return JSON.stringify({\n distinct_id,\n userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, safeJsonStringify, stripLeadingDollar, trim };\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n if (min > max) {\n logger.warn('min cannot be greater than max.');\n min = max;\n }\n if (isNumber(value)) if (value > max) {\n logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');\n return max;\n } else {\n if (!(value < min)) return value;\n logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n return min;\n }\n logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n if (null == field) return defaultValue;\n if ('boolean' == typeof field) return field;\n if ('object' == typeof field) {\n const value = field[key];\n return 'boolean' == typeof value ? value : defaultValue;\n }\n return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n if (null == field || 'object' != typeof field) return;\n const value = field[key];\n if ('number' == typeof value && Number.isFinite(value)) return value;\n if ('string' == typeof value) {\n const trimmed = value.trim();\n if ('' === trimmed) return;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : void 0;\n }\n}\nfunction isValidSampleRate(value) {\n return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n","import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;\nfunction resolveExceptionRateLimiterConfig(config = {}) {\n return {\n refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,\n bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE\n };\n}\nclass BucketedRateLimiter {\n constructor(options){\n this._buckets = {};\n this._onBucketRateLimited = options._onBucketRateLimited;\n this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n }\n _applyRefill(bucket, now) {\n const elapsedMs = now - bucket.lastAccess;\n const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n if (refillIntervals > 0) {\n const tokensToAdd = refillIntervals * this._refillRate;\n bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n }\n }\n consumeRateLimit(key) {\n const now = Date.now();\n const keyStr = String(key);\n let bucket = this._buckets[keyStr];\n if (bucket) this._applyRefill(bucket, now);\n else {\n bucket = {\n tokens: this._bucketSize,\n lastAccess: now\n };\n this._buckets[keyStr] = bucket;\n }\n if (0 === bucket.tokens) return true;\n bucket.tokens--;\n if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n return 0 === bucket.tokens;\n }\n stop() {\n this._buckets = {};\n }\n}\nexport { BucketedRateLimiter, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE, resolveExceptionRateLimiterConfig };\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n */ const DIGITS = \"0123456789abcdef\";\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n }\n static ofInner(bytes) {\n if (16 === bytes.length) return new UUID(bytes);\n throw new TypeError(\"not 128-bit length\");\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError(\"invalid field value\");\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n static parse(uuid) {\n let hex;\n switch(uuid.length){\n case 32:\n hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];\n break;\n case 36:\n 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(\"\");\n break;\n case 38:\n 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(\"\");\n break;\n case 45:\n 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(\"\");\n break;\n default:\n break;\n }\n if (hex) {\n const inner = new Uint8Array(16);\n for(let i = 0; i < 16; i += 4){\n const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);\n inner[i + 0] = n >>> 24;\n inner[i + 1] = n >>> 16;\n inner[i + 2] = n >>> 8;\n inner[i + 3] = n;\n }\n return new UUID(inner);\n }\n throw new SyntaxError(\"could not parse UUID string\");\n }\n toString() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += \"-\";\n }\n return text;\n }\n toHex() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n }\n return text;\n }\n toJSON() {\n return this.toString();\n }\n getVariant() {\n const n = this.bytes[8] >>> 4;\n if (n < 0) throw new Error(\"unreachable\");\n if (n <= 7) return this.bytes.every((e)=>0 === e) ? \"NIL\" : \"VAR_0\";\n if (n <= 11) return \"VAR_10\";\n if (n <= 13) return \"VAR_110\";\n if (n <= 15) return this.bytes.every((e)=>0xff === e) ? \"MAX\" : \"VAR_RESERVED\";\n else throw new Error(\"unreachable\");\n }\n getVersion() {\n return \"VAR_10\" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n constructor(randomNumberGenerator){\n this.timestamp = 0;\n this.counter = 0;\n this.random = randomNumberGenerator ?? getDefaultRandom();\n }\n generate() {\n return this.generateOrResetCore(Date.now(), 10000);\n }\n generateOrAbort() {\n return this.generateOrAbortCore(Date.now(), 10000);\n }\n generateOrResetCore(unixTsMs, rollbackAllowance) {\n let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n if (void 0 === value) {\n this.timestamp = 0;\n value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n }\n return value;\n }\n generateOrAbortCore(unixTsMs, rollbackAllowance) {\n const MAX_COUNTER = 0x3ffffffffff;\n if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 0xffffffffffff) throw new RangeError(\"`unixTsMs` must be a 48-bit positive integer\");\n if (rollbackAllowance < 0 || rollbackAllowance > 0xffffffffffff) throw new RangeError(\"`rollbackAllowance` out of reasonable range\");\n if (unixTsMs > this.timestamp) {\n this.timestamp = unixTsMs;\n this.resetCounter();\n } else {\n if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;\n this.counter++;\n if (this.counter > MAX_COUNTER) {\n this.timestamp++;\n this.resetCounter();\n }\n }\n return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());\n }\n resetCounter() {\n this.counter = 0x400 * this.random.nextUint32() + (0x3ff & this.random.nextUint32());\n }\n generateV4() {\n const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);\n bytes[6] = 0x40 | bytes[6] >>> 4;\n bytes[8] = 0x80 | bytes[8] >>> 2;\n return UUID.ofInner(bytes);\n }\n}\nconst getDefaultRandom = ()=>({\n nextUint32: ()=>0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random())\n });\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuidv4 = ()=>uuidv4obj().toString();\nconst uuidv4obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generateV4();\nexport { UUID, V7Generator, uuidv4, uuidv4obj, uuidv7, uuidv7obj };\n","import { uuidv7 } from \"../vendor/uuidv7.mjs\";\nclass PromiseQueue {\n add(promise) {\n const promiseUUID = uuidv7();\n const id = ++this.nextId;\n this.promiseByIds[promiseUUID] = {\n id,\n promise\n };\n promise.catch(()=>{}).finally(()=>{\n delete this.promiseByIds[promiseUUID];\n });\n return promise;\n }\n async join() {\n let promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n let length = promises.length;\n while(length > 0){\n await Promise.all(promises);\n promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n length = promises.length;\n }\n }\n getPromises(ignoredPromises = [], maxId = this.nextId) {\n const ignoredPromiseSet = new Set(ignoredPromises);\n return Object.values(this.promiseByIds).filter((item)=>item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item)=>item.promise);\n }\n get maxId() {\n return this.nextId;\n }\n get length() {\n return Object.keys(this.promiseByIds).length;\n }\n constructor(){\n this.promiseByIds = {};\n this.nextId = 0;\n }\n}\nexport { PromiseQueue };\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { includes } from \"./string-utils.mjs\";\nimport { isFunction, isUndefined } from \"./type-utils.mjs\";\nconst FACEBOOK = 'Facebook';\nconst MOBILE = 'Mobile';\nconst IOS = 'iOS';\nconst ANDROID = 'Android';\nconst TABLET = 'Tablet';\nconst ANDROID_TABLET = ANDROID + ' ' + TABLET;\nconst IPAD = 'iPad';\nconst APPLE = 'Apple';\nconst APPLE_WATCH = APPLE + ' Watch';\nconst SAFARI = 'Safari';\nconst BLACKBERRY = 'BlackBerry';\nconst SAMSUNG = 'Samsung';\nconst SAMSUNG_BROWSER = SAMSUNG + 'Browser';\nconst SAMSUNG_INTERNET = SAMSUNG + ' Internet';\nconst CHROME = 'Chrome';\nconst CHROME_OS = CHROME + ' OS';\nconst CHROME_IOS = CHROME + ' ' + IOS;\nconst INTERNET_EXPLORER = 'Internet Explorer';\nconst INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;\nconst OPERA = 'Opera';\nconst OPERA_MINI = OPERA + ' Mini';\nconst EDGE = 'Edge';\nconst MICROSOFT_EDGE = 'Microsoft ' + EDGE;\nconst FIREFOX = 'Firefox';\nconst FIREFOX_IOS = FIREFOX + ' ' + IOS;\nconst NINTENDO = 'Nintendo';\nconst PLAYSTATION = 'PlayStation';\nconst XBOX = 'Xbox';\nconst ANDROID_MOBILE = ANDROID + ' ' + MOBILE;\nconst MOBILE_SAFARI = MOBILE + ' ' + SAFARI;\nconst WINDOWS = 'Windows';\nconst WINDOWS_PHONE = WINDOWS + ' Phone';\nconst NOKIA = 'Nokia';\nconst OUYA = 'Ouya';\nconst GENERIC = 'Generic';\nconst GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();\nconst GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();\nconst KONQUEROR = 'Konqueror';\nconst OCULUS_BROWSER = 'Oculus Browser';\nconst VIVALDI = 'Vivaldi';\nconst YANDEX = 'Yandex';\nconst WHALE = 'Whale';\nconst DUCKDUCKGO = 'DuckDuckGo';\nconst PALE_MOON = 'Pale Moon';\nconst WATERFOX = 'Waterfox';\nconst BRAVE = 'Brave';\nconst GOOGLE_SEARCH_APP = 'Google Search App';\nconst BROWSER_VERSION_REGEX_SUFFIX = '(\\\\d+(\\\\.\\\\d+)?)';\nconst DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);\nfunction browserFromHints(hints) {\n if (hints?.brave) return BRAVE;\n return null;\n}\nconst XBOX_REGEX = new RegExp(XBOX, 'i');\nconst PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\\\w+', 'i');\nconst NINTENDO_REGEX = new RegExp(NINTENDO + ' \\\\w+', 'i');\nconst BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');\nconst windowsVersionMap = {\n 'NT3.51': 'NT 3.11',\n 'NT4.0': 'NT 4.0',\n '5.0': '2000',\n '5.1': 'XP',\n '5.2': 'XP',\n '6.0': 'Vista',\n '6.1': '7',\n '6.2': '8',\n '6.3': '8.1',\n '6.4': '10',\n '10.0': '10'\n};\nfunction isSafari(userAgent) {\n return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);\n}\nconst safariCheck = (ua, vendor)=>vendor && includes(vendor, APPLE) || isSafari(ua);\nconst detectBrowser = function(user_agent, vendor, hints, options) {\n vendor = vendor || '';\n const fromHints = browserFromHints(hints);\n if (fromHints) return fromHints;\n if (options?.detectGoogleSearchApp && includes(user_agent, 'GSA/')) return GOOGLE_SEARCH_APP;\n if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) return OPERA_MINI;\n if (includes(user_agent, ' OPR/')) return OPERA;\n if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) return INTERNET_EXPLORER_MOBILE;\n if (includes(user_agent, 'OculusBrowser')) return OCULUS_BROWSER;\n else if (includes(user_agent, SAMSUNG_BROWSER)) return SAMSUNG_INTERNET;\n else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) return MICROSOFT_EDGE;\n else if (includes(user_agent, VIVALDI + '/')) return VIVALDI;\n else if (includes(user_agent, 'YaBrowser/')) return YANDEX;\n else if (includes(user_agent, WHALE + '/')) return WHALE;\n else if (includes(user_agent, DUCKDUCKGO + '/') || includes(user_agent, 'Ddg/')) return DUCKDUCKGO;\n else if (includes(user_agent, 'FBIOS')) return FACEBOOK + ' ' + MOBILE;\n else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) return 'UC Browser';\n else if (includes(user_agent, 'CriOS')) return CHROME_IOS;\n else if (includes(user_agent, 'CrMo')) return CHROME;\n else if (includes(user_agent, CHROME)) return CHROME;\n else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) return ANDROID_MOBILE;\n else if (includes(user_agent, 'FxiOS')) return FIREFOX_IOS;\n else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) return KONQUEROR;\n else if (includes(user_agent, BRAVE + '/')) return BRAVE;\n else if (safariCheck(user_agent, vendor)) return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;\n else if (includes(user_agent, 'PaleMoon/')) return PALE_MOON;\n else if (includes(user_agent, WATERFOX + '/')) return WATERFOX;\n else if (includes(user_agent, FIREFOX)) return FIREFOX;\n else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) return INTERNET_EXPLORER;\n else if (includes(user_agent, 'Gecko')) return FIREFOX;\n return '';\n};\nconst versionRegexes = {\n [INTERNET_EXPLORER_MOBILE]: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [MICROSOFT_EDGE]: [\n new RegExp(EDGE + '?\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME]: [\n new RegExp('(' + CHROME + '|CrMo)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME_IOS]: [\n new RegExp('CriOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n 'UC Browser': [\n new RegExp('(UCBrowser|UCWEB)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [MOBILE_SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [OPERA]: [\n new RegExp('(' + OPERA + '|OPR)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX]: [\n new RegExp(FIREFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX_IOS]: [\n new RegExp('FxiOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [KONQUEROR]: [\n new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [BLACKBERRY]: [\n new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX),\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [ANDROID_MOBILE]: [\n new RegExp('android\\\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [SAMSUNG_INTERNET]: [\n new RegExp(SAMSUNG_BROWSER + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [OCULUS_BROWSER]: [\n new RegExp('OculusBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [VIVALDI]: [\n new RegExp(VIVALDI + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [YANDEX]: [\n new RegExp('YaBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WHALE]: [\n new RegExp(WHALE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [BRAVE]: [\n new RegExp(BRAVE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [DUCKDUCKGO]: [\n new RegExp('(DuckDuckGo|Ddg)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [PALE_MOON]: [\n new RegExp('PaleMoon\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WATERFOX]: [\n new RegExp(WATERFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [GOOGLE_SEARCH_APP]: [\n new RegExp('GSA\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [INTERNET_EXPLORER]: [\n new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n Mozilla: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ]\n};\nconst detectBrowserVersion = function(userAgent, vendor, hints, options) {\n const browser = detectBrowser(userAgent, vendor, hints, options);\n const regexes = versionRegexes[browser];\n if (isUndefined(regexes)) return null;\n for(let i = 0; i < regexes.length; i++){\n const regex = regexes[i];\n const matches = userAgent.match(regex);\n if (matches) return parseFloat(matches[matches.length - 2]);\n }\n return null;\n};\nconst osMatchers = [\n [\n new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'),\n (match)=>[\n XBOX,\n match && match[1] || ''\n ]\n ],\n [\n new RegExp(NINTENDO, 'i'),\n [\n NINTENDO,\n ''\n ]\n ],\n [\n new RegExp(PLAYSTATION, 'i'),\n [\n PLAYSTATION,\n ''\n ]\n ],\n [\n BLACKBERRY_REGEX,\n [\n BLACKBERRY,\n ''\n ]\n ],\n [\n new RegExp(WINDOWS, 'i'),\n (_, user_agent)=>{\n if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [\n WINDOWS_PHONE,\n ''\n ];\n if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\\b/.test(user_agent)) return [\n WINDOWS + ' ' + MOBILE,\n ''\n ];\n const match = /Windows NT ([0-9.]+)/i.exec(user_agent);\n if (match && match[1]) {\n const version = match[1];\n let osVersion = windowsVersionMap[version] || '';\n if (/arm/i.test(user_agent)) osVersion = 'RT';\n return [\n WINDOWS,\n osVersion\n ];\n }\n return [\n WINDOWS,\n ''\n ];\n }\n ],\n [\n /((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,\n (match)=>{\n if (match && match[3]) {\n const versionParts = [\n match[3],\n match[4],\n match[5] || '0'\n ];\n return [\n IOS,\n versionParts.join('.')\n ];\n }\n return [\n IOS,\n ''\n ];\n }\n ],\n [\n /(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,\n (match)=>{\n let version = '';\n if (match && match.length >= 3) version = isUndefined(match[2]) ? match[3] : match[2];\n return [\n 'watchOS',\n version\n ];\n }\n ],\n [\n new RegExp('(' + ANDROID + ' (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|' + ANDROID + ')', 'i'),\n (match)=>{\n if (match && match[2]) {\n const versionParts = [\n match[2],\n match[3],\n match[4] || '0'\n ];\n return [\n ANDROID,\n versionParts.join('.')\n ];\n }\n return [\n ANDROID,\n ''\n ];\n }\n ],\n [\n /Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,\n (match)=>{\n const result = [\n 'Mac OS X',\n ''\n ];\n if (match && match[1]) {\n const versionParts = [\n match[1],\n match[2],\n match[3] || '0'\n ];\n result[1] = versionParts.join('.');\n }\n return result;\n }\n ],\n [\n /Mac/i,\n [\n 'Mac OS X',\n ''\n ]\n ],\n [\n /CrOS/,\n [\n CHROME_OS,\n ''\n ]\n ],\n [\n /Linux|debian/i,\n [\n 'Linux',\n ''\n ]\n ]\n];\nconst detectOS = function(user_agent) {\n for(let i = 0; i < osMatchers.length; i++){\n const [rgex, resultOrFn] = osMatchers[i];\n const match = rgex.exec(user_agent);\n const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);\n if (result) return result;\n }\n return [\n '',\n ''\n ];\n};\nconst detectDevice = function(user_agent) {\n if (NINTENDO_REGEX.test(user_agent)) return NINTENDO;\n if (PLAYSTATION_REGEX.test(user_agent)) return PLAYSTATION;\n if (XBOX_REGEX.test(user_agent)) return XBOX;\n if (new RegExp(OUYA, 'i').test(user_agent)) return OUYA;\n if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) return WINDOWS_PHONE;\n else if (/iPad/.test(user_agent)) return IPAD;\n else if (/iPod/.test(user_agent)) return 'iPod Touch';\n else if (/iPhone/.test(user_agent)) return 'iPhone';\n else if (/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(user_agent)) return APPLE_WATCH;\n else if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n else if (/(kobo)\\s(ereader|touch)/i.test(user_agent)) return 'Kobo';\n else if (new RegExp(NOKIA, 'i').test(user_agent)) return NOKIA;\n else if (/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(user_agent) || /(kf[a-z]+)( bui|\\)).+silk\\//i.test(user_agent)) return 'Kindle Fire';\n else if (/(Android|ZTE)/i.test(user_agent)) if (!(!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent))) return ANDROID;\n else {\n if (/pixel[\\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) return ANDROID;\n return ANDROID_TABLET;\n }\n else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) return GENERIC_MOBILE;\n else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) return GENERIC_TABLET;\n else return '';\n};\nconst detectDeviceType = function(user_agent, options) {\n const device = detectDevice(user_agent);\n if (device === IPAD || device === ANDROID_TABLET || 'Kobo' === device || 'Kindle Fire' === device || device === GENERIC_TABLET) return TABLET;\n if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) return 'Console';\n if (device === APPLE_WATCH) return 'Wearable';\n if (device) return MOBILE;\n if (options?.userAgentDataPlatform === 'Android' && (options?.maxTouchPoints ?? 0) > 0) {\n const shortSide = Math.min(options?.screenWidth ?? 0, options?.screenHeight ?? 0);\n const shortSideDp = shortSide / (options?.devicePixelRatio ?? 1);\n return shortSideDp >= 600 ? TABLET : MOBILE;\n }\n return 'Desktop';\n};\nexport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS };\n","import { toJsonSafeValue } from \"./json-utils.mjs\";\nexport * from \"./bot-detection.mjs\";\nexport * from \"./browser-utils.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isValidUUID(value) {\n return 'string' == typeof value && UUID_REGEX.test(value);\n}\nfunction getEventUuid(uuid, generateUuid) {\n return isValidUUID(uuid) ? uuid : generateUuid();\n}\nfunction assert(truthyValue, message) {\n if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n if (0 === truthyValue.trim().length) return true;\n return false;\n}\nfunction removeTrailingSlash(url) {\n return url?.replace(/\\/+$/, '');\n}\nfunction stripUrlHash(url) {\n if (!url) return url;\n return url.split('#')[0];\n}\nasync function retriable(fn, props) {\n let lastError = null;\n for(let i = 0; i < props.retryCount + 1; i++){\n if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n try {\n const res = await fn();\n return res;\n } catch (e) {\n lastError = e;\n if (!props.retryCheck(e)) throw e;\n }\n }\n throw lastError;\n}\nfunction currentTimestamp() {\n return new Date().getTime();\n}\nfunction currentISOTime() {\n return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n const t = setTimeout(fn, timeout);\n t?.unref && t?.unref();\n return t;\n}\nasync function raceWithTimeout(promise, timeoutMs, onTimeout) {\n let timeoutHandle;\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject)=>{\n timeoutHandle = safeSetTimeout(()=>{\n try {\n onTimeout?.();\n resolve();\n } catch (error) {\n reject(error);\n }\n }, timeoutMs);\n })\n ]);\n } finally{\n clearTimeout(timeoutHandle);\n }\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nfunction getFetch() {\n return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n status: 'fulfilled',\n value\n }), (reason)=>({\n status: 'rejected',\n reason\n }))));\n}\nexport { STRING_FORMAT, UUID_REGEX, allSettled, assert, currentISOTime, currentTimestamp, getEventUuid, getFetch, isPromise, isValidUUID, raceWithTimeout, removeTrailingSlash, retriable, safeSetTimeout, stripUrlHash, toJsonSafeValue };\n","import { isArray, isBoolean, isNull, isNullish, isUndefined } from \"../utils/index.mjs\";\nimport { CIRCULAR_VALUE, FUNCTION_VALUE, MAX_JSON_SAFE_VALUE_DEPTH, MAX_JSON_SAFE_VALUE_ITEMS, MAX_JSON_SAFE_VALUE_NODES, TRUNCATED_VALUE, UNSERIALIZABLE_VALUE, sanitizeString } from \"../utils/json-utils.mjs\";\nconst OTLP_SEVERITY_MAP = {\n trace: {\n text: 'TRACE',\n number: 1\n },\n debug: {\n text: 'DEBUG',\n number: 5\n },\n info: {\n text: 'INFO',\n number: 9\n },\n warn: {\n text: 'WARN',\n number: 13\n },\n error: {\n text: 'ERROR',\n number: 17\n },\n fatal: {\n text: 'FATAL',\n number: 21\n }\n};\nconst DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;\nfunction getOtlpSeverityText(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).text;\n}\nfunction getOtlpSeverityNumber(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number;\n}\nconst INT64_RANGE_LIMIT = 9223372036854775808;\nconst propertyIsEnumerable = Object.prototype.propertyIsEnumerable;\nfunction newState() {\n return {\n ancestors: new WeakSet(),\n remainingNodes: MAX_JSON_SAFE_VALUE_NODES\n };\n}\nfunction toOtlpAnyValue(value, logger) {\n try {\n return encodeAnyValue(value, logger, newState(), 0);\n } catch {\n return {\n stringValue: UNSERIALIZABLE_VALUE\n };\n }\n}\nfunction toOtlpKeyValueList(attrs, logger) {\n try {\n return encodeKeyValueList(attrs, logger, newState(), 0);\n } catch {\n return [];\n }\n}\nfunction encodeAnyValue(value, logger, state, depth) {\n if (state.remainingNodes <= 0) return {\n stringValue: TRUNCATED_VALUE\n };\n state.remainingNodes--;\n if (isBoolean(value)) return {\n boolValue: value\n };\n if ('number' == typeof value) {\n if (!Number.isFinite(value)) return {\n stringValue: String(value)\n };\n if (Number.isInteger(value)) {\n if (Number.isSafeInteger(value)) return {\n intValue: String(value)\n };\n if ('undefined' == typeof BigInt) return {\n stringValue: String(value)\n };\n const decimal = BigInt(value).toString();\n if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {\n logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);\n return {\n stringValue: decimal\n };\n }\n return {\n intValue: decimal\n };\n }\n return {\n doubleValue: value\n };\n }\n if ('string' == typeof value) return {\n stringValue: sanitizeString(value)\n };\n if ('function' == typeof value) return {\n stringValue: FUNCTION_VALUE\n };\n if ('symbol' == typeof value) return {\n stringValue: String(value)\n };\n if ('object' == typeof value && null !== value) {\n if (state.ancestors.has(value)) return {\n stringValue: CIRCULAR_VALUE\n };\n if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) return {\n stringValue: TRUNCATED_VALUE\n };\n if (value instanceof Date) {\n const time = value.getTime();\n const iso = Number.isFinite(time) ? value.toISOString() : String(value);\n return {\n stringValue: 'string' == typeof iso ? sanitizeString(iso) : String(iso)\n };\n }\n state.ancestors.add(value);\n try {\n try {\n const toJSON = value.toJSON;\n if ('function' == typeof toJSON) return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);\n } catch {}\n if (isArray(value)) return {\n arrayValue: {\n values: encodeArrayValues(value, logger, state, depth + 1)\n }\n };\n return {\n kvlistValue: {\n values: encodeKeyValueList(value, logger, state, depth + 1)\n }\n };\n } finally{\n state.ancestors.delete(value);\n }\n }\n return {\n stringValue: sanitizeString(String(value))\n };\n}\nfunction encodeArrayValues(values, logger, state, depth) {\n const result = [];\n const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);\n let index = 0;\n for(; index < itemCount && state.remainingNodes > 0; index++)try {\n const element = index in values ? values[index] : void 0;\n if (isNullish(element)) continue;\n result.push(encodeAnyValue(element, logger, state, depth));\n } catch {\n result.push({\n stringValue: UNSERIALIZABLE_VALUE\n });\n }\n if (values.length > index) result.push({\n stringValue: TRUNCATED_VALUE\n });\n return result;\n}\nfunction encodeKeyValueList(attrs, logger, state, depth) {\n const result = [];\n for(const key in attrs)if (propertyIsEnumerable.call(attrs, key)) {\n if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {\n logger?.debug('Attributes truncated: the value exceeds the OTLP encoder budget');\n break;\n }\n try {\n const value = attrs[key];\n if (isNull(value) || isUndefined(value)) continue;\n result.push({\n key: sanitizeString(key),\n value: encodeAnyValue(value, logger, state, depth)\n });\n } catch {\n result.push({\n key: sanitizeString(key),\n value: {\n stringValue: UNSERIALIZABLE_VALUE\n }\n });\n }\n }\n return result;\n}\nfunction timestampToUnixNano() {\n return String(Date.now()) + '000000';\n}\nfunction encodeBody(body) {\n try {\n return sanitizeString(String(body));\n } catch {\n return UNSERIALIZABLE_VALUE;\n }\n}\nfunction buildOtlpLogRecord(options, sdkContext, logger) {\n const level = options.level || 'info';\n const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY;\n const now = timestampToUnixNano();\n const autoAttributes = {};\n if (sdkContext.distinctId) autoAttributes.posthogDistinctId = sdkContext.distinctId;\n if (sdkContext.sessionId) autoAttributes.sessionId = sdkContext.sessionId;\n if (sdkContext.windowId) autoAttributes['window.id'] = sdkContext.windowId;\n if (!isNullish(sdkContext.sessionStartTimestamp)) autoAttributes.sessionStartTimestamp = String(sdkContext.sessionStartTimestamp);\n if (!isNullish(sdkContext.lastActivityTimestamp)) autoAttributes.lastActivityTimestamp = String(sdkContext.lastActivityTimestamp);\n if (sdkContext.currentUrl) autoAttributes['url.full'] = sdkContext.currentUrl;\n if (sdkContext.screenName) autoAttributes['screen.name'] = sdkContext.screenName;\n if (sdkContext.appState) autoAttributes['app.state'] = sdkContext.appState;\n if (sdkContext.activeFeatureFlags && sdkContext.activeFeatureFlags.length > 0) autoAttributes.feature_flags = sdkContext.activeFeatureFlags;\n const mergedAttributes = {\n ...autoAttributes\n };\n const userAttributes = options.attributes;\n if (userAttributes) {\n let keys = [];\n try {\n keys = Object.keys(userAttributes);\n } catch {\n keys = [];\n }\n for (const key of keys){\n let value;\n try {\n value = userAttributes[key];\n } catch {\n value = UNSERIALIZABLE_VALUE;\n }\n Object.defineProperty(mergedAttributes, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true\n });\n }\n }\n const record = {\n timeUnixNano: now,\n observedTimeUnixNano: now,\n severityNumber,\n severityText,\n body: {\n stringValue: encodeBody(options.body)\n },\n attributes: toOtlpKeyValueList(mergedAttributes, logger)\n };\n if (options.trace_id) record.traceId = options.trace_id;\n if (options.span_id) record.spanId = options.span_id;\n if (!isUndefined(options.trace_flags)) record.flags = options.trace_flags;\n return record;\n}\nfunction buildResourceAttributes(config, sdkName, sdkVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': sdkName,\n 'telemetry.sdk.version': sdkVersion\n };\n}\nfunction buildOtlpLogsPayload(logRecords, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceLogs: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeLogs: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n logRecords\n }\n ]\n }\n ]\n };\n}\nexport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList };\n","import { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nconst DEFAULT_HISTOGRAM_BOUNDS = [\n 0,\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000\n];\nfunction msToUnixNano(ms) {\n return String(ms) + '000000';\n}\nfunction seriesKey(type, name, unit, attributes) {\n let attrsKey = '';\n if (attributes) {\n const keys = Object.keys(attributes).sort();\n attrsKey = keys.map((k)=>`${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(',');\n }\n return `${type}\\u0000${name}\\u0000${unit ?? ''}\\u0000${attrsKey}`;\n}\nfunction bucketIndexFor(value, bounds) {\n for(let i = 0; i < bounds.length; i++)if (value <= bounds[i]) return i;\n return bounds.length;\n}\nfunction buildMetricsResourceAttributes(config, scopeName, scopeVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': scopeName,\n 'telemetry.sdk.version': scopeVersion\n };\n}\nfunction buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceMetrics: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeMetrics: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n metrics\n }\n ]\n }\n ]\n };\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey };\n","const DEFAULT_FLUSH_INTERVAL_MS = 10000;\nconst DEFAULT_MAX_SERIES_PER_FLUSH = 1000;\nfunction resolveMetricsConfig(config) {\n const resourceAttributes = config?.resourceAttributes;\n return {\n serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,\n serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,\n environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,\n resourceAttributes,\n beforeSend: config?.beforeSend,\n flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH\n };\n}\nexport { resolveMetricsConfig };\n","import { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nimport { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey } from \"./metrics-utils.mjs\";\nimport { resolveMetricsConfig } from \"./config.mjs\";\nconst OTLP_TEMPORALITY_DELTA = 1;\nclass PostHogMetrics {\n constructor(_instance, _config, _logger){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n this._generation = 0;\n }\n count(name, value = 1, options) {\n this._capture({\n name,\n type: 'count',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n gauge(name, value, options) {\n this._capture({\n name,\n type: 'gauge',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n histogram(name, value, options) {\n this._capture({\n name,\n type: 'histogram',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n flush() {\n const prev = this._flushPromise;\n const run = async ()=>{\n if (prev) await prev.catch(()=>{});\n await this._doFlush();\n };\n const p = run().finally(()=>{\n if (this._flushPromise === p) this._flushPromise = null;\n });\n this._flushPromise = p;\n return p;\n }\n drainWindow() {\n if (0 === this._series.size) return null;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n return this._buildPayload(window);\n }\n reset() {\n this._generation++;\n this._clearFlushTimer();\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n }\n _capture(sample) {\n if (this._instance.isDisabled || this._instance.optedOut) return;\n const filtered = this._runBeforeSend(sample);\n if (null === filtered) return;\n if (!filtered.name || 'string' != typeof filtered.name) return void this._logger.warn('Dropping metric with empty name');\n if ('number' != typeof filtered.value || !Number.isFinite(filtered.value)) return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);\n if ('count' === filtered.type && filtered.value < 0) return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);\n let attributes;\n let key;\n try {\n attributes = filtered.attributes ? {\n ...filtered.attributes\n } : void 0;\n key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);\n } catch (e) {\n this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);\n return;\n }\n let state = this._series.get(key);\n if (!state) {\n if (!this._admitNewSeries()) return;\n state = {\n name: filtered.name,\n type: filtered.type,\n unit: filtered.unit,\n attributes,\n windowStartMs: Date.now()\n };\n this._series.set(key, state);\n }\n const seenType = this._typeByName.get(filtered.name);\n if (void 0 === seenType) this._typeByName.set(filtered.name, filtered.type);\n else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {\n this._typeCollisionWarned.add(filtered.name);\n this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);\n }\n this._fold(state, filtered.value);\n this._armFlushTimer();\n }\n _admitNewSeries() {\n if (this._series.size < this._config.maxSeriesPerFlush) return true;\n if (!this._seriesCapWarned) {\n this._seriesCapWarned = true;\n this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);\n }\n return false;\n }\n _fold(state, value) {\n switch(state.type){\n case 'count':\n state.total = (state.total ?? 0) + value;\n break;\n case 'gauge':\n state.last = value;\n break;\n case 'histogram':\n {\n if (!state.hist) state.hist = {\n count: 0,\n sum: 0,\n min: value,\n max: value,\n bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)\n };\n const hist = state.hist;\n hist.count += 1;\n hist.sum += value;\n hist.min = Math.min(hist.min, value);\n hist.max = Math.max(hist.max, value);\n hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;\n break;\n }\n }\n }\n _runBeforeSend(sample) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return sample;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = sample;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Metric was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for metric:\", e);\n return null;\n }\n return result;\n }\n _armFlushTimer() {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this.flush().catch((e)=>{\n this._logger.error('Metrics flush failed:', e);\n });\n }, this._config.flushIntervalMs);\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n async _doFlush() {\n if (0 === this._series.size) return;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n const generation = this._generation;\n const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));\n if (generation !== this._generation) return;\n switch(outcome.kind){\n case 'ok':\n return;\n case 'retry-later':\n this._mergeWindowBack(window);\n this._armFlushTimer();\n return;\n case 'too-large':\n this._logger.warn('Metrics batch exceeded the server size limit and was dropped');\n return;\n case 'fatal':\n this._logger.error('Failed to send metrics batch:', outcome.error);\n return;\n }\n }\n _buildPayload(window) {\n return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _buildMetrics(window) {\n const nowNano = msToUnixNano(Date.now());\n const byMetric = new Map();\n for (const state of window.values()){\n const metricKey = seriesKey(state.type, state.name, state.unit, void 0);\n let metric = byMetric.get(metricKey);\n if (!metric) {\n metric = {\n name: state.name,\n ...state.unit && {\n unit: state.unit\n }\n };\n if ('count' === state.type) metric.sum = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n isMonotonic: true,\n dataPoints: []\n };\n else if ('gauge' === state.type) metric.gauge = {\n dataPoints: []\n };\n else metric.histogram = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n dataPoints: []\n };\n byMetric.set(metricKey, metric);\n }\n const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);\n const startNano = msToUnixNano(state.windowStartMs);\n if ('count' === state.type) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n asDouble: state.total ?? 0\n };\n metric.sum.dataPoints.push(dp);\n } else if ('gauge' === state.type) {\n const dp = {\n attributes,\n timeUnixNano: nowNano,\n asDouble: state.last ?? 0\n };\n metric.gauge.dataPoints.push(dp);\n } else if (state.hist) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n count: state.hist.count,\n sum: state.hist.sum,\n min: state.hist.min,\n max: state.hist.max,\n bucketCounts: state.hist.bucketCounts,\n explicitBounds: DEFAULT_HISTOGRAM_BOUNDS\n };\n metric.histogram.dataPoints.push(dp);\n }\n }\n return Array.from(byMetric.values());\n }\n _mergeWindowBack(window) {\n for (const [key, old] of window){\n const current = this._series.get(key);\n if (!current) {\n if (this._admitNewSeries()) this._series.set(key, old);\n continue;\n }\n current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);\n switch(current.type){\n case 'count':\n current.total = (current.total ?? 0) + (old.total ?? 0);\n break;\n case 'gauge':\n break;\n case 'histogram':\n if (old.hist) if (current.hist) {\n current.hist.count += old.hist.count;\n current.hist.sum += old.hist.sum;\n current.hist.min = Math.min(current.hist.min, old.hist.min);\n current.hist.max = Math.max(current.hist.max, old.hist.max);\n for(let i = 0; i < current.hist.bucketCounts.length; i++)current.hist.bucketCounts[i] += old.hist.bucketCounts[i];\n } else current.hist = old.hist;\n break;\n }\n }\n }\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig };\n","class SimpleEventEmitter {\n constructor(){\n this.events = {};\n this.events = {};\n }\n on(event, listener) {\n if (!this.events[event]) this.events[event] = [];\n this.events[event].push(listener);\n return ()=>{\n this.events[event] = this.events[event].filter((x)=>x !== listener);\n };\n }\n emit(event, payload) {\n for (const listener of this.events[event] || [])listener(payload);\n for (const listener of this.events['*'] || [])listener(event, payload);\n }\n}\nexport { SimpleEventEmitter };\n","let parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameChunkIds;\nfunction getFilenameToChunkIdMap(stackParser) {\n const chunkIdMap = globalThis._posthogChunkIds;\n if (!chunkIdMap) return;\n const chunkIdKeys = Object.keys(chunkIdMap);\n if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;\n lastKeysCount = chunkIdKeys.length;\n cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{\n if (!parsedStackResults) parsedStackResults = {};\n const result = parsedStackResults[stackKey];\n if (result) acc[result[0]] = result[1];\n else {\n const parsedStack = stackParser(stackKey);\n for(let i = parsedStack.length - 1; i >= 0; i--){\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const chunkId = chunkIdMap[stackKey];\n if (filename && chunkId) {\n acc[filename] = chunkId;\n parsedStackResults[stackKey] = [\n filename,\n chunkId\n ];\n break;\n }\n }\n }\n return acc;\n }, {});\n return cachedFilenameChunkIds;\n}\nexport { getFilenameToChunkIdMap };\n","import { isArray } from \"../utils/index.mjs\";\nimport { getFilenameToChunkIdMap } from \"./chunk-ids.mjs\";\nconst MAX_CAUSE_RECURSION = 4;\nclass ErrorPropertiesBuilder {\n constructor(coercers, stackParser, modifiers = []){\n this.coercers = coercers;\n this.stackParser = stackParser;\n this.modifiers = modifiers;\n }\n buildFromUnknown(input, hint = {}) {\n const providedMechanism = hint && hint.mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic'\n };\n const coercingContext = this.buildCoercingContext(mechanism, hint, 0);\n const exceptionWithCause = coercingContext.apply(input);\n const parsingContext = this.buildParsingContext(hint);\n const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);\n const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);\n return {\n $exception_list: exceptionList,\n $exception_level: 'error'\n };\n }\n async modifyFrames(exceptionList) {\n for (const exc of exceptionList)if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);\n return exceptionList;\n }\n coerceFallback(ctx) {\n return {\n type: 'Error',\n value: 'Unknown error',\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n parseStacktrace(err, ctx) {\n let cause;\n if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);\n let stack;\n if ('' != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);\n return {\n ...err,\n cause,\n stack\n };\n }\n applyChunkIds(frames, chunkIdMap) {\n return frames.map((frame)=>{\n if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];\n return frame;\n });\n }\n applyCoercers(input, ctx) {\n for (const adapter of this.coercers)if (adapter.match(input)) return adapter.coerce(input, ctx);\n return this.coerceFallback(ctx);\n }\n async applyModifiers(frames) {\n let newFrames = frames;\n for (const modifier of this.modifiers)newFrames = await modifier(newFrames);\n return newFrames;\n }\n convertToExceptionList(exceptionWithStack, mechanism) {\n const currentException = {\n type: exceptionWithStack.type,\n value: exceptionWithStack.value,\n mechanism: {\n type: mechanism.type ?? 'generic',\n handled: mechanism.handled ?? true,\n synthetic: exceptionWithStack.synthetic ?? false\n }\n };\n if (exceptionWithStack.stack) currentException.stacktrace = {\n type: 'raw',\n frames: exceptionWithStack.stack\n };\n const exceptionList = [\n currentException\n ];\n if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {\n ...mechanism,\n handled: true\n }));\n return exceptionList;\n }\n buildParsingContext(hint) {\n const context = {\n chunkIdMap: getFilenameToChunkIdMap(this.stackParser),\n skipFirstLines: hint.skipFirstLines ?? 1\n };\n return context;\n }\n buildCoercingContext(mechanism, hint, depth = 0) {\n const coerce = (input, depth)=>{\n if (!(depth <= MAX_CAUSE_RECURSION)) return;\n {\n const ctx = this.buildCoercingContext(mechanism, hint, depth);\n return this.applyCoercers(input, ctx);\n }\n };\n const context = {\n ...hint,\n syntheticException: 0 == depth ? hint.syntheticException : void 0,\n mechanism,\n apply: (input)=>coerce(input, depth),\n next: (input)=>coerce(input, depth + 1)\n };\n return context;\n }\n}\nexport { ErrorPropertiesBuilder };\n","import { isUndefined } from \"../../utils/index.mjs\";\nconst UNKNOWN_FUNCTION = '?';\nconst MASKED_URL_PREFIX = 'webkit-masked-url://';\nconst ANONYMOUS_FILENAME = '<anonymous>';\nfunction createFrame(platform, filename, func, lineno, colno) {\n const frame = {\n platform,\n filename,\n function: '<anonymous>' === func ? UNKNOWN_FUNCTION : func,\n in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME\n };\n if (!isUndefined(lineno)) frame.lineno = lineno;\n if (!isUndefined(colno)) frame.colno = colno;\n return frame;\n}\nexport { UNKNOWN_FUNCTION, createFrame };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst extractSafariExtensionDetails = (func, filename)=>{\n const isSafariExtension = -1 !== func.indexOf('safari-extension');\n const isSafariWebExtension = -1 !== func.indexOf('safari-web-extension');\n return isSafariExtension || isSafariWebExtension ? [\n -1 !== func.indexOf('@') ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`\n ] : [\n func,\n filename\n ];\n};\nexport { extractSafariExtensionDetails };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\nconst chromeRegex = /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\nconst chromeStackLineParser = (line, platform)=>{\n const noFnParts = chromeRegexNoFnName.exec(line);\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);\n }\n const parts = chromeRegex.exec(line);\n if (parts) {\n const isEval = parts[2] && 0 === parts[2].indexOf('eval');\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n if (subMatch) {\n parts[2] = subMatch[1];\n parts[3] = subMatch[2];\n parts[4] = subMatch[3];\n }\n }\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);\n }\n};\nexport { chromeStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst geckoREgex = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst geckoStackLineParser = (line, platform)=>{\n const parts = geckoREgex.exec(line);\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n if (subMatch) {\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = '';\n }\n }\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);\n }\n};\nexport { geckoStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst FILENAME_MATCH = /^\\s*[-]{4,}$/;\nconst FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\nconst PROMISE_COMBINATOR = /^Promise\\.(?:all|any)$/;\nconst PROMISE_INDEX = /^index \\d+$/;\nconst PROMISE_FRAME_FILENAME = 'node:internal/promise';\nconst nodeStackLineParser = (line, platform)=>{\n const lineMatch = line.match(FULL_MATCH);\n if (lineMatch) {\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if ('.' === functionName[methodStart - 1]) methodStart--;\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = void 0;\n }\n if (method) {\n typeName = object;\n methodName = method;\n }\n if ('<anonymous>' === method) {\n methodName = void 0;\n functionName = void 0;\n }\n if (void 0 === functionName) {\n methodName = methodName || UNKNOWN_FUNCTION;\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = 'native' === lineMatch[5];\n if (filename?.match(/\\/[A-Z]:/)) filename = filename.slice(1);\n if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];\n if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || '')) filename = PROMISE_FRAME_FILENAME;\n return {\n filename: filename ? decodeURI(filename) : void 0,\n module: void 0,\n function: functionName,\n lineno: _parseIntOrUndefined(lineMatch[3]),\n colno: _parseIntOrUndefined(lineMatch[4]),\n in_app: filenameIsInApp(filename || '', isNative),\n platform: platform\n };\n }\n if (line.match(FILENAME_MATCH)) return {\n filename: line,\n platform: platform\n };\n};\nfunction filenameIsInApp(filename, isNative = false) {\n const isInternal = isNative || filename && !filename.startsWith('/') && !filename.match(/^[A-Z]:/) && !filename.startsWith('.') && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//);\n return !isInternal && void 0 !== filename && !filename.includes('node_modules/');\n}\nfunction _parseIntOrUndefined(input) {\n return parseInt(input || '', 10) || void 0;\n}\nexport { nodeStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nimport { chromeStackLineParser } from \"./chrome.mjs\";\nimport { geckoStackLineParser } from \"./gecko.mjs\";\nimport { winjsStackLineParser } from \"./winjs.mjs\";\nimport { opera10StackLineParser, opera11StackLineParser } from \"./opera.mjs\";\nimport { nodeStackLineParser } from \"./node.mjs\";\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STACKTRACE_FRAME_LIMIT = 50;\nfunction reverseAndStripFrames(stack) {\n if (!stack.length) return [];\n const localStack = Array.from(stack);\n localStack.reverse();\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame)=>({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION\n }));\n}\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\nfunction createDefaultStackParser() {\n return createStackParser(\"web:javascript\", chromeStackLineParser, geckoStackLineParser);\n}\nfunction createStackParser(platform, ...parsers) {\n return (stack, skipFirstLines = 0)=>{\n const frames = [];\n const lines = stack.split('\\n');\n for(let i = skipFirstLines; i < lines.length; i++){\n const line = lines[i];\n if (line.length > 1024) continue;\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n if (!cleanedLine.match(/\\S*Error: /)) {\n for (const parser of parsers){\n const frame = parser(cleanedLine, platform);\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n if (frames.length >= STACKTRACE_FRAME_LIMIT) break;\n }\n }\n return reverseAndStripFrames(frames);\n };\n}\nexport { chromeStackLineParser, createDefaultStackParser, createStackParser, geckoStackLineParser, nodeStackLineParser, opera10StackLineParser, opera11StackLineParser, reverseAndStripFrames, winjsStackLineParser };\n","import { isError } from \"../../utils/type-utils.mjs\";\nclass ErrorCoercer {\n match(err) {\n return isError(err);\n }\n coerce(err, ctx) {\n const stack = this.getStack(err);\n const synthetic = void 0 === stack;\n return {\n type: this.getType(err),\n value: this.getMessage(err, ctx),\n stack: stack ?? ctx.syntheticException?.stack,\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic\n };\n }\n getType(err) {\n return err.name || err.constructor.name;\n }\n getMessage(err, _ctx) {\n const message = err.message;\n if (message.error && 'string' == typeof message.error.message) return String(message.error.message);\n return String(message);\n }\n getStack(err) {\n return err.stacktrace || err.stack || void 0;\n }\n}\nexport { ErrorCoercer };\n","const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\nclass StringCoercer {\n match(input) {\n return 'string' == typeof input;\n }\n coerce(input, ctx) {\n const [type, value] = this.getInfos(input);\n return {\n type: type ?? 'Error',\n value: value ?? input,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n getInfos(candidate) {\n let type = 'Error';\n let value = candidate;\n const groups = candidate.match(ERROR_TYPES_PATTERN);\n if (groups) {\n type = groups[1];\n value = groups[2];\n }\n return [\n type,\n value\n ];\n }\n}\nexport { StringCoercer };\n","const severityLevels = [\n 'fatal',\n 'error',\n 'warning',\n 'log',\n 'info',\n 'debug'\n];\nexport { severityLevels };\n","function truncate(str, max = 0) {\n if ('string' != typeof str || 0 === max) return str;\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction extractExceptionKeysForMessage(err, maxLength = 40) {\n const keys = Object.keys(err);\n keys.sort();\n if (!keys.length) return '[object has no keys]';\n for(let i = keys.length; i > 0; i--){\n const serialized = keys.slice(0, i).join(', ');\n if (!(serialized.length > maxLength)) {\n if (i === keys.length) return serialized;\n return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;\n }\n }\n return '';\n}\nexport { extractExceptionKeysForMessage, truncate };\n","import { isEmptyString, isError, isEvent, isString } from \"../../utils/index.mjs\";\nimport { severityLevels } from \"../types.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass ObjectCoercer {\n match(candidate) {\n return 'object' == typeof candidate && null !== candidate;\n }\n coerce(candidate, ctx) {\n const errorProperty = this.getErrorPropertyFromObject(candidate);\n if (errorProperty) return ctx.apply(errorProperty);\n return {\n type: this.getType(candidate),\n value: this.getValue(candidate),\n stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,\n level: this.isSeverityLevel(candidate.level) ? candidate.level : 'error',\n synthetic: true\n };\n }\n getType(err) {\n if (isEvent(err)) return err.constructor.name;\n const name = 'name' in err ? err.name : void 0;\n return isString(name) && !isEmptyString(name) ? name : 'Error';\n }\n getValue(err) {\n if ('name' in err && 'string' == typeof err.name) {\n let message = `'${err.name}' captured as exception`;\n if ('message' in err && 'string' == typeof err.message) message += ` with message: '${err.message}'`;\n return message;\n }\n if ('message' in err && 'string' == typeof err.message) return err.message;\n const className = this.getObjectClassName(err);\n const keys = extractExceptionKeysForMessage(err);\n return `${className && 'Object' !== className ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;\n }\n isSeverityLevel(x) {\n return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;\n }\n getStack(candidate) {\n try {\n if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0) return candidate.stacktrace;\n return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : void 0;\n } catch {\n return;\n }\n }\n getErrorPropertyFromObject(obj) {\n for(const prop in obj)if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (isError(value)) return value;\n }\n }\n getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : void 0;\n } catch (e) {\n return;\n }\n }\n}\nexport { ObjectCoercer };\n","import { isEvent } from \"../../utils/index.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass EventCoercer {\n match(err) {\n return isEvent(err);\n }\n coerce(evt, ctx) {\n const constructorName = evt.constructor.name;\n return {\n type: constructorName,\n value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { EventCoercer };\n","import { isPrimitive } from \"../../utils/index.mjs\";\nclass PrimitiveCoercer {\n match(candidate) {\n return isPrimitive(candidate);\n }\n coerce(value, ctx) {\n return {\n type: 'Error',\n value: `Primitive value captured as exception: ${String(value)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { PrimitiveCoercer };\n","class ReduceableCache {\n constructor(_maxSize){\n this._maxSize = _maxSize;\n this._cache = new Map();\n }\n get(key) {\n const value = this._cache.get(key);\n if (void 0 === value) return;\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n set(key, value) {\n this._cache.set(key, value);\n }\n reduce() {\n while(this._cache.size >= this._maxSize){\n const value = this._cache.keys().next().value;\n if (value) this._cache.delete(value);\n }\n }\n}\nexport { ReduceableCache };\n","import { isNumber, isObject, isString, safeJsonStringify } from \"../utils/index.mjs\";\nconst EXCEPTION_STEP_INTERNAL_FIELDS = {\n MESSAGE: '$message',\n TIMESTAMP: '$timestamp'\n};\nconst RESERVED_EXCEPTION_STEP_KEYS = new Set([\n EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,\n EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP\n]);\nconst DEFAULT_EXCEPTION_STEPS_CONFIG = {\n enabled: true,\n max_bytes: 32768\n};\nfunction resolveExceptionStepsConfig(config) {\n if (!config) return {\n ...DEFAULT_EXCEPTION_STEPS_CONFIG\n };\n return {\n enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,\n max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)\n };\n}\nfunction stripReservedExceptionStepFields(properties) {\n if (!properties) return {\n sanitizedProperties: {},\n droppedKeys: []\n };\n const droppedKeys = [];\n const sanitizedProperties = Object.keys(properties).reduce((acc, key)=>{\n if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {\n droppedKeys.push(key);\n return acc;\n }\n acc[key] = properties[key];\n return acc;\n }, {});\n return {\n sanitizedProperties,\n droppedKeys\n };\n}\nclass ExceptionStepsBuffer {\n constructor(config){\n this._entries = [];\n this._totalBytes = 0;\n this._config = resolveExceptionStepsConfig(config);\n }\n setConfig(config) {\n this._config = resolveExceptionStepsConfig(config);\n this._trimToMaxBytes();\n }\n add(step) {\n const serialized = normalizeAndSerializeStep(step);\n if (!serialized) return;\n const bytes = getUtf8ByteLength(serialized.json);\n if (bytes > this._config.max_bytes) return;\n this._entries.push({\n step: serialized.step,\n bytes\n });\n this._totalBytes += bytes;\n this._trimToMaxBytes();\n }\n getAttachable() {\n return this._entries.map((e)=>e.step);\n }\n clear() {\n this._entries = [];\n this._totalBytes = 0;\n }\n size() {\n return this._entries.length;\n }\n _trimToMaxBytes() {\n while(this._totalBytes > this._config.max_bytes && this._entries.length > 0){\n const evicted = this._entries.shift();\n if (evicted) this._totalBytes -= evicted.bytes;\n }\n }\n}\nfunction normalizePositiveInteger(input, fallback) {\n if (!isNumber(input) || input === 1 / 0 || input === -1 / 0) return fallback;\n const normalized = Math.floor(input);\n if (normalized < 0) return fallback;\n return normalized;\n}\nfunction normalizeAndSerializeStep(step) {\n let json;\n try {\n json = safeJsonStringify(step);\n } catch {\n return;\n }\n try {\n const parsed = JSON.parse(json);\n if (!isObject(parsed)) return;\n const parsedStep = parsed;\n const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];\n const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];\n if (!isString(message) || 0 === message.trim().length) return;\n if (!isString(timestamp) && !isNumber(timestamp)) return;\n return {\n step: parsedStep,\n json\n };\n } catch {\n return;\n }\n}\nfunction getUtf8ByteLength(value) {\n if ('undefined' != typeof TextEncoder) return new TextEncoder().encode(value).length;\n const encoded = encodeURIComponent(value);\n let byteLength = 0;\n for(let i = 0; i < encoded.length; i++)if ('%' === encoded[i]) {\n byteLength += 1;\n i += 2;\n } else byteLength += 1;\n return byteLength;\n}\nexport { DEFAULT_EXCEPTION_STEPS_CONFIG, EXCEPTION_STEP_INTERNAL_FIELDS, ExceptionStepsBuffer, getUtf8ByteLength, resolveExceptionStepsConfig, stripReservedExceptionStepFields };\n","function getInjectedReleaseId() {\n const injected = globalThis._posthogReleaseId;\n return 'string' == typeof injected && injected.length > 0 ? injected : void 0;\n}\nexport { getInjectedReleaseId };\n","import { SimpleEventEmitter } from \"./eventemitter.mjs\";\nimport { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipSupported } from \"./gzip.mjs\";\nimport { PostHogPersistedProperty } from \"./types.mjs\";\nimport { PromiseQueue, STRING_FORMAT, allSettled, createLogger, currentISOTime, getEventUuid, raceWithTimeout, removeTrailingSlash, retriable, safeJsonStringify, safeSetTimeout } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { ErrorCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, StringCoercer, createDefaultStackParser } from \"./error-tracking/index.mjs\";\nclass PostHogFetchHttpError extends Error {\n constructor(response, reqByteLength, responseBodyDeadline, abortController){\n super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = 'PostHogFetchHttpError', this._bodyReadTimedOut = false;\n }\n get status() {\n return this.response.status;\n }\n get bodyReadTimedOut() {\n return this._bodyReadTimedOut;\n }\n get text() {\n if (!this.responseBodyTextPromise) if (Date.now() >= this.responseBodyDeadline) {\n this._bodyReadTimedOut = true;\n const timeoutError = new Error('Response body read timed out');\n timeoutError.name = 'AbortError';\n this.cancelResponseBody(timeoutError);\n this.responseBodyTextPromise = Promise.reject(timeoutError);\n } else {\n const responseBodyTimeout = new Promise((_resolve, reject)=>{\n this.responseBodyTimer = safeSetTimeout(()=>{\n this._bodyReadTimedOut = true;\n const timeoutError = new Error('Response body read timed out');\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n this.cancelResponseBody(timeoutError);\n }, this.responseBodyDeadline - Date.now());\n });\n let responseBodyText;\n try {\n responseBodyText = Promise.resolve(this.response.text());\n } catch (error) {\n responseBodyText = Promise.reject(error);\n }\n this.responseBodyTextPromise = Promise.race([\n responseBodyText,\n responseBodyTimeout\n ]).finally(()=>clearTimeout(this.responseBodyTimer));\n }\n return this.responseBodyTextPromise;\n }\n get json() {\n return this.text.then((text)=>JSON.parse(text));\n }\n cancelResponseBody(reason) {\n clearTimeout(this.responseBodyTimer);\n if (!this.abortController.signal.aborted) this.abortController.abort(reason);\n (async ()=>{\n try {\n await this.response.body?.cancel();\n } catch {}\n })();\n }\n}\nclass PostHogFetchNetworkError extends Error {\n constructor(error){\n super('Network error while fetching PostHog', error instanceof Error ? {\n cause: error\n } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';\n }\n}\nconst maybeAdd = (key, value)=>void 0 !== value ? {\n [key]: value\n } : {};\nconst applyCallerFeatureFlagOverrides = (target, callerProperties)=>{\n for (const key of Object.keys(callerProperties))if (key.startsWith('$feature/') || '$active_feature_flags' === key) target[key] = callerProperties[key];\n};\nasync function logFlushError(err) {\n if (err instanceof PostHogFetchHttpError) {\n let text = '';\n try {\n text = await err.text;\n } catch {\n if (err.bodyReadTimedOut) text = '<response body read timed out>';\n }\n console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);\n } else console.error('Error while flushing PostHog', err);\n return Promise.resolve();\n}\nfunction isPostHogFetchError(err) {\n return 'object' == typeof err && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));\n}\nfunction isPostHogFetchNetworkError(err) {\n return err instanceof PostHogFetchNetworkError;\n}\nfunction isRetryableFlagsFetchError(err) {\n if (err instanceof PostHogFetchHttpError) return 502 === err.status || 504 === err.status;\n if (!(err instanceof PostHogFetchNetworkError)) return false;\n const cause = err.error;\n const code = cause?.code ?? cause?.cause?.code;\n return 'ECONNREFUSED' !== code;\n}\nfunction isPostHogFetchContentTooLargeError(err) {\n return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;\n}\nfunction isPostHogFetchRetryableError(err) {\n if (err instanceof PostHogFetchHttpError) return 408 === err.status || 429 === err.status || err.status >= 500;\n return isPostHogFetchNetworkError(err);\n}\nfunction isPostHogEventProperties(value) {\n return null !== value && 'object' == typeof value && !Array.isArray(value);\n}\nvar posthog_core_stateless_QuotaLimitedFeature = /*#__PURE__*/ function(QuotaLimitedFeature) {\n QuotaLimitedFeature[\"FeatureFlags\"] = \"feature_flags\";\n QuotaLimitedFeature[\"Recordings\"] = \"recordings\";\n return QuotaLimitedFeature;\n}({});\nconst DEFAULT_QUEUE_ROUTE = 'default';\nclass PostHogCoreStateless {\n getErrorPropertiesBuilder() {\n if (!this._errorPropertiesBuilder) this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();\n return this._errorPropertiesBuilder;\n }\n createErrorPropertiesBuilder() {\n return new ErrorPropertiesBuilder([\n new ErrorCoercer(),\n new ObjectCoercer(),\n new StringCoercer(),\n new PrimitiveCoercer()\n ], createDefaultStackParser());\n }\n constructor(apiKey, options = {}){\n this.flushPromise = null;\n this.pendingFlushPromise = null;\n this.flushPromises = new Set();\n this._dequeuedMessagesCount = 0;\n this.shutdownPromise = null;\n this.promiseQueue = new PromiseQueue();\n this._events = new SimpleEventEmitter();\n this._isInitialized = false;\n const normalizedApiKey = 'string' == typeof apiKey ? apiKey.trim() : '';\n const normalizedHost = 'string' == typeof options.host ? options.host.trim() : '';\n const missingApiKey = !normalizedApiKey;\n this._logger = createLogger('[PostHog]', this.logMsgIfDebug.bind(this));\n if (missingApiKey) this._logger.error(\"You must pass your PostHog project's api key. The client will be disabled.\");\n this.apiKey = normalizedApiKey;\n this.host = removeTrailingSlash(normalizedHost || 'https://us.i.posthog.com');\n this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;\n this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);\n this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);\n this.flushInterval = options.flushInterval ?? 10000;\n this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;\n this.defaultOptIn = options.defaultOptIn ?? true;\n this.disableSurveys = options.disableSurveys ?? false;\n this._retryOptions = {\n retryCount: options.fetchRetryCount ?? 3,\n retryDelay: options.fetchRetryDelay ?? 3000,\n retryCheck: isPostHogFetchRetryableError\n };\n this.requestTimeout = options.requestTimeout ?? 10000;\n this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;\n this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;\n this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;\n this.disableGeoip = options.disableGeoip ?? true;\n this.disabled = (options.disabled ?? false) || missingApiKey;\n this.historicalMigration = options?.historicalMigration ?? false;\n this._initPromise = Promise.resolve();\n this._isInitialized = true;\n this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;\n if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');\n this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);\n }\n logMsgIfDebug(fn) {\n if (this.isDebug) fn();\n }\n wrap(fn) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (this._isInitialized) return fn();\n this._initPromise.then(()=>fn());\n }\n getCommonEventProperties() {\n return {\n $lib: this.getLibraryId(),\n $lib_version: this.getLibraryVersion()\n };\n }\n get optedOut() {\n return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;\n }\n async optIn() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);\n });\n }\n async optOut() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);\n });\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n debug(enabled = true) {\n this.removeDebugCallback?.();\n if (enabled) {\n const removeDebugCallback = this.on('*', (event, payload)=>this._logger.info(event, payload));\n this.removeDebugCallback = ()=>{\n removeDebugCallback();\n this.removeDebugCallback = void 0;\n };\n }\n }\n get isDebug() {\n return !!this.removeDebugCallback;\n }\n get isDisabled() {\n return this.disabled;\n }\n buildPayload(payload) {\n const userProperties = payload.properties || {};\n let properties = {\n ...userProperties,\n ...this.getCommonEventProperties()\n };\n applyCallerFeatureFlagOverrides(properties, userProperties);\n if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties);\n return {\n distinct_id: payload.distinct_id,\n event: payload.event,\n properties\n };\n }\n isMinimalFlagCalledEventsEnabled() {\n return false;\n }\n addPendingPromise(promise) {\n return this.promiseQueue.add(promise);\n }\n identifyStateless(distinctId, properties, options) {\n this.wrap(()=>{\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n this.enqueue('identify', payload, options);\n });\n }\n async identifyStatelessImmediate(distinctId, properties, options) {\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n await this.sendImmediate('identify', payload, options);\n }\n captureStateless(distinctId, event, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n this.enqueue('capture', payload, options);\n });\n }\n async captureStatelessImmediate(distinctId, event, properties, options) {\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n await this.sendImmediate('capture', payload, options);\n }\n aliasStateless(alias, distinctId, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n this.enqueue('alias', payload, options);\n });\n }\n async aliasStatelessImmediate(alias, distinctId, properties, options) {\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n await this.sendImmediate('alias', payload, options);\n }\n groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n this.enqueue('capture', payload, options);\n });\n }\n async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n await this.sendImmediate('capture', payload, options);\n }\n async getRemoteConfig() {\n await this._initPromise;\n let host = this.host;\n if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';\n else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';\n const url = `${host}/array/${this.apiKey}/config`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n return this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>response.json()\n }, {\n retryCount: 0\n }, this.remoteConfigRequestTimeoutMs).catch((error)=>{\n this._logger.error('Remote config could not be loaded', error);\n this._events.emit('error', error);\n });\n }\n async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {\n await this._initPromise;\n const configParam = fetchConfig ? '&config=true' : '';\n const url = `${this.host}/flags/?v=2${configParam}`;\n const requestData = {\n token: this.apiKey,\n distinct_id: distinctId,\n groups,\n person_properties: personProperties,\n group_properties: groupProperties,\n ...extraPayload\n };\n if (personProperties.$device_id) requestData.$device_id = personProperties.$device_id;\n if (this.evaluationContexts && this.evaluationContexts.length > 0) requestData.evaluation_contexts = this.evaluationContexts;\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(requestData)\n };\n this._logger.info('Flags URL', url);\n return this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>response.json()\n }, {\n retryCount: this.featureFlagsRequestMaxRetries,\n retryCheck: isRetryableFlagsFetchError\n }, this.featureFlagsRequestTimeoutMs).then((response)=>({\n success: true,\n response: normalizeFlagsResponse(response)\n })).catch((error)=>{\n this._events.emit('error', error);\n return {\n success: false,\n error: this.categorizeRequestError(error)\n };\n });\n }\n categorizeRequestError(error) {\n if (error instanceof PostHogFetchHttpError) return {\n type: 'api_error',\n statusCode: error.status\n };\n if (error instanceof PostHogFetchNetworkError) {\n const cause = error.error;\n if (cause instanceof Error && ('AbortError' === cause.name || 'TimeoutError' === cause.name)) return {\n type: 'timeout'\n };\n return {\n type: 'connection_error'\n };\n }\n return {\n type: 'unknown_error'\n };\n }\n async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);\n if (void 0 === flagDetailResponse) return {\n response: void 0,\n requestId: void 0\n };\n let response = getFeatureFlagValue(flagDetailResponse.response);\n if (void 0 === response) response = false;\n return {\n response,\n requestId: flagDetailResponse.requestId\n };\n }\n async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) return;\n const featureFlags = flagsResponse.flags;\n const flagDetail = featureFlags[key];\n return {\n response: flagDetail,\n requestId: flagsResponse.requestId,\n evaluatedAt: flagsResponse.evaluatedAt\n };\n }\n async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (!payloads) return;\n const response = payloads[key];\n if (void 0 === response) return null;\n return response;\n }\n async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;\n return payloads;\n }\n async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n }\n async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n if (!featureFlagDetails) return {\n flags: void 0,\n payloads: void 0,\n requestId: void 0\n };\n return {\n flags: featureFlagDetails.featureFlags,\n payloads: featureFlagDetails.featureFlagPayloads,\n requestId: featureFlagDetails.requestId\n };\n }\n async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const extraPayload = {\n geoip_disable: disableGeoip ?? this.disableGeoip\n };\n if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;\n const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);\n if (!result.success) return;\n const flagsResponse = result.response;\n 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');\n if (flagsResponse.quotaLimited?.includes(\"feature_flags\")) {\n 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');\n return {\n flags: {},\n featureFlags: {},\n featureFlagPayloads: {},\n requestId: flagsResponse?.requestId,\n quotaLimited: flagsResponse.quotaLimited\n };\n }\n return flagsResponse;\n }\n async getSurveysStateless() {\n await this._initPromise;\n if (this.disabled) return [];\n if (true === this.disableSurveys) {\n this._logger.info('Loading surveys is disabled.');\n return [];\n }\n const url = `${this.host}/api/surveys/?token=${this.apiKey}`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n const response = await this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>{\n if (200 !== response.status || !response.json) {\n const msg = `Surveys API could not be loaded: ${response.status}`;\n const error = new Error(msg);\n this._logger.error(error);\n this._events.emit('error', new Error(msg));\n return Promise.resolve(void 0);\n }\n return response.json();\n }\n }).catch((error)=>{\n this._logger.error('Surveys API could not be loaded', error);\n this._events.emit('error', error);\n });\n const newSurveys = response?.surveys;\n if (newSurveys) this._logger.info('Surveys fetched from API: ', JSON.stringify(newSurveys));\n return newSurveys ?? [];\n }\n get props() {\n if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);\n return this._props || {};\n }\n set props(val) {\n this._props = val;\n }\n async register(properties) {\n this.wrap(()=>{\n this.props = {\n ...this.props,\n ...properties\n };\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n async unregister(property) {\n this.wrap(()=>{\n delete this.props[property];\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n processBeforeEnqueue(message) {\n return message;\n }\n async flushStorage() {}\n getQueueRouteKey(_message) {\n return DEFAULT_QUEUE_ROUTE;\n }\n persistedQueueKeyForRoute(_route) {\n return PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return [\n DEFAULT_QUEUE_ROUTE\n ];\n }\n getRouteQueue(route) {\n return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];\n }\n enqueue(type, _message, options, explicitRoute) {\n this.wrap(()=>{\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));\n const queue = this.getPersistedProperty(queueKey) || [];\n if (queue.length >= this.maxQueueSize) {\n queue.shift();\n this._logger.warn('Queue is full, the oldest event is dropped.');\n }\n queue.push({\n message\n });\n this.setPersistedProperty(queueKey, queue);\n this._events.emit(type, message);\n if (queue.length >= this.flushAt) this.flushBackground();\n if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(()=>this.flushBackground(), this.flushInterval);\n });\n }\n async sendImmediate(type, _message, options, explicitRoute) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this._isInitialized) await this._initPromise;\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n try {\n await this.sendBatch([\n message\n ], void 0, explicitRoute ?? this.getQueueRouteKey(message));\n } catch (err) {\n this._events.emit('error', err);\n }\n }\n normalizeMessage(message) {\n const { type: _type, library, library_version, ...sanitizedMessage } = message;\n let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;\n if (void 0 !== library && properties?.$lib === void 0) properties = {\n ...properties || {},\n $lib: library\n };\n if (void 0 !== library_version && properties?.$lib_version === void 0) properties = {\n ...properties || {},\n $lib_version: library_version\n };\n if (properties) sanitizedMessage.properties = properties;\n sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);\n return sanitizedMessage;\n }\n normalizeTimestampForWire(timestamp) {\n const parsedTimestamp = timestamp instanceof Date ? timestamp : 'string' == typeof timestamp ? new Date(timestamp) : null;\n if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime())) return timestamp;\n const normalized = parsedTimestamp.toISOString();\n const fractionalSeconds = 'string' == typeof timestamp ? timestamp.match(/\\.(\\d+)(?:Z|[+-]\\d{2}:?\\d{2})?$/i)?.[1] : void 0;\n return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\\.\\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;\n }\n prepareMessage(_message, options) {\n const message = {\n ..._message,\n timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),\n uuid: getEventUuid(options?.uuid, uuidv7)\n };\n const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;\n if (addGeoipDisableProperty) {\n if (!isPostHogEventProperties(message.properties)) message.properties = {};\n message.properties['$geoip_disable'] = true;\n }\n if (message.distinctId) {\n message.distinct_id = message.distinctId;\n delete message.distinctId;\n }\n return message;\n }\n clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n flushBackground() {\n if (this.pendingFlushPromise) return;\n this.flush().catch(async (err)=>{\n await logFlushError(err);\n });\n }\n async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {\n const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);\n let iteration = 0;\n while(true){\n const promises = this.promiseQueue.getPromises([\n ...ignoredPendingPromises,\n ...this.flushPromises\n ], maxPromiseId);\n if (0 === promises.length) return;\n if (iteration > 0) this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);\n await Promise.all(promises.map((promise)=>promise.catch(()=>{})));\n iteration++;\n }\n }\n flushWithPendingPromises() {\n return this.flushInternal(true);\n }\n flush() {\n return this.flushInternal(false);\n }\n flushInternal(waitForPendingPromises) {\n if (this.disabled) return Promise.resolve();\n if (!waitForPendingPromises && this.pendingFlushPromise) return this.pendingFlushPromise;\n const previousFlushPromise = this.flushPromise;\n const maxPromiseId = this.promiseQueue.maxId;\n const nextFlushPromise = Promise.resolve().then(()=>{\n if (waitForPendingPromises) return this.waitForPendingPromises(maxPromiseId, [\n previousFlushPromise,\n nextFlushPromise\n ]);\n }).then(()=>allSettled([\n previousFlushPromise\n ])).then(()=>{\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n return this._flush();\n });\n this.pendingFlushPromise = nextFlushPromise;\n this.flushPromise = nextFlushPromise;\n this.flushPromises.add(nextFlushPromise);\n this.addPendingPromise(nextFlushPromise);\n allSettled([\n nextFlushPromise\n ]).then(()=>{\n this.flushPromises.delete(nextFlushPromise);\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n if (this.flushPromise === nextFlushPromise) this.flushPromise = null;\n });\n return nextFlushPromise;\n }\n getCustomHeaders() {\n const customUserAgent = this.getCustomUserAgent();\n const headers = {};\n if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;\n return headers;\n }\n compressPayload(payload) {\n return gzipCompress(payload, this.isDebug);\n }\n getBatchEndpointPath(_route) {\n return '/batch/';\n }\n async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {\n const data = {\n api_key: this.apiKey,\n batch: batchMessages.map((message)=>{\n if (!message) return message;\n const timestamp = this.normalizeTimestampForWire(message.timestamp);\n return timestamp === message.timestamp ? message : {\n ...message,\n timestamp\n };\n }),\n sent_at: currentISOTime()\n };\n if (this.historicalMigration) data.historical_migration = true;\n const payload = safeJsonStringify(data);\n const url = `${this.host}${this.getBatchEndpointPath(route)}`;\n const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || payload\n };\n await this.fetchWithRetry(url, fetchOptions, {\n type: 'successful-write'\n }, retryOptions);\n }\n async _flush() {\n this.clearFlushTimer();\n await this._initPromise;\n const routes = this.getActiveQueueRoutes();\n if (!routes.some((route)=>this.getRouteQueue(route).length > 0)) return;\n const sentMessages = [];\n let firstError;\n for (const route of routes)try {\n await this._flushRoute(route, sentMessages);\n } catch (err) {\n if (void 0 === firstError) firstError = err;\n }\n if (void 0 !== firstError) throw firstError;\n this._events.emit('flush', sentMessages);\n }\n async _flushRoute(route, sentMessages) {\n const queueKey = this.persistedQueueKeyForRoute(route);\n let queue = this.getPersistedProperty(queueKey) || [];\n if (!queue.length) return;\n const originalQueueLength = queue.length;\n let sentFromRoute = 0;\n while(queue.length > 0 && sentFromRoute < originalQueueLength){\n const batchItems = queue.slice(0, this.maxBatchSize);\n const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));\n const persistQueueChange = async ()=>{\n const refreshedQueue = this.getPersistedProperty(queueKey) || [];\n const remainingBatchItems = [\n ...batchItems\n ];\n const newQueue = refreshedQueue.filter((item)=>{\n const itemUuid = item.message?.uuid;\n const batchItemIndex = remainingBatchItems.findIndex((batchItem)=>batchItem === item || 'string' == typeof itemUuid && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);\n if (-1 === batchItemIndex) return true;\n remainingBatchItems.splice(batchItemIndex, 1);\n return false;\n });\n this.setPersistedProperty(queueKey, newQueue);\n queue = newQueue;\n this._dequeuedMessagesCount += batchItems.length;\n await this.flushStorage();\n };\n const retryOptions = {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n };\n try {\n await this.sendBatch(batchMessages, retryOptions, route);\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {\n this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));\n this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);\n continue;\n }\n if (!(err instanceof PostHogFetchNetworkError)) await persistQueueChange();\n this._events.emit('error', err);\n throw err;\n }\n await persistQueueChange();\n sentMessages.push(...batchMessages);\n sentFromRoute += batchMessages.length;\n }\n }\n async _sendOtlpBatch({ path, payload }) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n type: 'successful-write'\n }, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (isPostHogFetchRetryableError(err)) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async _sendLogsBatch(payload) {\n return this._sendOtlpBatch({\n path: 'logs',\n payload\n });\n }\n async _sendMetricsBatch(payload) {\n return this._sendOtlpBatch({\n path: 'metrics',\n payload\n });\n }\n async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {\n const body = options.body ? options.body : '';\n let reqByteLength = -1;\n try {\n reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);\n } catch {\n if (body instanceof Blob) reqByteLength = body.size;\n else if (body instanceof Uint8Array) reqByteLength = body.byteLength;\n else {\n const encoded = new TextEncoder().encode(body);\n reqByteLength = encoded.length;\n }\n }\n const retriableOptions = {\n ...this._retryOptions,\n ...retryOptions\n };\n let attempt = 0;\n return await retriable(async ()=>{\n attempt++;\n const ctrl = new AbortController();\n const timeoutMs = requestTimeout ?? this.requestTimeout;\n const requestDeadline = Date.now() + timeoutMs;\n let timer;\n const deadline = new Promise((_resolve, reject)=>{\n timer = safeSetTimeout(()=>{\n const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n ctrl.abort(timeoutError);\n }, timeoutMs);\n });\n let res;\n let responseAccepted = false;\n let cancellation;\n const cancelBody = ()=>cancellation ??= (async ()=>{\n try {\n await res?.body?.cancel();\n } catch {}\n })();\n try {\n let fetchPromise;\n try {\n fetchPromise = this.fetch(url, {\n signal: ctrl.signal,\n ...options\n });\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n }\n fetchPromise.then((lateResponse)=>{\n if (ctrl.signal.aborted && !responseAccepted) Promise.resolve(lateResponse.body?.cancel()).catch(()=>{});\n }).catch(()=>{});\n try {\n res = await Promise.race([\n fetchPromise,\n deadline\n ]);\n responseAccepted = true;\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n }\n const isNoCors = 'no-cors' === options.mode;\n if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);\n if ('successful-write' === responseHandling.type) {\n try {\n await Promise.race([\n cancelBody(),\n deadline\n ]);\n } catch {}\n return;\n }\n try {\n return await Promise.race([\n responseHandling.consume(res),\n deadline\n ]);\n } catch (e) {\n if (ctrl.signal.aborted) throw new PostHogFetchNetworkError(e);\n throw e;\n }\n } finally{\n clearTimeout(timer);\n if (ctrl.signal.aborted && res) cancelBody();\n }\n }, {\n ...retriableOptions,\n retryCheck: (error)=>{\n const shouldRetry = retriableOptions.retryCheck(error);\n if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError) error.cancelResponseBody();\n return shouldRetry;\n }\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n await this._initPromise;\n let hasTimedOut = false;\n this.clearFlushTimer();\n if (this.disabled) return;\n const doShutdown = async ()=>{\n try {\n await this.promiseQueue.join();\n while(true){\n const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);\n if (!hasQueuedEvents) break;\n const dequeuedBeforeFlush = this._dequeuedMessagesCount;\n await this.flush();\n if (hasTimedOut) break;\n if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {\n this._logger.warn('Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.');\n break;\n }\n }\n } catch (e) {\n if (!isPostHogFetchError(e)) throw e;\n await logFlushError(e);\n }\n };\n return raceWithTimeout(doShutdown(), shutdownTimeoutMs, ()=>{\n this._logger.critical('Timeout while shutting down PostHog. Some events may not have been sent.', {\n shutdownTimeoutMs\n });\n hasTimedOut = true;\n });\n }\n async shutdown(shutdownTimeoutMs = 30000) {\n 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');\n else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{\n this.shutdownPromise = null;\n });\n return this.shutdownPromise;\n }\n}\nexport { PostHogCoreStateless, posthog_core_stateless_QuotaLimitedFeature as QuotaLimitedFeature, applyCallerFeatureFlagOverrides, isPostHogFetchContentTooLargeError, isPostHogFetchNetworkError, logFlushError, maybeAdd };\n","import { ErrorTracking } from \"@posthog/core\";\nimport { constants } from \"node:fs\";\nimport { open as promises_open } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nconst LRU_FILE_CONTENTS_CACHE = new ErrorTracking.ReduceableCache(25);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new ErrorTracking.ReduceableCache(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst MAX_CONTEXTLINES_COLNO = 1000;\nconst MAX_CONTEXTLINES_LINENO = 10000;\nconst MAX_CONTEXTLINES_FILE_SIZE = 10485760;\nasync function addSourceContext(frames, openSourceFile = promises_open, logger) {\n const filesToLines = {};\n let basePath;\n try {\n basePath = process.cwd();\n } catch {}\n for(let i = frames.length - 1; i >= 0; i--){\n const frame = frames[i];\n const filename = frame?.filename;\n if (!frame || 'string' != typeof filename || 'number' != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;\n if (!isAbsolute(filename) && void 0 === basePath) continue;\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n filesToLines[filename].push(frame.lineno);\n }\n const files = Object.keys(filesToLines);\n if (0 == files.length) return frames;\n const readlinePromises = [];\n for (const file of files){\n const cacheKey = makeSourceCacheKey(file, basePath);\n if (void 0 === cacheKey) continue;\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey)) continue;\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) continue;\n filesToLineRanges.sort((a, b)=>a - b);\n const ranges = makeLineReaderRanges(filesToLineRanges);\n if (ranges.every((r)=>rangeExistsInContentCache(cacheKey, r))) continue;\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger));\n }\n await Promise.all(readlinePromises).catch(()=>{});\n if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);\n LRU_FILE_CONTENTS_CACHE.reduce();\n return frames;\n}\nasync function openRegularSourceFile(path, openSourceFile, logger) {\n let fileHandle;\n let isValid = false;\n try {\n fileHandle = await openSourceFile(path, constants.O_RDONLY | constants.O_NONBLOCK);\n const fileStat = await fileHandle.stat();\n if (!fileStat.isFile()) return;\n if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE) return void logger?.debug(`Skipping source context for oversized file ${path}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);\n isValid = true;\n return fileHandle;\n } catch {\n return;\n } finally{\n if (fileHandle && !isValid) await fileHandle.close().catch(()=>{});\n }\n}\nasync function getContextLinesFromFile(path, ranges, output, cacheKey, openSourceFile, logger) {\n const fileHandle = await openRegularSourceFile(path, openSourceFile, logger);\n if (void 0 === fileHandle) return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n const openedFileHandle = fileHandle;\n return new Promise((resolve)=>{\n let finished = false;\n function destroyStreamAndResolve(stream) {\n if (finished) return;\n finished = true;\n stream?.destroy();\n openedFileHandle.close().then(resolve, resolve);\n }\n let stream;\n try {\n stream = openedFileHandle.createReadStream({\n autoClose: false,\n start: 0,\n end: MAX_CONTEXTLINES_FILE_SIZE - 1\n });\n } catch {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n destroyStreamAndResolve();\n return;\n }\n let lineReaded;\n try {\n lineReaded = createInterface({\n input: stream\n });\n } catch {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n destroyStreamAndResolve(stream);\n return;\n }\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) return void destroyStreamAndResolve(stream);\n let rangeStart = range[0];\n let rangeEnd = range[1];\n function onStreamError() {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve(stream);\n }\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', ()=>destroyStreamAndResolve(stream));\n lineReaded.on('line', (line)=>{\n lineNumber++;\n if (lineNumber < rangeStart) return;\n output[lineNumber] = snipLine(line, 0);\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\nfunction addSourceContextToFrames(frames, cache, basePath) {\n for (const frame of frames)if (frame.filename && void 0 === frame.context_line && 'number' == typeof frame.lineno) {\n const cacheKey = makeSourceCacheKey(frame.filename, basePath);\n const contents = void 0 === cacheKey ? void 0 : cache.get(cacheKey);\n if (void 0 === contents) continue;\n addContextToFrame(frame.lineno, frame, contents);\n }\n}\nfunction addContextToFrame(lineno, frame, contents) {\n if (void 0 === frame.lineno || void 0 === contents) return;\n frame.pre_context = [];\n for(let i = makeRangeStart(lineno); i < lineno; i++){\n const line = contents[i];\n if (void 0 === line) return void clearLineContext(frame);\n frame.pre_context.push(line);\n }\n if (void 0 === contents[lineno]) return void clearLineContext(frame);\n frame.context_line = contents[lineno];\n const end = makeRangeEnd(lineno);\n frame.post_context = [];\n for(let i = lineno + 1; i <= end; i++){\n const line = contents[i];\n if (void 0 === line) break;\n frame.post_context.push(line);\n }\n}\nfunction clearLineContext(frame) {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\nfunction shouldSkipContextLinesForFile(path) {\n return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');\n}\nfunction shouldSkipContextLinesForFrame(frame) {\n if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\nfunction makeSourceCacheKey(path, basePath) {\n if (isAbsolute(path)) return JSON.stringify([\n null,\n path\n ]);\n return void 0 === basePath ? void 0 : JSON.stringify([\n basePath,\n path\n ]);\n}\nfunction rangeExistsInContentCache(cacheKey, range) {\n const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);\n if (void 0 === contents) return false;\n for(let i = range[0]; i <= range[1]; i++)if (void 0 === contents[i]) return false;\n return true;\n}\nfunction makeLineReaderRanges(lines) {\n if (!lines.length) return [];\n let i = 0;\n const line = lines[0];\n if ('number' != typeof line) return [];\n let current = makeContextRange(line);\n const out = [];\n while(true){\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n const next = lines[i + 1];\n if ('number' != typeof next) break;\n if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;\n else {\n out.push(current);\n current = makeContextRange(next);\n }\n i++;\n }\n return out;\n}\nfunction makeContextRange(line) {\n return [\n makeRangeStart(line),\n makeRangeEnd(line)\n ];\n}\nfunction makeRangeStart(line) {\n return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);\n}\nfunction makeRangeEnd(line) {\n return line + DEFAULT_LINES_OF_CONTEXT;\n}\nfunction emplace(map, key, contents) {\n const value = map.get(key);\n if (void 0 === value) {\n map.set(key, contents);\n return contents;\n }\n return value;\n}\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) return newLine;\n if (colno > lineLength) colno = lineLength;\n let start = Math.max(colno - 60, 0);\n if (start < 5) start = 0;\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) end = lineLength;\n if (end === lineLength) start = Math.max(end - 140, 0);\n newLine = newLine.slice(start, end);\n if (start > 0) newLine = `...${newLine}`;\n if (end < lineLength) newLine += '...';\n return newLine;\n}\nexport { MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_FILE_SIZE, MAX_CONTEXTLINES_LINENO, addSourceContext };\n","import { isAbsolute, relative, sep } from \"path\";\nfunction createRelativePathModifier(basePath = process.cwd()) {\n const isWindows = '\\\\' === sep;\n const toUnix = (p)=>isWindows ? p.replace(/\\\\/g, '/') : p;\n const normalizedBase = toUnix(basePath);\n return async (frames)=>{\n for (const frame of frames)if (!(!frame.filename || frame.filename.startsWith('node:') || frame.filename.startsWith('data:'))) {\n if (isAbsolute(frame.filename)) frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));\n }\n return frames;\n };\n}\nexport { createRelativePathModifier };\n","const version = '5.51.1';\nexport { version };\n","const FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n UNKNOWN_ERROR: 'unknown_error'\n};\nexport { FeatureFlagError };\n","import { FeatureFlagError } from \"./types.mjs\";\nclass FeatureFlagEvaluations {\n constructor(init){\n this._host = init.host;\n this._distinctId = init.distinctId;\n this._groups = init.groups;\n this._disableGeoip = init.disableGeoip;\n this._flags = init.flags;\n this._requestId = init.requestId;\n this._evaluatedAt = init.evaluatedAt;\n this._flagDefinitionsLoadedAt = init.flagDefinitionsLoadedAt;\n this._errorsWhileComputing = init.errorsWhileComputing ?? false;\n this._quotaLimited = init.quotaLimited ?? false;\n this._accessed = init.accessed ?? new Set();\n this._isSlice = init.isSlice ?? false;\n }\n isEnabled(key, options = {}) {\n const flag = this._flags[key];\n this._recordAccess(key);\n return flag?.enabled ?? options.defaultValue ?? false;\n }\n getFlag(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n if (!flag) return;\n if (!flag.enabled) return false;\n return flag.variant ?? true;\n }\n getFlagPayload(key) {\n return this._flags[key]?.payload;\n }\n onlyAccessed() {\n const filtered = {};\n for (const key of this._accessed){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n }\n return this._cloneWith(filtered);\n }\n only(keys) {\n const filtered = {};\n const missing = [];\n for (const key of keys){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n else missing.push(key);\n }\n if (missing.length > 0) this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${missing.join(', ')}`);\n return this._cloneWith(filtered);\n }\n get keys() {\n return Object.keys(this._flags);\n }\n _getEventProperties() {\n const properties = {};\n const activeFlags = [];\n for (const [key, flag] of Object.entries(this._flags)){\n const value = false === flag.enabled ? false : flag.variant ?? true;\n properties[`$feature/${key}`] = value;\n if (flag.enabled) activeFlags.push(key);\n }\n if (activeFlags.length > 0) {\n activeFlags.sort();\n properties['$active_feature_flags'] = activeFlags;\n }\n return properties;\n }\n _cloneWith(flags) {\n return new FeatureFlagEvaluations({\n host: this._host,\n distinctId: this._distinctId,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n flags,\n requestId: this._requestId,\n evaluatedAt: this._evaluatedAt,\n flagDefinitionsLoadedAt: this._flagDefinitionsLoadedAt,\n errorsWhileComputing: this._errorsWhileComputing,\n quotaLimited: this._quotaLimited,\n accessed: new Set(this._accessed),\n isSlice: true\n });\n }\n _recordAccess(key) {\n this._accessed.add(key);\n if ('' === this._distinctId) return;\n if (this._isSlice && !(key in this._flags)) return;\n const flag = this._flags[key];\n const response = void 0 === flag ? void 0 : false === flag.enabled ? false : flag.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flag?.id,\n $feature_flag_version: flag?.version,\n $feature_flag_reason: flag?.reason,\n locally_evaluated: flag?.locallyEvaluated ?? false,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: this._requestId,\n $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt\n };\n if (flag?.hasExperiment !== void 0) properties.$feature_flag_has_experiment = flag.hasExperiment;\n if (flag?.locallyEvaluated && void 0 !== this._flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;\n const errors = [];\n if (this._errorsWhileComputing) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (this._quotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n if (void 0 === flag) errors.push(FeatureFlagError.FLAG_MISSING);\n if (errors.length > 0) properties.$feature_flag_error = errors.join(',');\n this._host.captureFlagCalledEventIfNeeded({\n distinctId: this._distinctId,\n key,\n response,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n properties\n });\n }\n}\nexport { FeatureFlagEvaluations };\n","async function hashSHA1(text) {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('SubtleCrypto API not available');\n const hashBuffer = await subtle.digest('SHA-1', new TextEncoder().encode(text));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((byte)=>byte.toString(16).padStart(2, '0')).join('');\n}\nexport { hashSHA1 };\n","import { raceWithTimeout, safeSetTimeout } from \"@posthog/core\";\nimport { hashSHA1 } from \"./crypto.mjs\";\nconst SIXTY_SECONDS = 60000;\nconst LONG_SCALE = 0xfffffffffffffff;\nconst NULL_VALUES_ALLOWED_OPERATORS = [\n 'is_not',\n 'is_set'\n];\nclass ClientError extends Error {\n constructor(message){\n super();\n Error.captureStackTrace(this, this.constructor);\n this.name = 'ClientError';\n this.message = message;\n Object.setPrototypeOf(this, ClientError.prototype);\n }\n}\nfunction setCustomErrorPrototype(error, constructor) {\n error.name = constructor.name;\n Error.captureStackTrace(error, constructor);\n Object.setPrototypeOf(error, constructor.prototype);\n}\nclass InconclusiveMatchError extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, InconclusiveMatchError);\n }\n}\nclass RequiresServerEvaluation extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, RequiresServerEvaluation);\n }\n}\nclass FeatureFlagsPoller {\n constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }){\n this.debugMode = false;\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.pollerStopped = false;\n this.pollingInterval = pollingInterval;\n this.personalApiKey = personalApiKey;\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.loadedSuccessfullyOnce = false;\n this.timeout = timeout;\n this.projectApiKey = projectApiKey;\n this.host = host;\n this.poller = void 0;\n this.fetch = options.fetch || fetch;\n this.onError = options.onError;\n this.customHeaders = customHeaders;\n this.onLoad = options.onLoad;\n this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;\n this.cacheProvider = options.cacheProvider;\n this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;\n this.loadFeatureFlags();\n }\n debug(enabled = true) {\n this.debugMode = enabled;\n }\n logMsgIfDebug(fn) {\n if (this.debugMode) fn();\n }\n createEvaluationContext(distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {\n return {\n distinctId,\n groups,\n personProperties,\n groupProperties,\n evaluationCache\n };\n }\n async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {\n await this.loadFeatureFlags();\n let response;\n let featureFlag;\n if (!this.loadedSuccessfullyOnce) return response;\n featureFlag = this.featureFlagsByKey[key];\n if (void 0 !== featureFlag) {\n const evaluationContext = this.createEvaluationContext(distinctId, groups, personProperties, groupProperties);\n try {\n const result = await this.computeFlagAndPayloadLocally(featureFlag, evaluationContext);\n response = result.value;\n this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${key} -> ${response}`));\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));\n }\n }\n return response;\n }\n async getAllFlagsAndPayloads(evaluationContext, flagKeysToExplicitlyEvaluate) {\n await this.loadFeatureFlags();\n const response = {};\n const payloads = {};\n let fallbackToFlags = 0 == this.featureFlags.length;\n const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key)=>this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;\n const sharedEvaluationContext = {\n ...evaluationContext,\n evaluationCache: evaluationContext.evaluationCache ?? {}\n };\n await Promise.all(flagsToEvaluate.map(async (flag)=>{\n try {\n const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext);\n response[flag.key] = matchValue;\n if (matchPayload) payloads[flag.key] = matchPayload;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));\n fallbackToFlags = true;\n }\n }));\n return {\n response,\n payloads,\n fallbackToFlags\n };\n }\n async computeFlagAndPayloadLocally(flag, evaluationContext, options = {}) {\n const { matchValue, skipLoadCheck = false } = options;\n if (!skipLoadCheck) await this.loadFeatureFlags();\n if (!this.loadedSuccessfullyOnce) return {\n value: false,\n payload: null\n };\n let flagValue;\n flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, evaluationContext);\n const payload = this.getFeatureFlagPayload(flag.key, flagValue);\n return {\n value: flagValue,\n payload\n };\n }\n async computeFlagValueLocally(flag, evaluationContext) {\n const { distinctId, groups, personProperties, groupProperties } = evaluationContext;\n if (!flag.active) return false;\n if (flag.ensure_experience_continuity) throw new InconclusiveMatchError('Flag has experience continuity enabled');\n const flagFilters = flag.filters || {};\n const aggregation_group_type_index = flagFilters.aggregation_group_type_index;\n if (void 0 != aggregation_group_type_index) {\n const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];\n if (!groupName) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));\n throw new InconclusiveMatchError('Flag has unknown group type index');\n }\n if (!(groupName in groups)) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));\n return false;\n }\n if ('device_id' === flag.bucketing_identifier && (personProperties?.$device_id === void 0 || personProperties?.$device_id === null || personProperties?.$device_id === '')) this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${flag.key}`));\n const focusedGroupProperties = groupProperties[groupName];\n return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext);\n }\n {\n const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties);\n if (void 0 === bucketingValue) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${flag.key} without $device_id, falling back to server evaluation`));\n throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`);\n }\n return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext);\n }\n }\n getBucketingValueForFlag(flag, distinctId, properties) {\n if (flag.filters?.aggregation_group_type_index != void 0) return distinctId;\n if ('device_id' === flag.bucketing_identifier) {\n const deviceId = properties?.$device_id;\n if (null == deviceId || '' === deviceId) return;\n return deviceId;\n }\n return distinctId;\n }\n getFeatureFlagPayload(key, flagValue) {\n let payload = null;\n if (false !== flagValue && null != flagValue) {\n if ('boolean' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;\n else if ('string' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;\n if (null != payload) {\n if ('object' == typeof payload) return payload;\n if ('string' == typeof payload) try {\n return JSON.parse(payload);\n } catch {}\n return payload;\n }\n }\n return null;\n }\n async evaluateFlagDependency(property, properties, evaluationContext) {\n const { evaluationCache } = evaluationContext;\n const targetFlagKey = property.key;\n if (!this.featureFlagsByKey) throw new InconclusiveMatchError('Feature flags not available for dependency evaluation');\n if (!('dependency_chain' in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);\n const dependencyChain = property.dependency_chain;\n if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);\n if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);\n for (const depFlagKey of dependencyChain){\n if (!(depFlagKey in evaluationCache)) {\n const depFlag = this.featureFlagsByKey[depFlagKey];\n if (depFlag) if (depFlag.active) try {\n const depResult = await this.computeFlagValueLocally(depFlag, evaluationContext);\n evaluationCache[depFlagKey] = depResult;\n } catch (error) {\n throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);\n }\n else evaluationCache[depFlagKey] = false;\n else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);\n }\n const cachedResult = evaluationCache[depFlagKey];\n if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);\n }\n const targetFlagValue = evaluationCache[targetFlagKey];\n return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);\n }\n flagEvaluatesToExpectedValue(expectedValue, flagValue) {\n if ('boolean' == typeof expectedValue) return expectedValue === flagValue || 'string' == typeof flagValue && '' !== flagValue && true === expectedValue;\n if ('string' == typeof expectedValue) return flagValue === expectedValue;\n return false;\n }\n async matchFeatureFlagProperties(flag, bucketingValue, properties, evaluationContext) {\n const flagFilters = flag.filters || {};\n const flagConditions = flagFilters.groups || [];\n const flagAggregation = flagFilters.aggregation_group_type_index;\n const earlyExitEnabled = flagFilters.early_exit ?? false;\n const { groups, groupProperties } = evaluationContext;\n let isInconclusive = false;\n let result;\n for (const condition of flagConditions)try {\n const conditionAggregation = void 0 !== condition.aggregation_group_type_index ? condition.aggregation_group_type_index : flagAggregation;\n let effectiveProperties = properties;\n let effectiveBucketingValue = bucketingValue;\n if (conditionAggregation !== flagAggregation) {\n if (null != conditionAggregation) {\n const groupName = this.groupTypeMapping[String(conditionAggregation)];\n if (!groupName || !(groupName in groups)) {\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`));\n continue;\n }\n if (!(groupName in groupProperties)) {\n isInconclusive = true;\n continue;\n }\n effectiveProperties = groupProperties[groupName];\n effectiveBucketingValue = groups[groupName];\n }\n }\n const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);\n if ('match' === matchResult) {\n const variantOverride = condition.variant;\n const flagVariants = flagFilters.multivariate?.variants || [];\n result = variantOverride && flagVariants.some((variant)=>variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;\n break;\n }\n if (earlyExitEnabled && 'out_of_rollout_bound' === matchResult) return false;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation) throw e;\n if (e instanceof InconclusiveMatchError) isInconclusive = true;\n else throw e;\n }\n if (void 0 !== result) return result;\n if (isInconclusive) throw new InconclusiveMatchError(\"Can't determine if feature flag is enabled or not with given properties\");\n return false;\n }\n async isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext) {\n const rolloutPercentage = condition.rollout_percentage;\n const warnFunction = (msg)=>{\n this.logMsgIfDebug(()=>console.warn(msg));\n };\n if ((condition.properties || []).length > 0) {\n for (const prop of condition.properties){\n const propertyType = prop.type;\n let matches = false;\n if ('cohort' === propertyType) {\n const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp)=>this.evaluateFlagDependency(depProp, properties, evaluationContext));\n matches = 'not_in' === prop.operator ? !inCohort : inCohort;\n } else matches = 'flag' === propertyType ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);\n if (!matches) return 'no_match';\n }\n if (void 0 == rolloutPercentage) return 'match';\n }\n if (void 0 != rolloutPercentage && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100.0) return 'out_of_rollout_bound';\n return 'match';\n }\n async getMatchingVariant(flag, bucketingValue) {\n const hashValue = await _hash(flag.key, bucketingValue, 'variant');\n const matchingVariant = this.variantLookupTable(flag).find((variant)=>hashValue >= variant.valueMin && hashValue < variant.valueMax);\n if (matchingVariant) return matchingVariant.key;\n }\n variantLookupTable(flag) {\n const lookupTable = [];\n let valueMin = 0;\n let valueMax = 0;\n const flagFilters = flag.filters || {};\n const multivariates = flagFilters.multivariate?.variants || [];\n multivariates.forEach((variant)=>{\n valueMax = valueMin + variant.rollout_percentage / 100.0;\n lookupTable.push({\n valueMin,\n valueMax,\n key: variant.key\n });\n valueMin = valueMax;\n });\n return lookupTable;\n }\n updateFlagState(flagData) {\n this.featureFlags = flagData.flags;\n this.featureFlagsByKey = flagData.flags.reduce((acc, curr)=>(acc[curr.key] = curr, acc), {});\n this.groupTypeMapping = flagData.groupTypeMapping;\n this.cohorts = flagData.cohorts;\n this.loadedSuccessfullyOnce = true;\n this.onMinimalFlagCalledEvents?.(true === flagData.minimalFlagCalledEvents);\n }\n warnAboutExperienceContinuityFlags(flags) {\n if (this.strictLocalEvaluation) return;\n const experienceContinuityFlags = flags.filter((f)=>f.ensure_experience_continuity);\n if (experienceContinuityFlags.length > 0) console.warn(`[PostHog] You are using local evaluation but ${experienceContinuityFlags.length} flag(s) have experience continuity enabled: ${experienceContinuityFlags.map((f)=>f.key).join(', ')}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`);\n }\n async loadFromCache(debugMessage) {\n if (!this.cacheProvider) return false;\n try {\n const cached = await this.cacheProvider.getFlagDefinitions();\n if (cached) {\n this.updateFlagState(cached);\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(cached.flags);\n return true;\n }\n return false;\n } catch (err) {\n this.onError?.(new Error(`Failed to load from cache: ${err}`));\n return false;\n }\n }\n async loadFeatureFlags(forceReload = false) {\n if (this.loadedSuccessfullyOnce && !forceReload) return;\n if (!forceReload && this.nextFetchAllowedAt && Date.now() < this.nextFetchAllowedAt) return void this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Skipping fetch, in backoff period'));\n if (!this.loadingPromise) this.loadingPromise = this._loadFeatureFlags().catch((err)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(()=>{\n this.loadingPromise = void 0;\n });\n return this.loadingPromise;\n }\n isLocalEvaluationReady() {\n return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;\n }\n getFlagDefinitionsLoadedAt() {\n return this.flagDefinitionsLoadedAt;\n }\n getPollingInterval() {\n if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;\n return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);\n }\n beginBackoff() {\n this.shouldBeginExponentialBackoff = true;\n this.backOffCount += 1;\n this.nextFetchAllowedAt = Date.now() + this.getPollingInterval();\n }\n clearBackoff() {\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.nextFetchAllowedAt = void 0;\n }\n async _loadFeatureFlags() {\n if (this.poller) {\n clearTimeout(this.poller);\n this.poller = void 0;\n }\n try {\n let shouldFetch = true;\n if (this.cacheProvider) try {\n shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();\n } catch (err) {\n this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));\n }\n if (!shouldFetch) {\n const loaded = await this.loadFromCache('Loaded flags from cache (skipped fetch)');\n if (loaded) return;\n if (this.loadedSuccessfullyOnce) return;\n }\n const res = await this._requestFeatureFlagDefinitions();\n if (!res) return;\n switch(res.status){\n case 304:\n this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Flags not modified (304), using cached data'));\n this.flagsEtag = res.headers?.get('ETag') ?? this.flagsEtag;\n this.loadedSuccessfullyOnce = true;\n this.clearBackoff();\n return;\n case 401:\n this.beginBackoff();\n throw new ClientError(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 402:\n 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');\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.onMinimalFlagCalledEvents?.(false);\n return;\n case 403:\n this.beginBackoff();\n throw new ClientError(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);\n case 429:\n this.beginBackoff();\n 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`);\n case 200:\n {\n const responseJson = await res.json() ?? {};\n if (!('flags' in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));\n this.flagsEtag = res.headers?.get('ETag') ?? void 0;\n const flagData = {\n flags: responseJson.flags ?? [],\n groupTypeMapping: responseJson.group_type_mapping || {},\n cohorts: responseJson.cohorts || {},\n minimalFlagCalledEvents: true === responseJson.minimal_flag_called_events\n };\n this.updateFlagState(flagData);\n this.flagDefinitionsLoadedAt = Date.now();\n this.clearBackoff();\n if (this.cacheProvider && shouldFetch) try {\n await this.cacheProvider.onFlagDefinitionsReceived(flagData);\n } catch (err) {\n this.onError?.(new Error(`Failed to store in cache: ${err}`));\n }\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(flagData.flags);\n break;\n }\n default:\n return;\n }\n } catch (err) {\n if (err instanceof ClientError) this.onError?.(err);\n } finally{\n if (!this.pollerStopped) this.poller = setTimeout(()=>this.loadFeatureFlags(true), this.getPollingInterval());\n }\n }\n getPersonalApiKeyRequestOptions(method = 'GET', etag) {\n const headers = {\n ...this.customHeaders,\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.personalApiKey}`\n };\n if (etag) headers['If-None-Match'] = etag;\n return {\n method,\n headers\n };\n }\n async _requestFeatureFlagDefinitions() {\n const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;\n const options = this.getPersonalApiKeyRequestOptions('GET', this.flagsEtag);\n let abortTimeout = null;\n if (this.timeout && 'number' == typeof this.timeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.timeout);\n options.signal = controller.signal;\n }\n const clearAbortTimeout = ()=>clearTimeout(abortTimeout);\n try {\n const fetch1 = this.fetch;\n const res = await fetch1(url, options);\n if (200 !== res.status) {\n clearAbortTimeout();\n return res;\n }\n return {\n status: res.status,\n headers: res.headers,\n body: res.body,\n text: async ()=>{\n try {\n return await res.text();\n } finally{\n clearAbortTimeout();\n }\n },\n json: async ()=>{\n try {\n return await res.json();\n } finally{\n clearAbortTimeout();\n }\n }\n };\n } catch (err) {\n clearAbortTimeout();\n throw err;\n }\n }\n async stopPoller(timeoutMs = 30000) {\n this.pollerStopped = true;\n clearTimeout(this.poller);\n this.poller = void 0;\n if (this.cacheProvider) try {\n const shutdownResult = this.cacheProvider.shutdown();\n if (shutdownResult instanceof Promise) await raceWithTimeout(shutdownResult, timeoutMs, ()=>{\n throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);\n });\n } catch (err) {\n this.onError?.(new Error(`Error during cache shutdown: ${err}`));\n }\n }\n}\nasync function _hash(key, bucketingValue, salt = '') {\n const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);\n return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;\n}\nfunction matchProperty(property, propertyValues, warnFunction) {\n const key = property.key;\n const value = property.value;\n const operator = property.operator || 'exact';\n if (key in propertyValues) {\n if ('is_not_set' === operator) return false;\n } else {\n if ('is_not_set' === operator) return true;\n throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);\n }\n const overrideValue = propertyValues[key];\n if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {\n if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);\n return false;\n }\n function computeExactMatch(value, overrideValue) {\n if (Array.isArray(value)) return value.map((val)=>String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());\n return String(value).toLowerCase() === String(overrideValue).toLowerCase();\n }\n function compare(lhs, rhs, operator) {\n if ('gt' === operator) return lhs > rhs;\n if ('gte' === operator) return lhs >= rhs;\n if ('lt' === operator) return lhs < rhs;\n if ('lte' === operator) return lhs <= rhs;\n throw new Error(`Invalid operator: ${operator}`);\n }\n switch(operator){\n case 'exact':\n return computeExactMatch(value, overrideValue);\n case 'is_not':\n return !computeExactMatch(value, overrideValue);\n case 'is_set':\n return key in propertyValues;\n case 'icontains':\n return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'not_icontains':\n return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'starts_with':\n return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());\n case 'not_starts_with':\n return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());\n case 'ends_with':\n return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());\n case 'not_ends_with':\n return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());\n case 'regex':\n return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));\n case 'not_regex':\n return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n {\n const parsedValue = 'number' == typeof value ? value : parseFloat(String(value));\n let parsedOverride;\n parsedOverride = 'number' == typeof overrideValue ? overrideValue : null != overrideValue ? parseFloat(String(overrideValue)) : NaN;\n if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride)) return compare(parsedOverride, parsedValue, operator);\n return compare(String(overrideValue), String(value), operator);\n }\n case 'is_date_after':\n case 'is_date_before':\n {\n if ('boolean' == typeof value) throw new InconclusiveMatchError(\"Date operations cannot be performed on boolean values\");\n let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));\n if (null == parsedDate) parsedDate = convertToDateTime(value);\n if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);\n const overrideDate = convertToDateTime(overrideValue);\n if ([\n 'is_date_before'\n ].includes(operator)) return overrideDate < parsedDate;\n return overrideDate > parsedDate;\n }\n case 'semver_eq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 === cmp;\n }\n case 'semver_neq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 !== cmp;\n }\n case 'semver_gt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp > 0;\n }\n case 'semver_gte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp >= 0;\n }\n case 'semver_lt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp < 0;\n }\n case 'semver_lte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp <= 0;\n }\n case 'semver_tilde':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeTildeBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_caret':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeCaretBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_wildcard':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeWildcardBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n default:\n throw new InconclusiveMatchError(`Unknown operator: ${operator}`);\n }\n}\nfunction checkCohortExists(cohortId, cohortProperties) {\n if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);\n}\nasync function matchCohort(property, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n const cohortId = String(property.value);\n checkCohortExists(cohortId, cohortProperties);\n const propertyGroup = cohortProperties[cohortId];\n return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n}\nasync function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n if (!propertyGroup) return true;\n const propertyGroupType = propertyGroup.type;\n const properties = propertyGroup.values;\n if (!properties || 0 === properties.length) return true;\n let errorMatchingLocally = false;\n if ('values' in properties[0]) {\n for (const prop of properties)try {\n const matches = await matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n if ('AND' === propertyGroupType) {\n if (!matches) return false;\n } else if (matches) return true;\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"Can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n }\n for (const prop of properties)try {\n let matches;\n if ('cohort' === prop.type) matches = await matchCohort(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n else if ('flag' === prop.type) {\n if (!flagDependencyEvaluator) throw new InconclusiveMatchError(`Flag dependency '${prop.key || 'unknown'}' cannot be evaluated without a flag dependency evaluator`);\n matches = await flagDependencyEvaluator(prop);\n } else matches = matchProperty(prop, propertyValues);\n const negation = prop.negation || false;\n if ('AND' === propertyGroupType) {\n if (!matches && !negation) return false;\n if (matches && negation) return false;\n } else {\n if (matches && !negation) return true;\n if (!matches && negation) return true;\n }\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n}\nfunction isValidRegex(regex) {\n try {\n new RegExp(regex);\n return true;\n } catch (err) {\n return false;\n }\n}\nfunction parseSemverNumericIdentifier(part, raw) {\n if (!/^\\d+$/.test(part)) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n if (part.length > 1 && '0' === part[0]) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n return parseInt(part, 10);\n}\nfunction parseSemver(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const baseVersion = text.split('-')[0].split('+')[0];\n if (!baseVersion || baseVersion.startsWith('.')) throw new InconclusiveMatchError(`Invalid semver: ${value}`);\n const parts = baseVersion.split('.');\n const parsePart = (part)=>{\n if (void 0 === part || '' === part) return 0;\n return parseSemverNumericIdentifier(part, value);\n };\n const major = parsePart(parts[0]);\n const minor = parsePart(parts[1]);\n const patch = parsePart(parts[2]);\n return [\n major,\n minor,\n patch\n ];\n}\nfunction compareSemverTuples(a, b) {\n for(let i = 0; i < 3; i++){\n if (a[i] < b[i]) return -1;\n if (a[i] > b[i]) return 1;\n }\n return 0;\n}\nfunction computeTildeBounds(value) {\n const parsed = parseSemver(value);\n const lower = [\n parsed[0],\n parsed[1],\n parsed[2]\n ];\n const upper = [\n parsed[0],\n parsed[1] + 1,\n 0\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeCaretBounds(value) {\n const parsed = parseSemver(value);\n const [major, minor, patch] = parsed;\n const lower = [\n major,\n minor,\n patch\n ];\n let upper;\n upper = major > 0 ? [\n major + 1,\n 0,\n 0\n ] : minor > 0 ? [\n 0,\n minor + 1,\n 0\n ] : [\n 0,\n 0,\n patch + 1\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeWildcardBounds(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const cleanedText = text.replace(/\\.\\*$/, '').replace(/\\*$/, '');\n if (!cleanedText) throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n const parts = cleanedText.split('.');\n const parseWildcardPart = (part)=>{\n try {\n return parseSemverNumericIdentifier(part, value);\n } catch {\n throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n }\n };\n const major = parseWildcardPart(parts[0]);\n let lower;\n let upper;\n if (1 === parts.length) {\n lower = [\n major,\n 0,\n 0\n ];\n upper = [\n major + 1,\n 0,\n 0\n ];\n } else {\n const minor = parseWildcardPart(parts[1]);\n lower = [\n major,\n minor,\n 0\n ];\n upper = [\n major,\n minor + 1,\n 0\n ];\n }\n return {\n lower,\n upper\n };\n}\nfunction convertToDateTime(value) {\n if (value instanceof Date) return value;\n if ('string' == typeof value || 'number' == typeof value) {\n const date = new Date(value);\n if (!isNaN(date.valueOf())) return date;\n throw new InconclusiveMatchError(`${value} is in an invalid date format`);\n }\n throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);\n}\nfunction relativeDateParseForFeatureFlagMatching(value) {\n const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;\n const match = value.match(regex);\n const parsedDt = new Date(new Date().toISOString());\n if (!match) return null;\n {\n if (!match.groups) return null;\n const number = parseInt(match.groups['number']);\n if (number >= 10000) return null;\n const interval = match.groups['interval'];\n if ('h' == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);\n else if ('d' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);\n else if ('w' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);\n else if ('m' == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);\n else {\n if ('y' != interval) return null;\n parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);\n }\n return parsedDt;\n }\n}\nexport { ClientError, FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation, matchProperty, parseSemver, relativeDateParseForFeatureFlagMatching };\n","const UNHANDLED_REJECTION_OPTION_NAMES = [\n '--unhandled-rejections',\n '--unhandled_rejections'\n];\nconst UNHANDLED_REJECTION_MODES = new Set([\n 'throw',\n 'strict',\n 'warn',\n 'warn-with-error-code',\n 'none'\n]);\nconst STARTUP_EXEC_ARGV = [\n ...globalThis.process?.execArgv ?? []\n];\nconst STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;\nfunction splitNodeOptions(nodeOptions) {\n const args = [];\n let current = '';\n let isInString = false;\n for(let index = 0; index < nodeOptions.length; index++){\n const character = nodeOptions[index];\n if ('\\\\' === character && isInString && index + 1 < nodeOptions.length) current += nodeOptions[++index];\n else if (' ' !== character || isInString) if ('\"' === character) isInString = !isInString;\n else current += character;\n else if (current) {\n args.push(current);\n current = '';\n }\n }\n if (current) args.push(current);\n return args;\n}\nfunction findUnhandledRejectionMode(args) {\n let mode;\n for(let index = 0; index < args.length; index++){\n const argument = args[index];\n const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name)=>argument === name || argument.startsWith(`${name}=`));\n if (!optionName) continue;\n const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);\n if (UNHANDLED_REJECTION_MODES.has(value)) mode = value;\n }\n return mode;\n}\nfunction getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {\n return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? '')) ?? 'throw';\n}\nconst STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();\nfunction captureUncaughtException(captureFn, error, origin) {\n captureFn(error, {\n mechanism: {\n type: 'unhandledRejection' === origin ? 'onunhandledrejection' : 'onuncaughtexception',\n handled: false\n }\n });\n}\nfunction makeUncaughtExceptionHandler(captureFn, onFatalFn) {\n let calledFatalError = false;\n return Object.assign((error, origin)=>{\n const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;\n captureUncaughtException(captureFn, error, origin);\n if (!calledFatalError && 0 === userProvidedListenersCount) {\n calledFatalError = true;\n onFatalFn(error);\n }\n }, {\n _posthogErrorHandler: true\n });\n}\nfunction addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {\n const process = globalThis.process;\n if (!process) return;\n if ('strict' === mode) return void process.on('uncaughtExceptionMonitor', (error, origin)=>captureUncaughtException(captureFn, error, origin));\n process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));\n}\nfunction addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {\n const process = globalThis.process;\n if (!process || 'throw' === mode || 'strict' === mode || 'warn-with-error-code' === mode) return;\n process.on('unhandledRejection', (reason)=>{\n captureFn(reason, {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false\n }\n });\n });\n}\nexport { addUncaughtExceptionListener, addUnhandledRejectionListener, getUnhandledRejectionMode };\n","import { addUncaughtExceptionListener, addUnhandledRejectionListener } from \"./autocapture.mjs\";\nimport { BucketedRateLimiter, ErrorTracking, isObject, resolveExceptionRateLimiterConfig } from \"@posthog/core\";\nconst SHUTDOWN_TIMEOUT = 2000;\nclass error_tracking_ErrorTracking {\n constructor(client, options, _logger){\n this.client = client;\n this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;\n this._logger = _logger;\n this._rateLimiter = new BucketedRateLimiter({\n ...resolveExceptionRateLimiterConfig(options),\n refillInterval: 10000,\n _logger: this._logger\n });\n this.startAutocaptureIfEnabled();\n }\n static isPreviouslyCapturedError(x) {\n return isObject(x) && '__posthog_previously_captured_error' in x && true === x.__posthog_previously_captured_error;\n }\n static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {\n const properties = {\n ...additionalProperties\n };\n const exceptionProperties = builder.buildFromUnknown(error, hint);\n exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);\n const injectedReleaseId = ErrorTracking.getInjectedReleaseId();\n if (injectedReleaseId) properties.$release_id = injectedReleaseId;\n return {\n event: '$exception',\n distinctId: distinctId,\n properties: {\n ...exceptionProperties,\n ...properties\n },\n _originatedFromCaptureException: true\n };\n }\n startAutocaptureIfEnabled() {\n if (this.isEnabled()) {\n addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));\n addUnhandledRejectionListener(this.onException.bind(this));\n }\n }\n onException(exception, hint) {\n this.client.addPendingPromise((async ()=>{\n if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {\n const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);\n const exceptionProperties = eventMessage.properties;\n const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? 'Exception';\n const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);\n if (isRateLimited) return void this._logger.info('Skipping exception capture because of client rate limiting.', {\n exception: exceptionType\n });\n return this.client._capturePreparedEvent(eventMessage, false);\n }\n })());\n }\n async onFatalError(exception) {\n console.error(exception);\n await this.client.shutdown(SHUTDOWN_TIMEOUT);\n globalThis.process.exit(1);\n }\n isEnabled() {\n return !this.client.isDisabled && this._exceptionAutocaptureEnabled;\n }\n shutdown() {\n this._rateLimiter.stop();\n }\n}\nexport { error_tracking_ErrorTracking as default };\n","class PostHogMemoryStorage {\n getProperty(key) {\n return this._memoryStorage[key];\n }\n setProperty(key, value) {\n this._memoryStorage[key] = null !== value ? value : void 0;\n }\n constructor(){\n this._memoryStorage = {};\n }\n}\nexport { PostHogMemoryStorage };\n","function isCaptureMode(value) {\n return 'v0' === value || 'v1' === value;\n}\nfunction resolveCaptureMode() {\n const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;\n return isCaptureMode(envMode) ? envMode : 'v0';\n}\nexport { resolveCaptureMode };\n","const AI_EVENT_PREFIX = '$ai_';\nconst ANALYTICS_ROUTE = 'analytics';\nconst AI_ROUTE = 'ai';\nfunction isLegacyOnlyEvent(message) {\n return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);\n}\nexport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent };\n","class CaptureV1Error extends Error {\n constructor({ requestId, drops, retryExhausted, cause }){\n super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';\n this.requestId = requestId;\n this.drops = drops;\n this.retryExhausted = retryExhausted;\n this.cause = cause;\n }\n static buildMessage(requestId, drops, retryExhausted, cause) {\n let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;\n if (cause instanceof Error) message += ` (${cause.message})`;\n return message;\n }\n}\nexport { CaptureV1Error };\n","function coerceBool(value) {\n if ('boolean' == typeof value) return value;\n if ('number' == typeof value) return 0 !== value;\n if ('string' == typeof value) {\n const normalized = value.trim().toLowerCase();\n if ('true' === normalized || '1' === normalized) return true;\n if ('false' === normalized || '0' === normalized) return false;\n }\n}\nfunction coerceString(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst OPTION_SENTINELS = [\n {\n property: '$cookieless_mode',\n optionKey: 'cookieless_mode',\n coerce: coerceBool\n },\n {\n property: '$ignore_sent_at',\n optionKey: 'disable_skew_correction',\n coerce: coerceBool\n },\n {\n property: '$process_person_profile',\n optionKey: 'process_person_profile',\n coerce: coerceBool\n },\n {\n property: '$product_tour_id',\n optionKey: 'product_tour_id',\n coerce: coerceString\n }\n];\nconst TOPLEVEL_SENTINELS = [\n {\n property: '$session_id',\n field: 'session_id'\n },\n {\n property: '$window_id',\n field: 'window_id'\n }\n];\nfunction isRecord(value) {\n return 'object' == typeof value && null !== value && !Array.isArray(value);\n}\nfunction toRfc3339(timestamp) {\n if ('string' == typeof timestamp) {\n const asDate = new Date(timestamp);\n if (Number.isNaN(asDate.getTime())) return new Date().toISOString();\n const normalized = asDate.toISOString();\n const fractionalSeconds = timestamp.match(/\\.(\\d+)(?:Z|[+-]\\d{2}:?\\d{2})?$/i)?.[1];\n return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\\.\\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;\n }\n if (timestamp instanceof Date) return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();\n const asDate = null == timestamp ? new Date() : new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();\n}\nfunction relocateInto(properties, key, value) {\n if (void 0 !== value && !(key in properties)) properties[key] = value;\n}\nfunction buildV1Event(message) {\n const sourceProperties = isRecord(message.properties) ? message.properties : {};\n const properties = {\n ...sourceProperties\n };\n const options = {};\n for (const { property, optionKey, coerce } of OPTION_SENTINELS)if (property in properties) {\n const coerced = coerce(properties[property]);\n if (void 0 !== coerced) options[optionKey] = coerced;\n delete properties[property];\n }\n const topLevel = {};\n for (const { property, field } of TOPLEVEL_SENTINELS)if (property in properties) {\n const value = properties[property];\n if ('string' == typeof value) topLevel[field] = value;\n delete properties[property];\n }\n delete properties.$lib;\n delete properties.$lib_version;\n relocateInto(properties, '$set', message.$set);\n relocateInto(properties, '$set_once', message.$set_once);\n return {\n event: String(message.event ?? ''),\n uuid: String(message.uuid ?? ''),\n distinct_id: String(message.distinct_id ?? ''),\n timestamp: toRfc3339(message.timestamp),\n ...topLevel,\n options,\n properties\n };\n}\nfunction buildV1Batch(messages, { createdAt, historicalMigration }) {\n const batch = {\n created_at: createdAt,\n batch: messages.map(buildV1Event)\n };\n if (historicalMigration) batch.historical_migration = true;\n return batch;\n}\nexport { buildV1Batch, buildV1Event, coerceBool, coerceString };\n","import { gzipCompress, safeJsonStringify, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { CaptureV1Error } from \"./errors.mjs\";\nimport { buildV1Batch } from \"./transform.mjs\";\nconst V1_ANALYTICS_PATH = '/i/v1/analytics/events';\nconst DEFAULT_MAX_BACKOFF_MS = 30000;\nconst RETRYABLE_STATUSES = new Set([\n 408,\n 500,\n 502,\n 503,\n 504\n]);\nclass V1CaptureSender {\n constructor(config, hooks){\n this.config = config;\n this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;\n this.fetchFn = hooks.fetch;\n this.onError = hooks.onError;\n this.now = hooks.now ?? Date.now;\n this.sleep = hooks.sleep ?? ((ms)=>new Promise((resolve)=>safeSetTimeout(resolve, ms)));\n this.generateRequestId = hooks.generateRequestId ?? uuidv7;\n this.compress = hooks.compress ?? gzipCompress;\n }\n async sendV1Batch(messages) {\n if (0 === messages.length) return;\n const requestId = this.generateRequestId();\n const createdAt = new Date(this.now()).toISOString();\n const { batch } = buildV1Batch(messages, {\n createdAt,\n historicalMigration: this.config.historicalMigration\n });\n const url = `${this.config.host}${V1_ANALYTICS_PATH}`;\n const drops = [];\n let pending = batch;\n const maxAttempts = Math.max(1, this.config.maxAttempts);\n for(let attempt = 1; attempt <= maxAttempts; attempt++){\n const isLastAttempt = attempt === maxAttempts;\n const payload = safeJsonStringify({\n created_at: createdAt,\n ...this.config.historicalMigration ? {\n historical_migration: true\n } : {},\n batch: pending\n });\n let captureAttempt;\n let retryDelayMs;\n try {\n captureAttempt = await this.sendOnce(url, payload, attempt, requestId);\n const { response, signal } = captureAttempt;\n const { status } = response;\n if (status < 200 || status >= 300) if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {\n const retryAfterMs = this.parseRetryAfter(response);\n await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});\n retryDelayMs = this.backoffDelay(attempt, retryAfterMs);\n } else {\n const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);\n return this.surfaceBatchFailure(requestId, drops, pending, httpError);\n }\n else {\n let parsed;\n try {\n parsed = await captureAttempt.waitFor(this.parseResponse(response));\n } catch (error) {\n if (signal.aborted) throw error;\n return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));\n }\n const retryable = this.classify(pending, parsed, drops);\n if (0 === retryable.length) return this.surfacePartialDrops(requestId, drops);\n if (isLastAttempt) return void this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: retryable.map((event)=>event.uuid)\n }));\n pending = retryable;\n const retryAfterMs = this.parseRetryAfter(response);\n retryDelayMs = this.backoffDelay(attempt, retryAfterMs);\n }\n } catch (transportError) {\n if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;\n if (isLastAttempt) return this.surfaceBatchFailure(requestId, drops, pending, transportError);\n retryDelayMs = this.backoffDelay(attempt);\n } finally{\n captureAttempt?.cleanup();\n }\n if (void 0 !== retryDelayMs) await this.sleep(retryDelayMs);\n }\n }\n async sendOnce(url, payload, attempt, requestId) {\n const headers = this.buildHeaders(attempt, requestId);\n let body = payload;\n if (this.config.compressionEnabled) {\n const compressed = await this.compress(payload, this.config.isDebug);\n if (null !== compressed) {\n body = compressed;\n headers['Content-Encoding'] = 'gzip';\n }\n }\n const controller = new AbortController();\n let timeoutPhase = 'waiting for response headers';\n let timer;\n const deadline = new Promise((_resolve, reject)=>{\n timer = safeSetTimeout(()=>{\n const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n controller.abort(timeoutError);\n }, this.config.requestTimeoutMs);\n });\n try {\n const fetchPromise = this.fetchFn(url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal\n });\n let responseAccepted = false;\n fetchPromise.then((lateResponse)=>{\n if (controller.signal.aborted && !responseAccepted) this.cancelBody(lateResponse);\n }).catch(()=>{});\n const response = await Promise.race([\n fetchPromise,\n deadline\n ]);\n responseAccepted = true;\n timeoutPhase = 'while reading the response body';\n let cleanedUp = false;\n let cancellation;\n const cancelBody = ()=>cancellation ??= this.cancelBody(response);\n return {\n response,\n signal: controller.signal,\n waitFor: (operation)=>Promise.race([\n operation,\n deadline\n ]),\n cancelBody,\n cleanup: ()=>{\n if (cleanedUp) return;\n cleanedUp = true;\n clearTimeout(timer);\n if (controller.signal.aborted) cancelBody();\n }\n };\n } catch (error) {\n clearTimeout(timer);\n throw error;\n }\n }\n buildHeaders(attempt, requestId) {\n const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.config.apiKey}`,\n 'PostHog-Sdk-Info': sdkInfo,\n 'PostHog-Attempt': String(attempt),\n 'PostHog-Request-Id': requestId,\n 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()\n };\n if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;\n return headers;\n }\n classify(pending, parsed, drops) {\n const results = parsed.results ?? {};\n const retryable = [];\n for (const event of pending){\n const result = results[event.uuid];\n if (result) {\n if ('drop' === result.result) drops.push({\n uuid: event.uuid,\n details: result.details ?? void 0\n });\n else if ('retry' === result.result) retryable.push(event);\n }\n }\n return retryable;\n }\n backoffDelay(attempt, retryAfterMs) {\n const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);\n if (void 0 === retryAfterMs) return exponential;\n return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));\n }\n parseRetryAfter(response) {\n const raw = response.headers?.get('Retry-After');\n if (!raw) return;\n const trimmed = raw.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = parseInt(trimmed, 10);\n return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return;\n const delta = dateMs - this.now();\n return delta > 0 ? delta : void 0;\n }\n async parseResponse(response) {\n const text = await response.text();\n const parsed = JSON.parse(text);\n if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');\n const results = parsed.results;\n if (void 0 !== results && ('object' != typeof results || null === results || Array.isArray(results))) throw new Error('unexpected results shape');\n return {\n results: results ?? {}\n };\n }\n async buildHttpError(response, status, waitFor) {\n let bodyText = '';\n try {\n bodyText = (await waitFor(response.text())).slice(0, 512);\n } catch {}\n const suffix = bodyText ? `: ${bodyText}` : '';\n return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);\n }\n surfaceBatchFailure(requestId, drops, pending, cause) {\n this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: pending.map((event)=>event.uuid),\n cause\n }));\n }\n surfacePartialDrops(requestId, drops) {\n if (drops.length > 0) this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: []\n }));\n }\n async cancelBody(response) {\n try {\n await response.body?.cancel();\n } catch {}\n }\n}\nexport { V1CaptureSender };\n","const AI_CAPTURE_ROUTE = 'ai-capture';\nconst AI_CAPTURE_ENDPOINT_PATH = '/i/v0/ai/batch/';\nconst AI_MAX_EVENT_BYTES = 8388608;\nconst AI_BATCH_TARGET_BYTES = 5242880;\nexport { AI_BATCH_TARGET_BYTES, AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES };\n","import { safeJsonStringify } from \"@posthog/core\";\nimport { AI_BATCH_TARGET_BYTES, AI_MAX_EVENT_BYTES } from \"./routing.mjs\";\nconst encoder = new TextEncoder();\nfunction eventByteSize(message) {\n return encoder.encode(safeJsonStringify(message)).length;\n}\nfunction partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {\n const batches = [];\n const dropped = [];\n let current = [];\n let currentBytes = 0;\n for (const message of messages){\n if (void 0 === message) continue;\n const bytes = eventByteSize(message);\n if (bytes > maxEventBytes) {\n dropped.push({\n event: 'string' == typeof message.event ? message.event : 'unknown',\n bytes\n });\n continue;\n }\n if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {\n batches.push(current);\n current = [];\n currentBytes = 0;\n }\n current.push(message);\n currentBytes += bytes;\n }\n if (current.length > 0) batches.push(current);\n return {\n batches,\n dropped\n };\n}\nexport { eventByteSize, partitionAiBatch };\n","import { version } from \"./version.mjs\";\nimport { PostHogCoreStateless, PostHogMetrics, PostHogPersistedProperty, getEventUuid, isBlockedUA, isPlainObject, isPostHogFetchContentTooLargeError, minimizeFlagCalledEventProperties, raceWithTimeout, resolveMetricsConfig, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { FeatureFlagError } from \"./types.mjs\";\nimport { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from \"./extensions/feature-flags/feature-flags.mjs\";\nimport error_tracking from \"./extensions/error-tracking/index.mjs\";\nimport { PostHogMemoryStorage } from \"./storage-memory.mjs\";\nimport { resolveCaptureMode } from \"./capture-v1/config.mjs\";\nimport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from \"./capture-v1/routing.mjs\";\nimport { V1CaptureSender } from \"./capture-v1/sender.mjs\";\nimport { eventByteSize, partitionAiBatch } from \"./ai-capture/batching.mjs\";\nimport { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from \"./ai-capture/routing.mjs\";\nconst MINIMUM_POLLING_INTERVAL = 100;\nconst THIRTY_SECONDS = 30000;\nconst MAX_CACHE_SIZE = 50000;\nconst WAITUNTIL_DEBOUNCE_MS = 50;\nconst WAITUNTIL_MAX_WAIT_MS = 500;\nconst DEFAULT_NODE_HOST = 'https://us.i.posthog.com';\nconst _emittedDeprecations = new Set();\nfunction emitDeprecationWarningOnce(id, message) {\n if (_emittedDeprecations.has(id)) return;\n _emittedDeprecations.add(id);\n console.warn(`[PostHog] ${message}`);\n}\nfunction _resetDeprecationWarningsForTests() {\n _emittedDeprecations.clear();\n}\nfunction normalizeApiKey(value) {\n return 'string' == typeof value ? value.trim() : '';\n}\nfunction normalizePersonalApiKey(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || void 0;\n}\nfunction normalizeHost(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || DEFAULT_NODE_HOST;\n}\nfunction normalizeUnsetPersonProperties(value) {\n const propertyNames = Array.isArray(value) ? value : [\n value\n ];\n return propertyNames.filter((propertyName)=>'string' == typeof propertyName && propertyName.trim().length > 0);\n}\nfunction buildFlagEventProperties(flagValues) {\n if (!flagValues) return {};\n const additionalProperties = {};\n for (const [feature, variant] of Object.entries(flagValues))additionalProperties[`$feature/${feature}`] = variant;\n const activeFlags = Object.keys(flagValues).filter((flag)=>false !== flagValues[flag]).sort();\n if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;\n return additionalProperties;\n}\nclass PostHogBackendClient extends PostHogCoreStateless {\n constructor(apiKey, options = {}){\n const normalizedApiKey = normalizeApiKey(apiKey);\n const normalizedOptions = {\n ...options,\n maxQueueSize: options.maxQueueSize ?? 10000,\n flushInterval: options.flushInterval ?? 5000,\n host: normalizeHost(options.host),\n personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)\n };\n super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;\n this.options = normalizedOptions;\n this.captureMode = resolveCaptureMode();\n this.enableFullAiCapture = true === normalizedOptions.enableFullAiCapture;\n this.context = this.initializeContext();\n this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;\n if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);\n if ('number' == typeof normalizedOptions.waitUntilMaxWaitMs) this.options.waitUntilMaxWaitMs = Math.max(normalizedOptions.waitUntilMaxWaitMs, 0);\n if (!this.disabled && normalizedOptions.personalApiKey) {\n if (normalizedOptions.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.');\n const shouldEnableLocalEvaluation = false !== normalizedOptions.enableLocalEvaluation;\n if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({\n pollingInterval: this.options.featureFlagsPollingInterval,\n personalApiKey: normalizedOptions.personalApiKey,\n projectApiKey: normalizedApiKey,\n timeout: normalizedOptions.requestTimeout ?? 10000,\n host: this.host,\n fetch: normalizedOptions.fetch,\n onError: (err)=>{\n this._events.emit('error', err);\n },\n onLoad: (count)=>{\n this._events.emit('localEvaluationFlagsLoaded', count);\n },\n onMinimalFlagCalledEvents: (enabled)=>{\n this._minimalFlagCalledEvents = enabled;\n },\n customHeaders: this.getCustomHeaders(),\n cacheProvider: normalizedOptions.flagDefinitionCacheProvider,\n strictLocalEvaluation: normalizedOptions.strictLocalEvaluation\n });\n }\n this.errorTracking = new error_tracking(this, normalizedOptions, this._logger);\n this.distinctIdHasSentFlagCalls = {};\n this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;\n }\n enqueue(type, message, options, explicitRoute) {\n super.enqueue(type, message, options, explicitRoute);\n this.scheduleDebouncedFlush();\n }\n async flush() {\n const flushPromise = this.flushWithPendingPromises();\n const waitUntil = this.options.waitUntil;\n if (waitUntil && !this._waitUntilCycle) try {\n waitUntil(flushPromise.catch(()=>{}));\n } catch {}\n return flushPromise;\n }\n scheduleDebouncedFlush() {\n const waitUntil = this.options.waitUntil;\n if (!waitUntil) return;\n if (this.disabled || this.optedOut) return;\n if (!this._waitUntilCycle) {\n let resolve;\n const promise = new Promise((r)=>{\n resolve = r;\n });\n try {\n waitUntil(promise);\n } catch {\n return;\n }\n this._waitUntilCycle = {\n resolve: resolve,\n startedAt: Date.now(),\n timer: void 0\n };\n }\n const elapsed = Date.now() - this._waitUntilCycle.startedAt;\n const maxWaitMs = this.options.waitUntilMaxWaitMs ?? WAITUNTIL_MAX_WAIT_MS;\n const flushNow = elapsed >= maxWaitMs;\n if (void 0 !== this._waitUntilCycle.timer) clearTimeout(this._waitUntilCycle.timer);\n if (flushNow) return void this.resolveWaitUntilFlush();\n const debounceMs = this.options.waitUntilDebounceMs ?? WAITUNTIL_DEBOUNCE_MS;\n this._waitUntilCycle.timer = safeSetTimeout(()=>{\n this.resolveWaitUntilFlush();\n }, debounceMs);\n }\n _consumeWaitUntilCycle() {\n const cycle = this._waitUntilCycle;\n if (cycle) {\n clearTimeout(cycle.timer);\n this._waitUntilCycle = void 0;\n }\n return cycle?.resolve;\n }\n async resolveWaitUntilFlush() {\n const resolve = this._consumeWaitUntilCycle();\n try {\n await this.flushWithPendingPromises();\n } catch {} finally{\n resolve?.();\n }\n }\n getPersistedProperty(key) {\n return this._memoryStorage.getProperty(key);\n }\n setPersistedProperty(key, value) {\n return this._memoryStorage.setProperty(key, value);\n }\n fetch(url, options) {\n return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);\n }\n getQueueRouteKey(message) {\n return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;\n }\n persistedQueueKeyForRoute(route) {\n if (route === AI_CAPTURE_ROUTE) return PostHogPersistedProperty.AiCaptureQueue;\n return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n const routes = 'v1' === this.captureMode ? [\n ANALYTICS_ROUTE,\n AI_ROUTE\n ] : [\n ANALYTICS_ROUTE\n ];\n if (this._aiCaptureRouteActive) routes.push(AI_CAPTURE_ROUTE);\n return routes;\n }\n getBatchEndpointPath(route) {\n return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);\n }\n async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {\n if (route === AI_CAPTURE_ROUTE) return this.sendAiCaptureBatch(batchMessages, retryOptions);\n if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);\n const v1Events = batchMessages.filter((message)=>void 0 !== message);\n await this.getV1Sender().sendV1Batch(v1Events);\n }\n async sendAiCaptureBatch(batchMessages, retryOptions) {\n const { batches, dropped } = partitionAiBatch(batchMessages);\n for (const { event, bytes } of dropped){\n const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;\n this._logger.error(message);\n this._events.emit('error', new Error(message));\n }\n for (const batch of batches)await this.sendAiSubBatch(batch, retryOptions);\n }\n async sendAiSubBatch(batch, retryOptions) {\n try {\n await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);\n } catch (err) {\n if (!isPostHogFetchContentTooLargeError(err)) throw err;\n if (1 === batch.length) {\n const [event] = batch;\n const eventName = 'string' == typeof event.event ? event.event : 'unknown';\n const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;\n this._logger.error(message);\n this._events.emit('error', new Error(message));\n return;\n }\n const mid = Math.ceil(batch.length / 2);\n await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);\n await this.sendAiSubBatch(batch.slice(mid), retryOptions);\n }\n }\n getV1Sender() {\n if (!this._v1Sender) this._v1Sender = new V1CaptureSender({\n host: this.host,\n apiKey: this.apiKey,\n libraryId: this.getLibraryId(),\n libraryVersion: this.getLibraryVersion(),\n userAgent: this.getCustomUserAgent() || void 0,\n historicalMigration: this.historicalMigration,\n compressionEnabled: !this.disableCompression,\n requestTimeoutMs: this.requestTimeout,\n maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,\n initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,\n isDebug: this.isDebug\n }, {\n fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),\n onError: (error)=>this._events.emit('error', error),\n compress: (payload)=>this.compressPayload(payload)\n });\n return this._v1Sender;\n }\n getLibraryVersion() {\n return version;\n }\n get metrics() {\n if (!this._metrics) this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);\n return this._metrics;\n }\n getCustomUserAgent() {\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`;\n }\n getCommonEventProperties() {\n const commonProperties = super.getCommonEventProperties();\n if (this.options.isServer ?? true) commonProperties.$is_server = true;\n return commonProperties;\n }\n enable() {\n return super.optIn();\n }\n disable() {\n return super.optOut();\n }\n debug(enabled = true) {\n super.debug(enabled);\n this.featureFlagsPoller?.debug(enabled);\n }\n _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {\n if ('string' == typeof props) this._logger.warn(stringArgumentWarning);\n if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);\n }\n _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {\n return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{\n const captureOptions = {\n timestamp: options.timestamp,\n disableGeoip: options.disableGeoip,\n uuid: options.uuid\n };\n const message = {\n distinctId,\n event,\n properties: {\n ...properties,\n ...this.getCommonEventProperties()\n }\n };\n return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);\n }).catch((err)=>{\n if (err) console.error(err);\n }));\n }\n _capturePreparedEvent(props, immediate) {\n return this._sendPreparedEvent('capture', props, immediate);\n }\n capture(props) {\n this._warnIfInvalidCapture(props, 'Called capture() with a string as the first argument when an object was expected.', \"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this._capturePreparedEvent(props, false);\n }\n async captureImmediate(props) {\n this._warnIfInvalidCapture(props, 'Called captureImmediate() with a string as the first argument when an object was expected.', \"Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.\");\n return this._capturePreparedEvent(props, true);\n }\n captureAi(props) {\n if (this.disabled) return;\n const uuid = getEventUuid(props.uuid, uuidv7);\n this._sendPreparedAiEvent({\n ...props,\n uuid\n }, false);\n return uuid;\n }\n async captureAiImmediate(props) {\n if (this.disabled) return;\n const uuid = getEventUuid(props.uuid, uuidv7);\n await this._sendPreparedAiEvent({\n ...props,\n uuid\n }, true);\n return uuid;\n }\n _sendPreparedAiEvent(props, immediate) {\n if ('string' == typeof props?.event && !props.event.startsWith('$ai_')) this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);\n this._aiCaptureRouteActive = true;\n return this._sendPreparedEvent('capture', props, immediate, void 0, AI_CAPTURE_ROUTE);\n }\n identify({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n await this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {\n if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;\n const eventProperties = {};\n if (Object.keys(properties).length > 0) eventProperties.$set = properties;\n if (Object.keys(propertiesOnce).length > 0) eventProperties.$set_once = propertiesOnce;\n this.capture({\n distinctId,\n event: '$set',\n properties: eventProperties\n });\n }\n unsetPersonProperties({ distinctId, properties }) {\n const propertyNames = normalizeUnsetPersonProperties(properties);\n if (0 === propertyNames.length) return;\n this.capture({\n distinctId,\n event: '$set',\n properties: {\n $unset: propertyNames\n }\n });\n }\n alias(data) {\n this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async aliasImmediate(data) {\n await this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n isLocalEvaluationReady() {\n return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;\n }\n async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {\n if (this.isLocalEvaluationReady()) return true;\n if (void 0 === this.featureFlagsPoller) return false;\n return new Promise((resolve)=>{\n const timeout = setTimeout(()=>{\n cleanup();\n resolve(false);\n }, timeoutMs);\n const cleanup = this._events.on('localEvaluationFlagsLoaded', (count)=>{\n clearTimeout(timeout);\n cleanup();\n resolve(count > 0);\n });\n });\n }\n _resolveDistinctId(distinctIdOrOptions, options) {\n if ('string' == typeof distinctIdOrOptions) return {\n distinctId: distinctIdOrOptions,\n options\n };\n return {\n distinctId: this.context?.get()?.distinctId,\n options: distinctIdOrOptions\n };\n }\n async _getFeatureFlagResult(key, distinctId, options = {}, matchValue) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true;\n if (void 0 !== this._flagOverrides && key in this._flagOverrides) {\n const overrideValue = this._flagOverrides[key];\n if (void 0 === overrideValue) return;\n const overridePayload = this._payloadOverrides?.[key];\n return {\n key,\n enabled: false !== overrideValue,\n variant: 'string' == typeof overrideValue ? overrideValue : void 0,\n payload: overridePayload\n };\n }\n const { groups, disableGeoip } = options;\n let { onlyEvaluateLocally, personProperties, groupProperties } = options;\n const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n let result;\n let flagWasLocallyEvaluated = false;\n let requestId;\n let evaluatedAt;\n let featureFlagError;\n let flagId;\n let flagVersion;\n let flagReason;\n let flagHasExperiment;\n const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;\n if (localEvaluationEnabled) {\n await this.featureFlagsPoller?.loadFeatureFlags();\n const flag = this.featureFlagsPoller?.featureFlagsByKey[key];\n if (flag) try {\n const localResult = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, evaluationContext, {\n matchValue\n });\n if (localResult) {\n flagWasLocallyEvaluated = true;\n const value = localResult.value;\n flagId = flag.id;\n flagReason = 'Evaluated locally';\n flagHasExperiment = flag.has_experiment;\n result = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payload ?? void 0\n };\n }\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${key}: ${e.message}`);\n else throw e;\n }\n }\n if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {\n const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) featureFlagError = FeatureFlagError.UNKNOWN_ERROR;\n else {\n this._minimalFlagCalledEvents = true === flagsResponse.minimalFlagCalledEvents;\n requestId = flagsResponse.requestId;\n evaluatedAt = flagsResponse.evaluatedAt;\n const errors = [];\n if (flagsResponse.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (flagsResponse.quotaLimited?.includes('feature_flags')) errors.push(FeatureFlagError.QUOTA_LIMITED);\n const flagDetail = flagsResponse.flags[key];\n if (void 0 === flagDetail) errors.push(FeatureFlagError.FLAG_MISSING);\n else {\n flagId = flagDetail.metadata?.id;\n flagVersion = flagDetail.metadata?.version;\n flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;\n flagHasExperiment = flagDetail.metadata?.has_experiment;\n let parsedPayload;\n if (flagDetail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(flagDetail.metadata.payload);\n } catch {\n parsedPayload = flagDetail.metadata.payload;\n }\n result = {\n key,\n enabled: flagDetail.enabled,\n variant: flagDetail.variant ?? void 0,\n payload: parsedPayload\n };\n }\n if (errors.length > 0) featureFlagError = errors.join(',');\n }\n }\n if (sendFeatureFlagEvents) {\n const response = void 0 === result ? void 0 : false === result.enabled ? false : result.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flagId,\n $feature_flag_version: flagVersion,\n $feature_flag_reason: flagReason,\n locally_evaluated: flagWasLocallyEvaluated,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: requestId,\n $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt\n };\n if (void 0 !== flagHasExperiment) properties.$feature_flag_has_experiment = flagHasExperiment;\n if (flagWasLocallyEvaluated && this.featureFlagsPoller) {\n const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();\n if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;\n }\n if (featureFlagError) properties.$feature_flag_error = featureFlagError;\n this._captureFlagCalledEventIfNeeded({\n distinctId,\n key,\n response,\n groups,\n disableGeoip,\n properties\n });\n }\n if (void 0 !== result && void 0 !== this._payloadOverrides && key in this._payloadOverrides) result = {\n ...result,\n payload: this._payloadOverrides[key]\n };\n return result;\n }\n async getFeatureFlag(key, distinctId, options) {\n emitDeprecationWarningOnce('getFeatureFlag', \"`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n return result.variant ?? true;\n }\n async getFeatureFlagPayload(key, distinctId, matchValue, options) {\n emitDeprecationWarningOnce('getFeatureFlagPayload', \"`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n if (void 0 !== this._payloadOverrides && key in this._payloadOverrides) return this._payloadOverrides[key];\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: false\n }, matchValue);\n if (void 0 === result) return;\n return result.payload ?? null;\n }\n async getFeatureFlagResult(key, distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) return void this._logger.warn(\"[PostHog] distinctId is required \\u2014 pass it explicitly or use withContext()\");\n return this._getFeatureFlagResult(key, resolvedDistinctId, {\n ...resolvedOptions,\n sendFeatureFlagEvents: resolvedOptions?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n }\n async getRemoteConfigPayload(flagKey) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this.options.personalApiKey) throw new Error('Personal API key is required for remote config payload decryption');\n const response = await this._requestRemoteConfigPayload(flagKey);\n if (!response) return;\n const parsed = await response.json();\n if ('string' == typeof parsed) try {\n return JSON.parse(parsed);\n } catch (e) {}\n return parsed;\n }\n async isFeatureEnabled(key, distinctId, options) {\n emitDeprecationWarningOnce('isFeatureEnabled', \"`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n const feat = result.variant ?? true;\n return !!feat || false;\n }\n async getAllFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags \\u2014 pass it explicitly or use withContext()\");\n return {};\n }\n const response = await this.getAllFlagsAndPayloads(resolvedDistinctId, resolvedOptions);\n return response.featureFlags || {};\n }\n async getAllFlagsAndPayloads(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags and payloads \\u2014 pass it explicitly or use withContext()\");\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n let featureFlags = {};\n let featureFlagPayloads = {};\n let fallbackToFlags = true;\n if (localEvaluationResult) {\n featureFlags = localEvaluationResult.response;\n featureFlagPayloads = localEvaluationResult.payloads;\n fallbackToFlags = localEvaluationResult.fallbackToFlags;\n }\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n featureFlags = {\n ...featureFlags,\n ...remoteEvaluationResult.flags || {}\n };\n featureFlagPayloads = {\n ...featureFlagPayloads,\n ...remoteEvaluationResult.payloads || {}\n };\n }\n if (void 0 !== this._flagOverrides) featureFlags = {\n ...featureFlags,\n ...this._flagOverrides\n };\n if (void 0 !== this._payloadOverrides) featureFlagPayloads = {\n ...featureFlagPayloads,\n ...this._payloadOverrides\n };\n return {\n featureFlags,\n featureFlagPayloads\n };\n }\n async evaluateFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to evaluate feature flags \\u2014 pass it explicitly or use withContext()\");\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: '',\n flags: {}\n });\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n flags: {}\n });\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const requestedFlagKeys = flagKeys ? new Set(flagKeys) : void 0;\n const records = {};\n let requestId;\n let evaluatedAt;\n let errorsWhileComputing = false;\n let quotaLimited = false;\n const localResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n const locallyEvaluatedKeys = new Set();\n if (localResult) for (const [key, value] of Object.entries(localResult.response)){\n const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payloads[key],\n id: flagDef?.id,\n version: void 0,\n reason: 'Evaluated locally',\n locallyEvaluated: true,\n hasExperiment: flagDef?.has_experiment\n };\n locallyEvaluatedKeys.add(key);\n }\n const requestedFlagMissingLocally = void 0 !== requestedFlagKeys && Array.from(requestedFlagKeys).some((key)=>this.featureFlagsPoller?.featureFlagsByKey[key] === void 0);\n const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n if (details) {\n this._minimalFlagCalledEvents = true === details.minimalFlagCalledEvents;\n requestId = details.requestId;\n evaluatedAt = details.evaluatedAt;\n errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);\n quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');\n for (const [key, detail] of Object.entries(details.flags)){\n if (locallyEvaluatedKeys.has(key)) continue;\n let parsedPayload;\n if (detail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(detail.metadata.payload);\n } catch {\n parsedPayload = detail.metadata.payload;\n }\n records[key] = {\n key,\n enabled: detail.enabled,\n variant: detail.variant,\n payload: parsedPayload,\n id: detail.metadata?.id,\n version: detail.metadata?.version,\n reason: detail.reason?.description ?? detail.reason?.code,\n locallyEvaluated: false,\n hasExperiment: detail.metadata?.has_experiment\n };\n }\n }\n }\n if (void 0 !== this._flagOverrides) for (const [key, value] of Object.entries(this._flagOverrides)){\n if (void 0 === value) {\n delete records[key];\n continue;\n }\n const existing = records[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: existing?.payload,\n id: existing?.id,\n version: existing?.version,\n reason: existing?.reason,\n locallyEvaluated: existing?.locallyEvaluated ?? false,\n hasExperiment: existing?.hasExperiment\n };\n }\n if (void 0 !== this._payloadOverrides) for (const [key, payload] of Object.entries(this._payloadOverrides)){\n const existing = records[key];\n if (existing) records[key] = {\n ...existing,\n payload\n };\n }\n if (void 0 !== requestedFlagKeys) {\n for (const key of Object.keys(records))if (!requestedFlagKeys.has(key)) delete records[key];\n }\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n groups,\n disableGeoip,\n flags: records,\n requestId,\n evaluatedAt,\n flagDefinitionsLoadedAt: this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),\n errorsWhileComputing,\n quotaLimited\n });\n }\n _shouldSendMinimalFlagCalledEvent(event, properties) {\n return '$feature_flag_called' === event && this._minimalFlagCalledEvents && false === properties.$feature_flag_has_experiment;\n }\n _captureFlagCalledEventIfNeeded(params) {\n const { distinctId, key, response, groups, disableGeoip, properties } = params;\n const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0))}` : '';\n const featureFlagReportedKey = `${key}_${response}${groupSuffix}`;\n if (distinctId in this.distinctIdHasSentFlagCalls && this.distinctIdHasSentFlagCalls[distinctId].has(featureFlagReportedKey)) return;\n if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};\n if (this.distinctIdHasSentFlagCalls[distinctId] instanceof Set) this.distinctIdHasSentFlagCalls[distinctId].add(featureFlagReportedKey);\n else this.distinctIdHasSentFlagCalls[distinctId] = new Set([\n featureFlagReportedKey\n ]);\n this.capture({\n distinctId,\n event: '$feature_flag_called',\n properties,\n groups,\n disableGeoip\n });\n }\n _getFeatureFlagEvaluationsHost() {\n if (!this._featureFlagEvaluationsHost) this._featureFlagEvaluationsHost = {\n captureFlagCalledEventIfNeeded: (params)=>this._captureFlagCalledEventIfNeeded(params),\n logWarning: (message)=>{\n if (false !== this.options.featureFlagsLogWarnings) console.warn(`[PostHog] ${message}`);\n }\n };\n return this._featureFlagEvaluationsHost;\n }\n groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n await this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n async reloadFeatureFlags() {\n await this.featureFlagsPoller?.loadFeatureFlags(true);\n }\n overrideFeatureFlags(overrides) {\n const flagArrayToRecord = (flags)=>Object.fromEntries(flags.map((f)=>[\n f,\n true\n ]));\n if (false === overrides) {\n this._flagOverrides = void 0;\n this._payloadOverrides = void 0;\n return;\n }\n if (Array.isArray(overrides)) {\n this._flagOverrides = flagArrayToRecord(overrides);\n return;\n }\n if (this._isFeatureFlagOverrideOptions(overrides)) {\n if ('flags' in overrides) {\n if (false === overrides.flags) this._flagOverrides = void 0;\n else if (Array.isArray(overrides.flags)) this._flagOverrides = flagArrayToRecord(overrides.flags);\n else if (void 0 !== overrides.flags) this._flagOverrides = {\n ...overrides.flags\n };\n }\n if ('payloads' in overrides) {\n if (false === overrides.payloads) this._payloadOverrides = void 0;\n else if (void 0 !== overrides.payloads) this._payloadOverrides = {\n ...overrides.payloads\n };\n }\n return;\n }\n this._flagOverrides = {\n ...overrides\n };\n }\n _isFeatureFlagOverrideOptions(overrides) {\n if ('object' != typeof overrides || null === overrides || Array.isArray(overrides)) return false;\n const obj = overrides;\n if ('flags' in obj) {\n const flagsValue = obj['flags'];\n if (false === flagsValue || Array.isArray(flagsValue) || 'object' == typeof flagsValue && null !== flagsValue) return true;\n }\n if ('payloads' in obj) {\n const payloadsValue = obj['payloads'];\n if (false === payloadsValue || 'object' == typeof payloadsValue && null !== payloadsValue) return true;\n }\n return false;\n }\n withContext(data, fn, options) {\n if (!this.context) return fn();\n return this.context.run(data, fn, options);\n }\n getContext() {\n return this.context?.get();\n }\n enterContext(data, options) {\n this.context?.enter(data, options);\n }\n async _shutdown(shutdownTimeoutMs) {\n const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);\n const resolve = this._consumeWaitUntilCycle();\n await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);\n this.errorTracking.shutdown();\n if (this._metrics) {\n await raceWithTimeout(this._metrics.flush().catch(()=>{}), Math.max(0, shutdownDeadlineMs - Date.now()));\n this._metrics.reset();\n }\n try {\n return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));\n } finally{\n this.distinctIdHasSentFlagCalls = {};\n resolve?.();\n }\n }\n async _requestRemoteConfigPayload(flagKey) {\n if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;\n const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;\n const options = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.options.personalApiKey}`\n }\n };\n let abortTimeout = null;\n if (this.options.requestTimeout && 'number' == typeof this.options.requestTimeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.options.requestTimeout);\n options.signal = controller.signal;\n }\n try {\n return await this.fetch(url, options);\n } catch (error) {\n this._events.emit('error', error);\n return;\n } finally{\n if (abortTimeout) clearTimeout(abortTimeout);\n }\n }\n extractPropertiesFromEvent(eventProperties, groups) {\n if (!eventProperties) return {\n personProperties: {},\n groupProperties: {}\n };\n const personProperties = {};\n const groupProperties = {};\n for (const [key, value] of Object.entries(eventProperties))if (isPlainObject(value) && groups && key in groups) {\n const groupProps = {};\n for (const [groupKey, groupValue] of Object.entries(value))groupProps[String(groupKey)] = String(groupValue);\n groupProperties[String(key)] = groupProps;\n } else personProperties[String(key)] = String(value);\n return {\n personProperties,\n groupProperties\n };\n }\n async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {\n if (this.disabled || !this.apiKey) return void this._logger.warn('The client is disabled');\n const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};\n const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};\n const flagKeys = sendFeatureFlagsOptions?.flagKeys;\n const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? this.options.strictLocalEvaluation ?? false;\n if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};\n else {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;\n }\n addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {\n const allPersonProperties = {\n ...personProperties || {}\n };\n const allGroupProperties = {};\n if (groups) for (const groupName of Object.keys(groups))allGroupProperties[groupName] = {\n $group_key: groups[groupName],\n ...groupProperties?.[groupName] || {}\n };\n return {\n allPersonProperties,\n allGroupProperties\n };\n }\n personPropertiesForLocalEvaluation(distinctId, personProperties) {\n return {\n distinct_id: distinctId,\n ...personProperties || {}\n };\n }\n createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {\n return {\n distinctId,\n groups: groups || {},\n personProperties: personProperties || {},\n groupProperties: groupProperties || {},\n evaluationCache: {}\n };\n }\n captureException(error, distinctId, additionalProperties, uuid, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this._capturePreparedEvent({\n ...msg,\n uuid,\n flags\n }, false)));\n }\n }\n async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this.captureImmediate({\n ...msg,\n flags\n })));\n }\n }\n async prepareEventMessage(props) {\n return this._prepareEventMessage(props);\n }\n async _prepareEventMessage(props, options = {}) {\n const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;\n const contextData = this.context?.get();\n const includeContextProperties = options.includeContextProperties ?? true;\n let mergedDistinctId = distinctId || contextData?.distinctId;\n const mergedProperties = includeContextProperties ? {\n ...this.props,\n ...contextData?.properties || {},\n ...properties || {}\n } : {\n ...properties || {}\n };\n if (!mergedDistinctId) {\n mergedDistinctId = uuidv7();\n mergedProperties.$process_person_profile = false;\n }\n if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;\n const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;\n const eventMessage = this._runBeforeSend({\n distinctId: mergedDistinctId,\n event,\n properties: finalProperties,\n groups,\n flags,\n sendFeatureFlags,\n timestamp,\n disableGeoip,\n uuid\n });\n if (!eventMessage) return Promise.reject(null);\n const eventProperties = await Promise.resolve().then(async ()=>{\n if (flags) {\n if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');\n return flags._getEventProperties();\n }\n if (sendFeatureFlags) {\n emitDeprecationWarningOnce('sendFeatureFlags', \"`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.\");\n const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;\n const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);\n return buildFlagEventProperties(flagValues);\n }\n return {};\n }).catch(()=>({})).then((additionalProperties)=>{\n const resolvedGroups = eventMessage.groups || groups;\n return {\n ...additionalProperties,\n ...eventMessage.properties || {},\n ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {\n $groups: resolvedGroups\n } : {}\n };\n });\n if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {\n if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {\n eventMessage.event = '$bot_pageview';\n eventProperties.$browser_type = 'bot';\n }\n }\n return {\n distinctId: eventMessage.distinctId,\n event: eventMessage.event,\n properties: eventProperties,\n options: {\n timestamp: eventMessage.timestamp,\n disableGeoip: eventMessage.disableGeoip,\n uuid: eventMessage.uuid\n }\n };\n }\n _runBeforeSend(eventMessage) {\n const beforeSend = this.options.before_send;\n if (!beforeSend) return eventMessage;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = eventMessage;\n for (const fn of fns)try {\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);\n return null;\n }\n if (!result.properties || 0 === Object.keys(result.properties).length) {\n const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;\n this._logger.warn(message);\n }\n } catch (error) {\n this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);\n return null;\n }\n return result;\n }\n}\nexport { PostHogBackendClient, _resetDeprecationWarningsForTests };\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nclass PostHogContext {\n constructor(){\n this.storage = new AsyncLocalStorage();\n }\n get() {\n return this.storage.getStore();\n }\n run(context, fn, options) {\n return this.storage.run(this.resolve(context, options), fn);\n }\n enter(context, options) {\n this.storage.enterWith(this.resolve(context, options));\n }\n resolve(context, options) {\n if (options?.fresh === true) return context;\n const current = this.get() || {};\n return {\n distinctId: context.distinctId ?? current.distinctId,\n sessionId: context.sessionId ?? current.sessionId,\n properties: {\n ...current.properties || {},\n ...context.properties || {}\n }\n };\n }\n}\nexport { PostHogContext };\n","import { gzip } from \"node:zlib\";\nimport { promisify } from \"node:util\";\nconst gzipAsync = promisify(gzip);\nasync function gzipCompress(input, isDebug = true) {\n try {\n const compressed = await gzipAsync(input);\n return new Uint8Array(compressed);\n } catch (error) {\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress };\n","import { ErrorTracking } from \"@posthog/core\";\nconst NAME = 'posthog-node';\nfunction createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [\n 'error'\n], sendExceptionsToPostHog = true } = {}) {\n return (event)=>{\n const shouldProcessLevel = '*' === severityAllowList || severityAllowList.includes(event.level);\n if (!shouldProcessLevel) return event;\n if (!event.tags) event.tags = {};\n const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];\n if (void 0 === userId) return event;\n const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';\n const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();\n event.tags['PostHog Person URL'] = personUrl;\n const exceptions = event.exception?.values || [];\n const exceptionList = exceptions.map((exception)=>({\n ...exception,\n stacktrace: exception.stacktrace ? {\n ...exception.stacktrace,\n type: 'raw',\n frames: (exception.stacktrace.frames || []).map((frame)=>({\n ...frame,\n platform: \"node:javascript\"\n }))\n } : void 0\n }));\n const properties = {\n $exception_message: exceptions[0]?.value || event.message,\n $exception_type: exceptions[0]?.type,\n $exception_level: event.level,\n $exception_list: exceptionList,\n $sentry_event_id: event.event_id,\n $sentry_exception: event.exception,\n $sentry_exception_message: exceptions[0]?.value || event.message,\n $sentry_exception_type: exceptions[0]?.type,\n $sentry_tags: event.tags\n };\n const injectedReleaseId = ErrorTracking.getInjectedReleaseId();\n if (injectedReleaseId) properties.$release_id = injectedReleaseId;\n if (organization && projectId) properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;\n if (sendExceptionsToPostHog) _posthog.capture({\n event: '$exception',\n distinctId: userId,\n properties\n });\n return event;\n };\n}\nfunction sentryIntegration(_posthog, options) {\n const processor = createEventProcessor(_posthog, options);\n return {\n name: NAME,\n processEvent (event) {\n return processor(event);\n }\n };\n}\nclass PostHogSentryIntegration {\n static #_ = this.POSTHOG_ID_TAG = 'posthog_distinct_id';\n constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog){\n this.name = NAME;\n this.name = NAME;\n this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {\n const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;\n addGlobalEventProcessor(createEventProcessor(_posthog, {\n organization,\n projectId,\n prefix,\n severityAllowList,\n sendExceptionsToPostHog: sendExceptionsToPostHog ?? true\n }));\n };\n }\n}\nexport { PostHogSentryIntegration, createEventProcessor, sentryIntegration };\n","const TRACING_HEADER_MAX_LENGTH = 1000;\nconst TRACING_HEADER_CONTROL_CHARS_REGEX = /[\\x00-\\x1f\\x7f-\\x9f]/g;\nconst POSTHOG_TRACING_HEADERS = {\n sessionId: 'x-posthog-session-id',\n distinctId: 'x-posthog-distinct-id'\n};\nfunction addProperty(properties, key, value) {\n if (null != value && '' !== value) properties[key] = value;\n}\nfunction getFirstHeaderValue(value) {\n return Array.isArray(value) ? value[0] : value;\n}\nfunction sanitizeTracingHeaderValue(value) {\n if (Array.isArray(value)) {\n for (const item of value){\n const sanitized = sanitizeTracingHeaderValue(item);\n if (void 0 !== sanitized) return sanitized;\n }\n return;\n }\n if ('string' != typeof value) return;\n const sanitized = value.replace(TRACING_HEADER_CONTROL_CHARS_REGEX, '').trim();\n if (!sanitized) return;\n return sanitized.length > TRACING_HEADER_MAX_LENGTH ? sanitized.slice(0, TRACING_HEADER_MAX_LENGTH) : sanitized;\n}\nfunction getPostHogTracingHeaderValues(headers) {\n if (!headers) return {};\n const sessionId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.sessionId]);\n const distinctId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.distinctId]);\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {}\n };\n}\nexport { POSTHOG_TRACING_HEADERS, addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues, sanitizeTracingHeaderValue };\n","import { stripUrlHash } from \"@posthog/core\";\nfunction normalizeRequestCurrentUrl(currentUrl, disableCaptureUrlHashes) {\n return disableCaptureUrlHashes ? stripUrlHash(currentUrl) : currentUrl;\n}\nfunction normalizeRequestPath(path, disableCaptureUrlHashes) {\n const pathWithoutSearch = stripUrlSearch(path);\n return disableCaptureUrlHashes ? stripUrlHash(pathWithoutSearch) : pathWithoutSearch;\n}\nfunction stripUrlSearch(url) {\n if (!url) return url;\n const searchIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n if (-1 === searchIndex || -1 !== hashIndex && hashIndex < searchIndex) return url;\n return `${url.slice(0, searchIndex)}${-1 === hashIndex ? '' : url.slice(hashIndex)}`;\n}\nexport { normalizeRequestCurrentUrl, normalizeRequestPath };\n","import error_tracking from \"./error-tracking/index.mjs\";\nimport { addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues } from \"./tracing-headers.mjs\";\nimport { normalizeRequestCurrentUrl, normalizeRequestPath } from \"./url-utils.mjs\";\nfunction getClientIp(req) {\n const forwarded = getFirstHeaderValue(req.headers['x-forwarded-for']);\n if (forwarded) {\n const ip = forwarded.split(',')[0].trim();\n if (ip) return ip;\n }\n return req.socket?.remoteAddress;\n}\nfunction buildRequestContextData(posthog, req) {\n const { sessionId, distinctId } = getPostHogTracingHeaderValues(req.headers);\n const properties = {};\n const disableCaptureUrlHashes = true === posthog.options.disable_capture_url_hashes;\n addProperty(properties, '$current_url', normalizeRequestCurrentUrl(req.originalUrl || req.url, disableCaptureUrlHashes));\n addProperty(properties, '$request_method', req.method);\n addProperty(properties, '$request_path', normalizeRequestPath(req.path, disableCaptureUrlHashes));\n addProperty(properties, '$user_agent', getFirstHeaderValue(req.headers['user-agent']));\n addProperty(properties, '$ip', getClientIp(req));\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {},\n properties\n };\n}\nfunction setupExpressRequestContext(_posthog, app) {\n app.use(posthogRequestContext(_posthog));\n}\nfunction posthogRequestContext(posthog) {\n return (req, _res, next)=>{\n posthog.withContext(buildRequestContextData(posthog, req), ()=>next());\n };\n}\nfunction setupExpressErrorHandler(_posthog, app) {\n app.use(posthogErrorHandler(_posthog));\n}\nfunction posthogErrorHandler(posthog) {\n return (error, req, res, next)=>{\n if (error_tracking.isPreviouslyCapturedError(error)) return void next(error);\n const contextData = buildRequestContextData(posthog, req);\n const syntheticException = new Error('Synthetic exception');\n const hint = {\n mechanism: {\n type: 'middleware',\n handled: false\n },\n syntheticException\n };\n const additionalProperties = {\n ...void 0 !== contextData.sessionId ? {\n $session_id: contextData.sessionId\n } : {},\n ...contextData.properties || {},\n $response_status_code: res.statusCode\n };\n posthog.addPendingPromise(error_tracking.buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, contextData.distinctId, additionalProperties).then((msg)=>posthog._capturePreparedEvent(msg, false)));\n next(error);\n };\n}\nexport { setupExpressErrorHandler, setupExpressRequestContext };\n","import { createModulerModifier } from \"../extensions/error-tracking/modifiers/module.node.mjs\";\nimport { addSourceContext } from \"../extensions/error-tracking/modifiers/context-lines.node.mjs\";\nimport { createRelativePathModifier } from \"../extensions/error-tracking/modifiers/relative-path.node.mjs\";\nimport { PostHogBackendClient } from \"../client.mjs\";\nimport { ErrorTracking } from \"@posthog/core\";\nimport { PostHogContext } from \"../extensions/context/context.mjs\";\nimport { gzipCompress } from \"../gzip.node.mjs\";\nexport * from \"../exports.mjs\";\nclass PostHog extends PostHogBackendClient {\n getLibraryId() {\n return 'posthog-node';\n }\n compressPayload(payload) {\n return gzipCompress(payload, this.isDebug);\n }\n initializeContext() {\n return new PostHogContext();\n }\n createErrorPropertiesBuilder() {\n return new ErrorTracking.ErrorPropertiesBuilder([\n new ErrorTracking.EventCoercer(),\n new ErrorTracking.ErrorCoercer(),\n new ErrorTracking.ObjectCoercer(),\n new ErrorTracking.StringCoercer(),\n new ErrorTracking.PrimitiveCoercer()\n ], ErrorTracking.createStackParser(\"node:javascript\", ErrorTracking.nodeStackLineParser), [\n createModulerModifier(),\n (frames)=>addSourceContext(frames, void 0, this._logger),\n createRelativePathModifier()\n ]);\n }\n}\nexport { PostHog };\n","type ShutdownHook = () => void | Promise<void>\n\nconst SIGNAL_SHUTDOWN_TIMEOUT_MS = 2_000\n\nconst hooks = new Set<ShutdownHook>()\nlet signalsBound = false\n\nconst runHooks = async() => {\n await Promise.all([...hooks].map(async(hook) => {\n try {\n await hook()\n } catch (error) {\n console.error(\"[rb/server] shutdown hook error\", error)\n }\n }))\n}\n\nexport const bindShutdownSignals = () => {\n if (signalsBound) return\n signalsBound = true\n\n // Handling a signal disables Node's default exit-on-signal behavior, so we\n // must re-raise it once the hooks are done; `once` keeps a second signal fatal\n const stop = (signal: NodeJS.Signals) => {\n const timeout = new Promise(resolve => setTimeout(resolve, SIGNAL_SHUTDOWN_TIMEOUT_MS).unref())\n void Promise.race([runHooks(), timeout]).finally(() => process.kill(process.pid, signal))\n }\n\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n}\n\nexport const onShutdown = (hook: ShutdownHook) => {\n hooks.add(hook)\n bindShutdownSignals()\n}\n","import type { Application } from \"express\"\nimport { PostHog, setupExpressErrorHandler } from \"posthog-node\"\n\nimport { onShutdown } from \"./shutdown\"\n\n\ntype ServerEnv = Record<string, string | undefined>\n\nlet client: PostHog | null | undefined\nlet shutdownHookBound = false\n\nexport const resolvePosthogApiKey = (env: ServerEnv) => env.RB_PUBLIC_POSTHOG_KEY\n\nexport const resolvePosthogHost = () => \"https://eu.i.posthog.com\"\n\nexport const getPosthogClient = (env: ServerEnv): PostHog | null => {\n if (client !== undefined) return client\n\n const apiKey = resolvePosthogApiKey(env)\n\n if (!apiKey) {\n client = null\n return client\n }\n\n client = new PostHog(apiKey, {\n host: resolvePosthogHost(),\n enableExceptionAutocapture: true,\n flushAt: 1,\n flushInterval: 1_000,\n })\n\n return client\n}\n\nexport const bindExpressErrorHandler = (app: Application, posthog: PostHog | null) => {\n if (!posthog) return\n setupExpressErrorHandler(posthog, app)\n}\n\nexport const captureServerException = (\n error: unknown,\n posthog?: PostHog | null,\n properties?: Record<string, unknown>,\n) => {\n const clientToUse = posthog ?? client ?? null\n\n if (!clientToUse || typeof clientToUse.captureException !== \"function\") return\n\n clientToUse.captureException(error as any, \"server\", properties)\n}\n\nconst shutdown = async() => {\n if (!client) return\n try {\n await client.shutdown()\n } catch (err) {\n console.error(\"posthog shutdown error\", err)\n }\n}\n\nexport const ensurePosthogShutdown = () => {\n if (shutdownHookBound || !client) return\n shutdownHookBound = true\n\n onShutdown(shutdown)\n process.on(\"beforeExit\", shutdown)\n}\n","import type {Application} from \"express\"\nimport httpProxy from \"http-proxy-3\"\n\n\nconst POSTHOG_INGEST_TARGET = \"https://eu.i.posthog.com\"\n\nconst getStatusCode = (errorCode: unknown): number => {\n if (typeof errorCode === \"string\" && /HPE_INVALID/.test(errorCode)) {\n return 502\n }\n\n switch (errorCode) {\n case \"ECONNRESET\":\n case \"ENOTFOUND\":\n case \"ECONNREFUSED\":\n case \"ETIMEDOUT\":\n return 504\n default:\n return 500\n }\n}\n\nconst proxy = httpProxy.createProxyServer({\n changeOrigin: true,\n})\n\nproxy.on(\"error\", (err: any, req: any, res: any) => {\n console.error(`Proxy error: ${err?.message ?? String(err)}`)\n\n if (!res || typeof res.writeHead !== \"function\") return\n if (res.headersSent) return\n\n const statusCode = getStatusCode(err?.code)\n res.writeHead(statusCode)\n\n const host = req?.headers?.host ?? \"\"\n const url = req?.url ?? \"\"\n res.end(`Error occurred while trying to proxy: ${host}${url}`)\n})\n\nexport const metricsIngestProxyMiddleware = (app: Application) => {\n app.use(\"/ingest\", (req, res) => {\n if (!req.url) {\n req.url = \"/\"\n }\n\n proxy.web(req, res, {target: POSTHOG_INGEST_TARGET})\n })\n}\n","import { MongoClient } from \"mongodb\"\n\n\ntype ServerEnv = { [key: string]: string | undefined }\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nlet hasWarnedNoReplicationEnabled = false\n\nexport const checkInitReplicaSet = async (serverEnv: ServerEnv): Promise<void> => {\n const port = serverEnv.DB_PORT?.trim()\n if (!port) return\n\n const host = (serverEnv.DB_HOST ?? \"localhost\").trim()\n\n const replSetName = \"rs0\"\n const memberHost = `${host}:${port}`\n const maxAttempts = 10\n const serverSelectionTimeoutMs = 2000\n\n const uri = `mongodb://${host}:${port}/?directConnection=true`\n\n const waitForReplicaSetReady = async (admin: any): Promise<void> => {\n const maxWaitAttempts = 10\n\n for (let attempt = 1; attempt <= maxWaitAttempts; attempt++) {\n try {\n const status: any = await admin.command({ replSetGetStatus: 1 })\n const state = Number(status?.myState ?? 0)\n if (status?.ok && (state === 1 || state === 2)) return\n } catch {\n // ignore\n }\n\n await sleep(250 * attempt)\n }\n }\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n let client: MongoClient | null = null\n\n try {\n client = new MongoClient(uri, {\n family: 4,\n serverSelectionTimeoutMS: serverSelectionTimeoutMs,\n connectTimeoutMS: serverSelectionTimeoutMs,\n })\n\n await client.connect()\n\n const admin = client.db(\"admin\").admin()\n await admin.command({ ping: 1 })\n\n try {\n await admin.command({ replSetGetStatus: 1 })\n return\n } catch (error) {\n const codeName = (error as any)?.codeName\n\n if (codeName === \"NotYetInitialized\") {\n try {\n const res: any = await admin.command({\n replSetInitiate: {\n _id: replSetName,\n members: [{ _id: 0, host: memberHost }],\n },\n })\n\n if (res?.ok) {\n console.warn(`[rb/server] MongoDB replica set '${replSetName}' initiated (${memberHost}).`)\n } else {\n console.warn(`[rb/server] MongoDB replica set initiation returned ok=${String(res?.ok)}.`)\n }\n } catch (initError) {\n const initCodeName = (initError as any)?.codeName\n if (initCodeName !== \"AlreadyInitialized\") {\n const message = initError instanceof Error ? initError.message : String(initError)\n console.warn(`[rb/server] MongoDB replica set initiation failed: ${message}`)\n if (initCodeName === \"InvalidReplicaSetConfig\") {\n console.warn(\n \"[rb/server] Hint: the replica set member host must match the mongod address/port. \" +\n `If MongoDB runs in Docker with port mapping, ensure the container listens on ${port} (e.g. mongod --port ${port}) instead of the default 27017.`,\n )\n }\n }\n }\n\n await waitForReplicaSetReady(admin)\n return\n }\n\n if (codeName === \"NoReplicationEnabled\") {\n if (!hasWarnedNoReplicationEnabled) {\n hasWarnedNoReplicationEnabled = true\n console.warn(\n `[rb/server] MongoDB is not started with --replSet ${replSetName} (replication disabled). ` +\n \"Change streams require a replica set; start mongod with --replSet.\",\n )\n }\n return\n }\n\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set check failed: ${message}`)\n return\n }\n } catch (error) {\n if (attempt === maxAttempts) {\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set auto-init skipped (unable to connect to ${host}:${port}): ${message}`)\n return\n }\n\n await sleep(250 * attempt)\n } finally {\n try {\n await client?.close()\n } catch {\n // ignore\n }\n }\n }\n}\n","import fs from \"node:fs\"\nimport fsPromises from \"node:fs/promises\"\nimport inspector from \"node:inspector\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport type { Application } from \"express\"\n\n\ntype CoverageRoots = {\n projectRoot: string\n workspaceRoot: string\n}\n\ntype NormalizedPath = {\n absolutePath: string\n relativePath: string\n}\n\ntype CoverageRun = {\n roots: CoverageRoots\n session: inspector.Session\n sourceCache: Map<string, Promise<string>>\n startedAt: number\n}\n\ntype ServerCoverageTarget = \"api\" | \"worker\" | \"ssr\"\n\nconst VITE_FS_PREFIX = \"/@fs/\"\n\nlet activeRun: CoverageRun | null = null\n\nconst post = async <T = any>(\n session: inspector.Session,\n method: string,\n params?: Record<string, unknown>,\n): Promise<T> => {\n return await new Promise<T>((resolve, reject) => {\n session.post(method, params, (error, result) => {\n if (error) {\n reject(error)\n return\n }\n resolve(result as T)\n })\n })\n}\n\nconst describeError = (error: unknown): string => {\n return error instanceof Error ? error.message : String(error)\n}\n\nconst findWorkspaceRoot = (projectRoot: string): string => {\n let dir = path.resolve(projectRoot)\n\n while (true) {\n const pkgPath = path.join(dir, \"package.json\")\n try {\n if (fs.existsSync(pkgPath)) {\n const parsed = JSON.parse(fs.readFileSync(pkgPath, \"utf8\")) as { workspaces?: unknown }\n if (parsed && typeof parsed === \"object\" && parsed.workspaces) {\n return dir\n }\n }\n } catch {\n //\n }\n\n const parent = path.dirname(dir)\n if (parent === dir) {\n return path.resolve(projectRoot)\n }\n dir = parent\n }\n}\n\nconst stripQuery = (url: string): string => {\n const queryIndex = url.indexOf(\"?\")\n const hashIndex = url.indexOf(\"#\")\n\n const endIndex = Math.min(\n queryIndex === -1 ? Number.POSITIVE_INFINITY : queryIndex,\n hashIndex === -1 ? Number.POSITIVE_INFINITY : hashIndex,\n )\n\n if (!Number.isFinite(endIndex)) {\n return url\n }\n\n return url.slice(0, endIndex)\n}\n\nconst resolveAbsoluteFromUrl = (rawUrl: string, roots: CoverageRoots): string | null => {\n const cleaned = stripQuery(rawUrl)\n\n try {\n if (cleaned.startsWith(\"file://\")) {\n return path.normalize(fileURLToPath(cleaned))\n }\n } catch {\n //\n }\n\n let pathname = cleaned\n\n try {\n const parsed = new URL(cleaned)\n pathname = parsed.pathname\n } catch {\n //\n }\n\n const decoded = decodeURIComponent(pathname)\n\n if (decoded.startsWith(VITE_FS_PREFIX)) {\n return path.normalize(decoded.slice(VITE_FS_PREFIX.length))\n }\n\n if (!path.isAbsolute(decoded)) {\n return null\n }\n\n if (fs.existsSync(decoded)) {\n return path.normalize(decoded)\n }\n\n const projectRoot = path.resolve(roots.projectRoot)\n const workspaceRoot = path.resolve(roots.workspaceRoot)\n\n if (decoded.startsWith(projectRoot + path.sep) || decoded.startsWith(workspaceRoot + path.sep)) {\n return path.normalize(decoded)\n }\n\n return path.resolve(projectRoot, `.${decoded}`)\n}\n\nconst normalizeScriptUrl = async (rawUrl: string, roots: CoverageRoots): Promise<NormalizedPath | null> => {\n if (!rawUrl || rawUrl.startsWith(\"node:\")) {\n return null\n }\n\n const absolute = resolveAbsoluteFromUrl(rawUrl, roots)\n if (!absolute) {\n return null\n }\n\n let realPath = absolute\n try {\n realPath = await fsPromises.realpath(absolute)\n } catch {\n //\n }\n\n const normalized = path.normalize(realPath)\n\n if (normalized.includes(`${path.sep}node_modules${path.sep}`)) {\n return null\n }\n\n const workspaceRoot = path.resolve(roots.workspaceRoot)\n const projectRoot = path.resolve(roots.projectRoot)\n\n if (normalized.startsWith(workspaceRoot + path.sep) || normalized === workspaceRoot) {\n return {\n absolutePath: normalized,\n relativePath: path.relative(workspaceRoot, normalized),\n }\n }\n\n if (normalized.startsWith(projectRoot + path.sep) || normalized === projectRoot) {\n return {\n absolutePath: normalized,\n relativePath: path.relative(projectRoot, normalized),\n }\n }\n\n return null\n}\n\nconst fetchScriptSource = async (session: inspector.Session, scriptId: string): Promise<string> => {\n try {\n const response = await post<{ scriptSource?: unknown }>(session, \"Debugger.getScriptSource\", { scriptId })\n return typeof response?.scriptSource === \"string\" ? response.scriptSource : \"\"\n } catch {\n return \"\"\n }\n}\n\nconst resolveScriptSource = async (\n session: inspector.Session,\n cache: Map<string, Promise<string>>,\n scriptId: string,\n): Promise<string> => {\n const cached = cache.get(scriptId)\n if (cached) {\n return await cached\n }\n\n const promise = fetchScriptSource(session, scriptId)\n cache.set(scriptId, promise)\n return await promise\n}\n\nconst shutdownSession = async (session: inspector.Session): Promise<void> => {\n await Promise.allSettled([\n post(session, \"Profiler.stopPreciseCoverage\").catch(() => undefined),\n post(session, \"Profiler.disable\").catch(() => undefined),\n post(session, \"Debugger.disable\").catch(() => undefined),\n ])\n\n try {\n session.disconnect()\n } catch {\n //\n }\n}\n\nconst toPosixPath = (input: string): string => input.split(path.sep).join(\"/\")\n\nconst isSubpath = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate)\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))\n}\n\nconst classifyServerTarget = (absolutePath: string, projectRoot: string): ServerCoverageTarget => {\n if (!isSubpath(absolutePath, projectRoot)) {\n return \"ssr\"\n }\n\n const relative = toPosixPath(path.relative(projectRoot, absolutePath))\n\n if (relative.startsWith(\"src/api/\") || relative.includes(\"/src/api/\")) {\n return \"api\"\n }\n if (relative.startsWith(\"src/worker/\") || relative.includes(\"/src/worker/\")) {\n return \"worker\"\n }\n if (relative.startsWith(\"src/server/\") || relative.includes(\"/src/server/\")) {\n return \"ssr\"\n }\n\n if (relative.startsWith(\"build/dist/api/\") || relative.includes(\"/build/dist/api/\")) {\n return \"api\"\n }\n if (relative.startsWith(\"build/dist/worker/\") || relative.includes(\"/build/dist/worker/\")) {\n return \"worker\"\n }\n if (relative.startsWith(\"build/dist/ssr/\") || relative.includes(\"/build/dist/ssr/\")) {\n return \"ssr\"\n }\n\n return \"ssr\"\n}\n\nexport function registerDevCoverageEndpoints(app: Application): void {\n app.post(\"/api/dev/coverage/start\", async (_req, res) => {\n if (process.env.NODE_ENV === \"production\") {\n res.status(404).json({ error: \"Not Found\" })\n return\n }\n\n if (activeRun) {\n res.json({ ok: true, status: \"already_started\", startedAt: activeRun.startedAt })\n return\n }\n\n const roots = {\n projectRoot: path.resolve(process.cwd()),\n workspaceRoot: findWorkspaceRoot(process.cwd()),\n }\n\n const session = new inspector.Session()\n session.connect()\n\n try {\n await post(session, \"Debugger.enable\")\n await post(session, \"Profiler.enable\")\n await post(session, \"Profiler.startPreciseCoverage\", { callCount: false, detailed: true })\n\n activeRun = {\n roots,\n session,\n sourceCache: new Map(),\n startedAt: Date.now(),\n }\n\n res.json({ ok: true, status: \"started\", startedAt: activeRun.startedAt })\n } catch (error) {\n await shutdownSession(session)\n activeRun = null\n res.status(500).json({ ok: false, error: describeError(error) })\n }\n })\n\n app.post(\"/api/dev/coverage/stop\", async (req, res) => {\n if (process.env.NODE_ENV === \"production\") {\n res.status(404).json({ error: \"Not Found\" })\n return\n }\n\n const run = activeRun\n if (!run) {\n res.status(409).json({ ok: false, error: \"coverage_not_started\" })\n return\n }\n\n activeRun = null\n\n const outputRoot = path.join(run.roots.projectRoot, \"build\", \"coverage\", \"server\")\n const outputFiles: Record<ServerCoverageTarget, string> = {\n api: path.join(outputRoot, \"api\", \"v8-coverage.json\"),\n worker: path.join(outputRoot, \"worker\", \"v8-coverage.json\"),\n ssr: path.join(outputRoot, \"ssr\", \"v8-coverage.json\"),\n }\n\n try {\n const taken = await post<{ result?: unknown }>(run.session, \"Profiler.takePreciseCoverage\")\n const result = Array.isArray(taken?.result) ? (taken.result as any[]) : []\n\n const scriptsByTarget: Record<ServerCoverageTarget, any[]> = {\n api: [],\n worker: [],\n ssr: [],\n }\n\n for (const entry of result) {\n const scriptId = typeof entry?.scriptId === \"string\" ? entry.scriptId : null\n const url = typeof entry?.url === \"string\" ? entry.url : null\n if (!scriptId || !url) {\n continue\n }\n\n const normalized = await normalizeScriptUrl(url, run.roots)\n if (!normalized) {\n continue\n }\n\n const source = await resolveScriptSource(run.session, run.sourceCache, scriptId)\n\n const script = {\n absolutePath: normalized.absolutePath,\n relativePath: normalized.relativePath,\n source,\n functions: Array.isArray(entry?.functions) ? entry.functions : [],\n url,\n }\n\n const target = classifyServerTarget(script.absolutePath, run.roots.projectRoot)\n scriptsByTarget[target].push(script)\n }\n\n await Promise.all(\n (Object.keys(outputFiles) as ServerCoverageTarget[]).map(async (target) => {\n const outputFile = outputFiles[target]\n const payload = {\n testId: `node-${target}`,\n scripts: scriptsByTarget[target],\n }\n\n await fsPromises.mkdir(path.dirname(outputFile), { recursive: true })\n await fsPromises.writeFile(outputFile, JSON.stringify(payload, null, 2), \"utf8\")\n }),\n )\n\n res.json({\n ok: true,\n status: \"stopped\",\n outputFiles,\n scriptCount: {\n api: scriptsByTarget.api.length,\n worker: scriptsByTarget.worker.length,\n ssr: scriptsByTarget.ssr.length,\n },\n })\n } catch (error) {\n res.status(500).json({ ok: false, error: describeError(error) })\n } finally {\n await shutdownSession(run.session)\n }\n })\n}\n","import path from \"node:path\"\n\nimport type {Request, RequestHandler} from \"express\"\n\n\nconst vitePathPrefixes = [\n \"/@fs\",\n \"/@id\",\n \"/@react-refresh\",\n \"/@vite\",\n \"/node_modules\",\n \"/src\",\n]\n\nconst assetDestinations = new Set([\n \"audio\",\n \"audioworklet\",\n \"embed\",\n \"font\",\n \"image\",\n \"manifest\",\n \"object\",\n \"paintworklet\",\n \"script\",\n \"serviceworker\",\n \"sharedworker\",\n \"style\",\n \"track\",\n \"video\",\n \"worker\",\n \"xslt\",\n])\n\nconst isPathAtOrBelow = (requestPath: string, prefix: string): boolean => {\n return requestPath === prefix || requestPath.startsWith(`${prefix}/`)\n}\n\nconst getHeader = (req: Request, name: string): string => {\n const value = req.headers[name]\n return Array.isArray(value) ? value[0] ?? \"\" : value ?? \"\"\n}\n\nexport const isDevelopmentAssetRequest = (req: Request): boolean => {\n if (req.method !== \"GET\" && req.method !== \"HEAD\") return false\n if (isPathAtOrBelow(req.path, \"/api\")) return false\n if (getHeader(req, \"accept\") === \"text/x-vite-ping\") return true\n if (vitePathPrefixes.some((prefix) => isPathAtOrBelow(req.path, prefix))) return true\n\n const destination = getHeader(req, \"sec-fetch-dest\").toLowerCase()\n return assetDestinations.has(destination) && path.posix.extname(req.path) !== \"\"\n}\n\nexport const developmentSessionMiddleware = (sessionMiddleware: RequestHandler): RequestHandler => {\n return (req, res, next) => {\n if (isDevelopmentAssetRequest(req)) {\n next()\n return\n }\n\n sessionMiddleware(req, res, next)\n }\n}\n","import type { Application, RequestHandler } from \"express\"\n\n\nexport const RPCBASE_SERVICE_WORKER_PATH = \"/rpcbase-service-worker.js\"\nexport const RPCBASE_SERVICE_WORKER_MESSAGE_SOURCE = \"@rpcbase/service-worker\"\n\nexport const rpcbaseServiceWorkerSource = `\nconst MESSAGE_SOURCE = ${JSON.stringify(RPCBASE_SERVICE_WORKER_MESSAGE_SOURCE)}\n\nconst getSameOriginWindowClients = async () => {\n const windowClients = await self.clients.matchAll({ type: \"window\", includeUncontrolled: true })\n return windowClients.filter((client) => {\n try {\n return new URL(client.url).origin === self.location.origin\n } catch {\n return false\n }\n })\n}\n\nconst normalizeMessage = (value) => {\n if (!value || typeof value !== \"object\") return null\n if (value.source !== MESSAGE_SOURCE || typeof value.type !== \"string\" || !value.type.trim()) return null\n return {\n source: MESSAGE_SOURCE,\n type: value.type.trim(),\n ...(value.payload === undefined ? {} : { payload: value.payload }),\n }\n}\n\nconst broadcastMessage = async (message, excludedClientId) => {\n const windowClients = await getSameOriginWindowClients()\n for (const client of windowClients) {\n if (client.id === excludedClientId) continue\n client.postMessage(message)\n }\n}\n\nconst showNotificationFromMessage = async (message) => {\n if (message.type !== \"notifications.show\") return false\n const payload = message.payload\n if (!payload || typeof payload !== \"object\") return false\n const title = typeof payload.title === \"string\" ? payload.title.trim() : \"\"\n if (!title) return false\n const options = payload.options && typeof payload.options === \"object\" ? payload.options : undefined\n await self.registration.showNotification(title, options)\n return true\n}\n\nconst getTargetUrl = (link, linkMode, client) => {\n try {\n if (linkMode === \"merge_current_search\" && client) {\n const currentUrl = new URL(client.url)\n const actionUrl = new URL(link, currentUrl)\n actionUrl.searchParams.forEach((value, key) => currentUrl.searchParams.set(key, value))\n if (actionUrl.hash) currentUrl.hash = actionUrl.hash\n return currentUrl.origin === self.location.origin ? currentUrl.href : null\n }\n\n const targetUrl = new URL(link, self.location.origin)\n return targetUrl.origin === self.location.origin ? targetUrl.href : null\n } catch {\n return null\n }\n}\n\nself.addEventListener(\"install\", (event) => event.waitUntil(self.skipWaiting()))\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n await self.clients.claim()\n await broadcastMessage({ source: MESSAGE_SOURCE, type: \"worker.ready\" })\n })())\n})\n\nself.addEventListener(\"message\", (event) => {\n const message = normalizeMessage(event.data)\n if (!message) return\n\n event.waitUntil((async () => {\n if (await showNotificationFromMessage(message)) return\n const sourceClientId = event.source && typeof event.source.id === \"string\"\n ? event.source.id\n : undefined\n await broadcastMessage(message, sourceClientId)\n })())\n})\n\nself.addEventListener(\"push\", (event) => {\n let message = null\n try {\n message = normalizeMessage(event.data ? event.data.json() : null)\n } catch {\n return\n }\n if (!message || message.type !== \"notifications.show\") return\n event.waitUntil(showNotificationFromMessage(message))\n})\n\nself.addEventListener(\"notificationclick\", (event) => {\n event.notification.close()\n event.waitUntil((async () => {\n const data = event.notification.data && typeof event.notification.data === \"object\"\n ? event.notification.data\n : {}\n const link = typeof data.link === \"string\" ? data.link.trim() : \"\"\n const linkMode = data.linkMode === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\"\n const windowClients = await getSameOriginWindowClients()\n const client = windowClients.find((candidate) => candidate.focused) ?? windowClients[0]\n\n if (!link) {\n if (client) await client.focus()\n return\n }\n\n const targetUrl = getTargetUrl(link, linkMode, client)\n if (!targetUrl) return\n\n if (client) {\n try {\n const navigatedClient = await client.navigate(targetUrl)\n await (navigatedClient ?? client).focus()\n return\n } catch {\n await self.clients.openWindow(targetUrl)\n return\n }\n }\n\n await self.clients.openWindow(targetUrl)\n })())\n})\n`.trimStart()\n\nexport const rpcbaseServiceWorkerRequestHandler: RequestHandler = (_req, res) => {\n res.set({\n \"Cache-Control\": \"no-cache\",\n \"Content-Type\": \"application/javascript; charset=utf-8\",\n \"Service-Worker-Allowed\": \"/\",\n \"X-Content-Type-Options\": \"nosniff\",\n })\n res.send(rpcbaseServiceWorkerSource)\n}\n\nexport const registerRpcbaseServiceWorkerRoute = (app: Application): void => {\n app.get(RPCBASE_SERVICE_WORKER_PATH, rpcbaseServiceWorkerRequestHandler)\n}\n","import type { Application, RequestHandler } from \"express\"\nimport session, { type CookieOptions, type SessionOptions } from \"express-session\"\nimport {RedisStore} from \"connect-redis\"\nimport MongoStore from \"connect-mongo\"\nimport {createClient} from \"redis\"\nimport requestIp from \"request-ip\"\nimport { MongoClient } from \"mongodb\"\nimport env from \"@rpcbase/env\"\nimport { initApiClient } from \"@rpcbase/client\"\nimport { getMongoDirectConnection, getMongoUrl } from \"@rpcbase/db/mongo\"\n\nimport { bindExpressErrorHandler, ensurePosthogShutdown, getPosthogClient } from \"./posthog\"\nimport { bindShutdownSignals } from \"./shutdown\"\nimport { getDerivedKey } from \"./getDerivedKey\"\nimport { metricsIngestProxyMiddleware } from \"./metricsIngestProxyMiddleware\"\nimport { checkInitReplicaSet } from \"./checkInitReplicaSet\"\nimport { registerDevCoverageEndpoints } from \"./dev/coverage\"\nimport { syncAuthenticatedSessionMiddleware } from \"./syncAuthenticatedSession\"\nimport { developmentSessionMiddleware } from \"./developmentSessionMiddleware\"\nimport { registerRpcbaseServiceWorkerRoute } from \"./serviceWorker\"\n\n// dotenv setup, merge process env with vite process.env file\nprocess.env = {\n ...env,\n ...__rb_env__,\n ...process.env,\n} as NodeJS.ProcessEnv\n\n\nconst isProduction = process.env.NODE_ENV === \"production\"\n\ntype ServerEnv = { [key: string]: string | undefined }\n\nexport type InitServerOptions = {\n sessions?: boolean\n}\n\nexport type InitServerResult = {\n sessionMiddleware: RequestHandler | undefined\n}\n\ntype InitServerWithSessionsOptions = InitServerOptions & {\n sessions?: true\n}\n\ntype InitServerWithoutSessionsOptions = InitServerOptions & {\n sessions: false\n}\n\nconst SESSION_MAX_AGE_S = 3600 * 24 * 60 // 60 days\n\nconst getMongoSessionUrl = (serverEnv: ServerEnv) => {\n const appName = serverEnv.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME (required to build MongoDB session store DB name)\")\n }\n\n return getMongoUrl(serverEnv, { dbName: `${appName}-sessions` })\n}\n\nconst createMongoSessionStore = async (serverEnv: ServerEnv) => {\n const mongoUrl = getMongoSessionUrl(serverEnv)\n\n console.log(\"Using MongoDB session store\")\n\n const client = await MongoClient.connect(mongoUrl, {\n family: 4,\n serverSelectionTimeoutMS: 2000,\n connectTimeoutMS: 2000,\n directConnection: getMongoDirectConnection(serverEnv),\n })\n\n const store = MongoStore.create({\n client,\n collectionName: \"sessions\",\n ttl: SESSION_MAX_AGE_S,\n })\n\n await (store as any).collectionP\n return store\n}\n\nconst createRedisSessionStore = async (redisUrl: string) => {\n const reconnectStrategy = (retries: number) => {\n console.log(\"redis_client::rb/server reconnectStrategy::retrying with arg\", retries)\n if (retries < 5) {\n console.log(\"retry count:\", retries, \"retrying in 1s\")\n return 4000\n } else {\n return new Error(\"max retries expired\")\n }\n }\n\n const redisClient = createClient({\n url: redisUrl,\n socket: {\n reconnectStrategy,\n connectTimeout: 10000,\n keepAlive: false,\n },\n })\n\n redisClient.on(\"ready\", () => {\n console.log(\"session-storage::redis_client connected\")\n })\n\n redisClient.on(\"error\", (error) => {\n console.log(\"session-storage::redis_client ERROR\", error)\n })\n\n console.log(\"Using Redis session store\")\n\n await redisClient.connect()\n\n return new RedisStore({\n client: redisClient,\n ttl: SESSION_MAX_AGE_S,\n })\n}\n\n\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerWithoutSessionsOptions,\n): Promise<{ sessionMiddleware: undefined }>\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options?: InitServerWithSessionsOptions,\n): Promise<{ sessionMiddleware: RequestHandler }>\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerOptions,\n): Promise<InitServerResult>\nexport async function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerOptions = {},\n): Promise<InitServerResult> {\n bindShutdownSignals()\n\n await initApiClient({app})\n\n const replicaSetInitPromise = checkInitReplicaSet(serverEnv).catch((error) => {\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set auto-init error: ${message}`)\n })\n\n app.disable(\"x-powered-by\")\n\n app.set(\"trust proxy\", true)\n\n app.use(requestIp.mw())\n\n // redirect www to non-www middleware\n app.use((req, res, next) => {\n if (req.headers.host?.startsWith(\"www.\")) {\n const newHost = req.headers.host.replace(\"www.\", \"\")\n return res.redirect(301, `${req.protocol}://${newHost}${req.originalUrl}`)\n }\n next()\n })\n\n registerRpcbaseServiceWorkerRoute(app)\n metricsIngestProxyMiddleware(app)\n\n const posthog = getPosthogClient(serverEnv)\n\n if (posthog) {\n app.locals.posthog = posthog\n bindExpressErrorHandler(app, posthog)\n ensurePosthogShutdown()\n }\n\n if (!isProduction) {\n registerDevCoverageEndpoints(app)\n }\n\n if (options.sessions === false) {\n return {\n sessionMiddleware: undefined,\n }\n }\n\n if (!serverEnv.MASTER_KEY) {\n throw new Error(\"MASTER_KEY must be defined to derive the session secret\")\n }\n if (!serverEnv.RB_PROXY_SHARED_SECRET?.trim()) {\n throw new Error(\"RB_PROXY_SHARED_SECRET must be defined\")\n }\n\n const sessionSecret = getDerivedKey(serverEnv.MASTER_KEY, \"express_session_key\")\n\n const redisUrl = serverEnv.REDIS_URL?.trim()\n\n let store: SessionOptions[\"store\"]\n if (redisUrl) {\n store = await createRedisSessionStore(redisUrl)\n } else {\n await replicaSetInitPromise\n store = await createMongoSessionStore(serverEnv)\n }\n\n const cookie: CookieOptions = {\n maxAge: SESSION_MAX_AGE_S * 1000\n }\n\n if (isProduction) {\n cookie.secure = \"auto\"\n // cookie.domain = \"\"\n }\n\n const sessionConfig: SessionOptions = {\n name: `${serverEnv.APP_NAME?.trim()}-session`,\n store,\n proxy: true,\n resave: false,\n saveUninitialized: false,\n secret: sessionSecret,\n cookie,\n }\n\n const sessionMiddleware = session(sessionConfig)\n\n app.use(isProduction ? sessionMiddleware : developmentSessionMiddleware(sessionMiddleware))\n app.use(syncAuthenticatedSessionMiddleware)\n\n return {\n sessionMiddleware\n }\n}\n","import { scrypt } from \"crypto\"\n\n\nexport async function hashPassword(password: string, salt: string): Promise<Buffer> {\n const keyLength = 64 // Length of the derived key\n const options = {\n N: 8192, // CPU/memory cost parameter\n r: 8, // Block size\n p: 1 // Parallelization factor\n }\n\n // Return a Promise-wrapped scrypt call\n const derivedKey = await new Promise<Buffer>((resolve, reject) => {\n scrypt(password, salt, keyLength, options, (err, derivedKey) => {\n if (err) {\n reject(err)\n } else {\n resolve(derivedKey)\n }\n })\n })\n\n return derivedKey\n}\n","import crypto from \"crypto\"\n\n\nconst PRODUCTION_SCRYPT_PARAMS = {\n N: 8192,\n r: 8,\n p: 4,\n keylen: 64,\n saltBytes: 16,\n maxmemBytes: 256 * 1024 * 1024,\n}\n\nconst DEVELOPMENT_SCRYPT_PARAMS = {\n N: 1024,\n r: 8,\n p: 1,\n keylen: 64,\n saltBytes: 16,\n maxmemBytes: 256 * 1024 * 1024,\n}\n\nconst MAX_SCRYPT_MAXMEM_BYTES = 1024 * 1024 * 1024\nconst MAX_SCRYPT_N = 1_048_576\nconst MAX_SCRYPT_R = 64\nconst MAX_SCRYPT_P = 16\nconst MAX_SCRYPT_KEYLEN = 128\nconst MAX_SCRYPT_SALT_BYTES = 64\n\nexport type HashPasswordForStorageOptions = Partial<{\n N: number\n r: number\n p: number\n keylen: number\n saltBytes: number\n maxmemBytes: number\n}>\n\ntype ScryptParams = {\n N: number\n r: number\n p: number\n keylen: number\n saltBytes: number\n maxmemBytes: number\n}\n\nconst parseEnvInt = (value: unknown): number | undefined => {\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n const parsed = Number(trimmed)\n if (!Number.isSafeInteger(parsed)) return undefined\n return parsed\n}\n\nconst isPowerOfTwo = (value: number) => (value & (value - 1)) === 0\n\nconst estimateScryptMemoryBytes = ({ N, r, p }: Pick<ScryptParams, \"N\" | \"r\" | \"p\">) => {\n return 128 * r * (N + p)\n}\n\nconst isProductionRuntime = () => {\n return process.env.NODE_ENV === \"production\" || globalThis.__rb_env__?.MODE === \"production\"\n}\n\nconst getDefaultScryptParams = (): ScryptParams => {\n return isProductionRuntime() ? PRODUCTION_SCRYPT_PARAMS : DEVELOPMENT_SCRYPT_PARAMS\n}\n\nconst validateScryptParams = (params: ScryptParams): { ok: true } | { ok: false, error: string } => {\n const { N, r, p, keylen, saltBytes, maxmemBytes } = params\n\n if (!Number.isSafeInteger(N) || N < 2 || N > MAX_SCRYPT_N || !isPowerOfTwo(N)) {\n return { ok: false, error: \"invalid_scrypt_N\" }\n }\n\n if (!Number.isSafeInteger(r) || r < 1 || r > MAX_SCRYPT_R) {\n return { ok: false, error: \"invalid_scrypt_r\" }\n }\n\n if (!Number.isSafeInteger(p) || p < 1 || p > MAX_SCRYPT_P) {\n return { ok: false, error: \"invalid_scrypt_p\" }\n }\n\n if (!Number.isSafeInteger(keylen) || keylen < 16 || keylen > MAX_SCRYPT_KEYLEN) {\n return { ok: false, error: \"invalid_scrypt_keylen\" }\n }\n\n if (!Number.isSafeInteger(saltBytes) || saltBytes < 8 || saltBytes > MAX_SCRYPT_SALT_BYTES) {\n return { ok: false, error: \"invalid_scrypt_salt_bytes\" }\n }\n\n if (!Number.isSafeInteger(maxmemBytes) || maxmemBytes < 16 * 1024 * 1024 || maxmemBytes > MAX_SCRYPT_MAXMEM_BYTES) {\n return { ok: false, error: \"invalid_scrypt_maxmem\" }\n }\n\n const estimatedMem = estimateScryptMemoryBytes({ N, r, p })\n if (estimatedMem > maxmemBytes) {\n return { ok: false, error: \"scrypt_params_exceed_maxmem\" }\n }\n\n return { ok: true }\n}\n\nconst getCurrentMaxmemBytes = (opts?: HashPasswordForStorageOptions): number => {\n const envMaxmemBytes = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_MAXMEM_BYTES)\n const maxmemBytes = opts?.maxmemBytes ?? envMaxmemBytes ?? getDefaultScryptParams().maxmemBytes\n\n if (\n !Number.isSafeInteger(maxmemBytes)\n || maxmemBytes < 16 * 1024 * 1024\n || maxmemBytes > MAX_SCRYPT_MAXMEM_BYTES\n ) {\n throw new Error(\"invalid_scrypt_maxmem\")\n }\n\n return maxmemBytes\n}\n\nconst getCurrentScryptParams = (opts?: HashPasswordForStorageOptions): ScryptParams => {\n const envN = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_N)\n const envR = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_R)\n const envP = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_P)\n const envKeylen = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_KEYLEN)\n const envSaltBytes = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_SALT_BYTES)\n const defaults = getDefaultScryptParams()\n\n const params: ScryptParams = {\n N: opts?.N ?? envN ?? defaults.N,\n r: opts?.r ?? envR ?? defaults.r,\n p: opts?.p ?? envP ?? defaults.p,\n keylen: opts?.keylen ?? envKeylen ?? defaults.keylen,\n saltBytes: opts?.saltBytes ?? envSaltBytes ?? defaults.saltBytes,\n maxmemBytes: getCurrentMaxmemBytes(opts),\n }\n\n const validated = validateScryptParams(params)\n if (!validated.ok) {\n throw new Error(validated.error)\n }\n\n return params\n}\n\nconst scryptAsync = async (\n password: string,\n salt: Buffer,\n params: Pick<ScryptParams, \"N\" | \"r\" | \"p\" | \"keylen\" | \"maxmemBytes\">,\n): Promise<Buffer> => {\n const { N, r, p, keylen, maxmemBytes } = params\n\n return await new Promise<Buffer>((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, { N, r, p, maxmem: maxmemBytes }, (err, derivedKey) => {\n if (err) {\n reject(err)\n return\n }\n resolve(derivedKey)\n })\n })\n}\n\nconst base64Regex = /^[A-Za-z0-9+/]+={0,2}$/\n\nconst parseB64 = (value: string): Buffer | null => {\n if (!value) return null\n if (!base64Regex.test(value)) return null\n if (value.length % 4 !== 0) return null\n\n const buf = Buffer.from(value, \"base64\")\n if (buf.length === 0) return null\n if (buf.toString(\"base64\") !== value) return null\n return buf\n}\n\ntype ParsedStoredScryptHash = {\n N: number\n r: number\n p: number\n keylen: number\n salt: Buffer\n dk: Buffer\n}\n\nconst MAX_STORED_PASSWORD_LENGTH = 1024\nconst MAX_STORED_PASSWORD_SECTION_LENGTH = 256\n\nconst parseStoredScryptHash = (stored: string): ParsedStoredScryptHash | null => {\n if (stored.length > MAX_STORED_PASSWORD_LENGTH) return null\n\n const parts = stored.split(\"$\")\n if (parts.length !== 5) return null\n if (parts[0] !== \"\" || parts[1] !== \"scrypt\") return null\n\n const paramsStr = parts[2]\n const saltB64 = parts[3]\n const dkB64 = parts[4]\n\n if (paramsStr.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n if (saltB64.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n if (dkB64.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n\n const kvPairs = paramsStr.split(\",\").filter(Boolean)\n if (kvPairs.length === 0) return null\n\n const params = new Map<string, number>()\n for (const pair of kvPairs) {\n const idx = pair.indexOf(\"=\")\n if (idx <= 0 || idx === pair.length - 1) return null\n const key = pair.slice(0, idx)\n const valueRaw = pair.slice(idx + 1)\n if (!/^[a-zA-Z0-9]+$/.test(key)) return null\n if (params.has(key)) return null\n const value = Number(valueRaw)\n if (!Number.isSafeInteger(value)) return null\n params.set(key, value)\n }\n\n const N = params.get(\"N\")\n const r = params.get(\"r\")\n const p = params.get(\"p\")\n const keylen = params.get(\"keylen\")\n\n if (N === undefined || r === undefined || p === undefined || keylen === undefined) return null\n if (params.size !== 4) return null\n\n const salt = parseB64(saltB64)\n const dk = parseB64(dkB64)\n if (!salt || !dk) return null\n\n if (dk.length !== keylen) return null\n if (salt.length < 8 || salt.length > MAX_SCRYPT_SALT_BYTES) return null\n if (dk.length < 16 || dk.length > MAX_SCRYPT_KEYLEN) return null\n\n const currentMaxmemBytes = getCurrentMaxmemBytes()\n const validated = validateScryptParams({\n N,\n r,\n p,\n keylen,\n saltBytes: salt.length,\n maxmemBytes: currentMaxmemBytes,\n })\n if (!validated.ok) return null\n\n return { N, r, p, keylen, salt, dk }\n}\n\nexport async function hashPasswordForStorage(password: string, opts?: HashPasswordForStorageOptions): Promise<string> {\n const { N, r, p, keylen, saltBytes, maxmemBytes } = getCurrentScryptParams(opts)\n\n const salt = crypto.randomBytes(saltBytes)\n const dk = await scryptAsync(password, salt, { N, r, p, keylen, maxmemBytes })\n\n const saltB64 = salt.toString(\"base64\")\n const dkB64 = dk.toString(\"base64\")\n\n return `$scrypt$N=${N},r=${r},p=${p},keylen=${keylen}$${saltB64}$${dkB64}`\n}\n\nexport async function verifyPasswordFromStorage(password: string, stored: string): Promise<boolean> {\n const parsed = parseStoredScryptHash(stored)\n if (!parsed) return false\n\n const { N, r, p, keylen, salt, dk } = parsed\n const maxmemBytes = getCurrentMaxmemBytes()\n\n let derivedKey: Buffer\n try {\n derivedKey = await scryptAsync(password, salt, { N, r, p, keylen, maxmemBytes })\n } catch {\n return false\n }\n\n if (derivedKey.length !== dk.length) return false\n\n return crypto.timingSafeEqual(dk, derivedKey)\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Request as ExpressRequest, Response as ExpressResponse } from \"express\"\nimport {\n StaticHandlerContext,\n matchRoutes,\n createPath,\n Location,\n parsePath,\n To,\n} from \"@rpcbase/router\"\n\n\nfunction createKey() {\n return Math.random().toString(36).substring(2, 10)\n}\n\nfunction createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string,\n): Readonly<Location> {\n const location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n }\n return location\n}\n\nfunction getShortCircuitMatches(routes: any[]): {\n matches: any[];\n route: any;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n const route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: \"__shim-error-route__\",\n }\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n }\n}\n\nconst NOT_FOUND_STATUS = 404\nconst LOADER_TIMEOUT_MS = 10_000\nconst IMMUTABLE_LAZY_ROUTE_KEYS = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n])\n\nconst getErrorStatus = (error: any): number | undefined => {\n if (!error) return undefined\n\n const candidate = error?.reason ?? error\n\n if (typeof candidate?.status === \"number\") return candidate.status\n if (typeof candidate?.statusCode === \"number\") return candidate.statusCode\n if (typeof candidate?.response?.status === \"number\") return candidate.response.status\n\n return undefined\n}\n\nconst isResponseLike = (value: unknown): value is Response => {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as any).status === \"number\" &&\n (value as any).headers &&\n typeof (value as any).headers.get === \"function\",\n )\n}\n\nconst isRedirectResponse = (value: unknown): value is Response => {\n if (!isResponseLike(value)) return false\n return (\n value.status >= 300 &&\n value.status < 400 &&\n Boolean(value.headers.get(\"Location\"))\n )\n}\n\nconst getRouteHandleStatusCode = (route: any): number | undefined => {\n if (!route) return undefined\n const handle = route.handle\n if (!handle) return undefined\n\n const candidate = handle.statusCode ?? handle.status ?? handle.httpStatus\n if (typeof candidate === \"number\") return candidate\n return undefined\n}\n\nconst isNotFoundFallbackRoute = (route: any): boolean => {\n if (!route) return false\n if (route.path !== \"*\") return false\n if (route.loader) return false\n if (route.action) return false\n if (route.children?.length) return false\n return true\n}\n\nexport type RouterContextWithRedirect = StaticHandlerContext & {\n redirectResponse?: Response\n redirectRouteId?: string | null\n redirectRoutePath?: string | null\n}\n\nexport async function applyRouteLoaders(\n req: ExpressRequest,\n res: ExpressResponse,\n dataRoutes: any[],\n): Promise<RouterContextWithRedirect> {\n\n const baseUrl = `${req.protocol}://${req.get(\"host\")}`\n const url = new URL(req.originalUrl, baseUrl)\n\n const method = req.method\n const location = createLocation(\"\", createPath(url), null, \"default\")\n\n const baseContext = {\n basename: \"\",\n location,\n loaderHeaders: {},\n actionHeaders: {},\n }\n\n const resolveLazyRoute = async (route: any) => {\n if (!route || typeof route !== \"object\") return\n\n const lazy = route.lazy\n if (typeof lazy !== \"function\") return\n\n const lazyModule = await lazy()\n if (!lazyModule || typeof lazyModule !== \"object\") {\n route.lazy = undefined\n return\n }\n\n for (const [key, value] of Object.entries(lazyModule as Record<string, unknown>)) {\n if (IMMUTABLE_LAZY_ROUTE_KEYS.has(key)) continue\n if (route[key] !== undefined) continue\n route[key] = value\n }\n\n route.lazy = undefined\n }\n\n // Match routes to the current location\n const matches = matchRoutes(dataRoutes, location)\n\n // Handle 404 (no matches)\n if (!matches || matches.length === 0) {\n const error = {\n status: 404,\n statusText: \"Not Found\",\n internal: true,\n data: {\n message: `No route matches URL: ${req.originalUrl}`,\n },\n }\n const { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes)\n\n return {\n ...baseContext,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: { [route.id]: error },\n statusCode: 404,\n }\n }\n\n // Skip if anything but GET\n if (method !== \"GET\") {\n return {\n ...baseContext,\n matches,\n loaderData: {},\n actionData: null,\n errors: null,\n statusCode: 200,\n }\n }\n\n const runLoaderWithTimeout = async (route: any, params: any) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n const err: any = new Error(`Loader timeout after ${LOADER_TIMEOUT_MS}ms`)\n err.status = 504\n console.error(\"[rpcbase timeout][server loader]\", {\n routeId: route.id,\n ms: LOADER_TIMEOUT_MS,\n url: req.originalUrl,\n })\n reject({id: route.id, path: route.path, reason: err})\n }, LOADER_TIMEOUT_MS)\n })\n\n const loaderPromise = (async () => {\n try {\n await resolveLazyRoute(route)\n if (!route.loader) return null\n\n const data = await route.loader({\n params,\n ctx: {req, res},\n })\n return {id: route.id, path: route.path, data}\n } catch (error) {\n throw {id: route.id, path: route.path, reason: error}\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n }\n })()\n\n return Promise.race([loaderPromise, timeoutPromise])\n }\n\n // Collect loader data and errors\n const loaderPromisesResults = await Promise.allSettled(\n matches.map((match) => runLoaderWithTimeout(match.route, match.params)),\n )\n\n const loaderData: Record<string, any> = {}\n // TODO: add i18n error handling\n let errors: Record<string, any> | null = null\n let hasNotFoundError = false\n let hasNonNotFoundError = false\n\n let redirectResponse: Response | null = null\n let redirectRouteId: string | null = null\n let redirectRoutePath: string | null = null\n\n for (const result of loaderPromisesResults) {\n if (result.status === \"fulfilled\") {\n if (result.value) {\n if (isRedirectResponse(result.value.data)) {\n redirectResponse = result.value.data\n redirectRouteId = result.value.id\n redirectRoutePath = result.value.path ?? null\n } else {\n loaderData[result.value.id] = result.value.data\n }\n }\n } else if (result.status === \"rejected\") {\n const id = (result as any).reason?.id\n if (!id) {\n throw new Error(\n `missing route ID in error: ${(result as any).reason}`,\n )\n }\n\n const reasonCandidate =\n (result as any).reason?.reason ?? (result as any).reason\n if (isRedirectResponse(reasonCandidate)) {\n redirectResponse = reasonCandidate\n redirectRouteId = id\n redirectRoutePath = (result as any).reason?.path ?? null\n continue\n }\n if (!errors) {\n errors = {}\n }\n const status = getErrorStatus((result as any).reason)\n if (status === NOT_FOUND_STATUS) {\n hasNotFoundError = true\n } else {\n hasNonNotFoundError = true\n }\n errors[id] = (result as any).reason\n }\n }\n\n if (redirectResponse) {\n return {\n ...baseContext,\n matches,\n loaderData,\n actionData: null,\n errors: null,\n statusCode: redirectResponse.status,\n redirectResponse,\n redirectRouteId,\n redirectRoutePath,\n }\n }\n\n let statusCode = 200\n if (errors) {\n if (hasNonNotFoundError) {\n statusCode = 500\n } else if (hasNotFoundError) {\n statusCode = NOT_FOUND_STATUS\n } else {\n statusCode = 500\n }\n }\n\n if (!errors && statusCode === 200) {\n const leafRoute = matches.at(-1)?.route\n\n const handleStatusCode = getRouteHandleStatusCode(leafRoute)\n if (typeof handleStatusCode === \"number\") {\n statusCode = handleStatusCode\n } else if (isNotFoundFallbackRoute(leafRoute)) {\n statusCode = NOT_FOUND_STATUS\n }\n }\n\n return {\n ...baseContext,\n matches,\n loaderData,\n actionData: null,\n errors,\n statusCode,\n }\n}\n","import type { Request } from \"express\"\nimport {\n STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY,\n type RtsSsrCountRegistration,\n type RtsSsrHydrationCountData,\n type RtsSsrHydrationQueryData,\n type RtsSsrQueryRegistration,\n type RtsSsrRuntime,\n type StaticRpcbaseRtsHydrationData,\n} from \"@rpcbase/client\"\n\nimport {\n buildRtsAbilityFromRequest,\n isRtsRequestAuthorized,\n normalizeRtsQueryOptions,\n resolveRtsRequestTenantId,\n runRtsCount,\n runRtsQuery,\n} from \"./queryExecutor\"\nimport { RTS_QUERY_WINDOW_MAX_COUNT } from \"./queryWindow\"\n\n\nconst DEFAULT_MAX_QUERIES = 32\nconst DEFAULT_MAX_DOCS_PER_QUERY = 500\nconst DEFAULT_MAX_SERIALIZED_BYTES = 200 * 1024\n\nconst makeRegistrationKey = (modelName: string, queryKey: string): string => `${modelName}.${queryKey}`\n\nconst hasSessionUser = (req: Request): boolean => {\n const id = (req.session?.user as { id?: unknown } | undefined)?.id\n return typeof id === \"string\" && id.trim().length > 0\n}\n\nconst escapeForInlineScript = (value: string): string => {\n return value\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nconst toSerializedHydrationPayload = (\n payload: StaticRpcbaseRtsHydrationData,\n): StaticRpcbaseRtsHydrationData | null => {\n try {\n return JSON.parse(JSON.stringify(payload)) as StaticRpcbaseRtsHydrationData\n } catch {\n return null\n }\n}\n\nexport type RtsSsrCollector = {\n runtime: RtsSsrRuntime\n hasRegistrations: () => boolean\n resolve: () => Promise<StaticRpcbaseRtsHydrationData | null>\n}\n\nexport const createRtsSsrCollector = (\n req: Request,\n opts?: {\n maxQueries?: number\n maxDocsPerQuery?: number\n maxSerializedBytes?: number\n },\n): RtsSsrCollector => {\n const maxQueries = typeof opts?.maxQueries === \"number\" && opts.maxQueries > 0\n ? Math.floor(opts.maxQueries)\n : DEFAULT_MAX_QUERIES\n const maxDocsPerQuery = typeof opts?.maxDocsPerQuery === \"number\" && opts.maxDocsPerQuery > 0\n ? Math.floor(opts.maxDocsPerQuery)\n : DEFAULT_MAX_DOCS_PER_QUERY\n const maxSerializedBytes = typeof opts?.maxSerializedBytes === \"number\" && opts.maxSerializedBytes > 0\n ? Math.floor(opts.maxSerializedBytes)\n : DEFAULT_MAX_SERIALIZED_BYTES\n\n const registrations = new Map<string, RtsSsrQueryRegistration>()\n const countRegistrations = new Map<string, RtsSsrCountRegistration>()\n const resolved = new Map<string, unknown[]>()\n const resolvedPageInfo = new Map<string, RtsSsrHydrationQueryData[\"pageInfo\"]>()\n const resolvedTotalCount = new Map<string, RtsSsrHydrationQueryData[\"totalCount\"]>()\n const resolvedCounts = new Map<string, RtsSsrHydrationCountData[\"count\"]>()\n\n const runtime: RtsSsrRuntime = {\n registerQuery(query: RtsSsrQueryRegistration) {\n const modelName = typeof query.modelName === \"string\" ? query.modelName.trim() : \"\"\n const queryKey = typeof query.queryKey === \"string\" ? query.queryKey.trim() : \"\"\n if (!modelName || !queryKey) return\n\n const key = makeRegistrationKey(modelName, queryKey)\n if (registrations.has(key)) return\n if (registrations.size + countRegistrations.size >= maxQueries) return\n\n registrations.set(key, {\n modelName: modelName as RtsSsrQueryRegistration[\"modelName\"],\n queryKey,\n query: query.query ?? {},\n options: query.options ?? {},\n })\n },\n registerCount(query: RtsSsrCountRegistration) {\n const modelName = typeof query.modelName === \"string\" ? query.modelName.trim() : \"\"\n const queryKey = typeof query.queryKey === \"string\" ? query.queryKey.trim() : \"\"\n if (!modelName || !queryKey) return\n\n const key = makeRegistrationKey(modelName, queryKey)\n if (countRegistrations.has(key)) return\n if (registrations.size + countRegistrations.size >= maxQueries) return\n\n countRegistrations.set(key, {\n modelName: modelName as RtsSsrCountRegistration[\"modelName\"],\n queryKey,\n query: query.query ?? {},\n options: query.options ?? {},\n })\n },\n getQueryData(modelName: string, queryKey: string) {\n return resolved.get(makeRegistrationKey(modelName, queryKey))\n },\n getQueryPageInfo(modelName: string, queryKey: string) {\n return resolvedPageInfo.get(makeRegistrationKey(modelName, queryKey))\n },\n getQueryTotalCount(modelName: string, queryKey: string) {\n return resolvedTotalCount.get(makeRegistrationKey(modelName, queryKey))\n },\n getCount(modelName: string, queryKey: string) {\n return resolvedCounts.get(makeRegistrationKey(modelName, queryKey))\n },\n }\n\n const resolve = async (): Promise<StaticRpcbaseRtsHydrationData | null> => {\n if (!registrations.size && !countRegistrations.size) return null\n\n const tenantId = resolveRtsRequestTenantId(req)\n if (!tenantId) return null\n\n if (hasSessionUser(req) && !isRtsRequestAuthorized(req, tenantId)) {\n return null\n }\n\n const { ability, userId } = await buildRtsAbilityFromRequest(req, tenantId)\n const queryEntries: RtsSsrHydrationQueryData[] = []\n const countEntries: RtsSsrHydrationCountData[] = []\n\n for (const registration of registrations.values()) {\n const options = normalizeRtsQueryOptions(registration.options)\n\n try {\n const result = await runRtsQuery({\n tenantId,\n ability,\n modelName: registration.modelName,\n query: registration.query,\n options,\n ...(options.pagination\n ? {\n paginationMaxLimit: RTS_QUERY_WINDOW_MAX_COUNT,\n includePaginationCursors: false,\n }\n : {}),\n })\n\n const boundedData = maxDocsPerQuery > 0 ? result.data.slice(0, maxDocsPerQuery) : result.data\n queryEntries.push({\n modelName: registration.modelName,\n queryKey: registration.queryKey,\n data: boundedData,\n ...(result.pageInfo ? { pageInfo: result.pageInfo } : {}),\n ...(typeof result.totalCount === \"number\" ? { totalCount: result.totalCount } : {}),\n })\n } catch {\n continue\n }\n }\n\n for (const registration of countRegistrations.values()) {\n try {\n const count = await runRtsCount({\n tenantId,\n ability,\n modelName: registration.modelName,\n query: registration.query,\n })\n\n countEntries.push({\n modelName: registration.modelName,\n queryKey: registration.queryKey,\n count,\n })\n } catch {\n continue\n }\n }\n\n if (!queryEntries.length && !countEntries.length) return null\n\n const payload: StaticRpcbaseRtsHydrationData = {\n v: 1,\n tenantId,\n uid: userId,\n queries: [],\n counts: [],\n }\n\n for (const entry of queryEntries) {\n payload.queries.push(entry)\n const bytes = Buffer.byteLength(JSON.stringify(payload), \"utf8\")\n if (bytes > maxSerializedBytes) {\n payload.queries.pop()\n break\n }\n }\n\n for (const entry of countEntries) {\n payload.counts.push(entry)\n const bytes = Buffer.byteLength(JSON.stringify(payload), \"utf8\")\n if (bytes > maxSerializedBytes) {\n payload.counts.pop()\n break\n }\n }\n\n const serializedPayload = toSerializedHydrationPayload(payload)\n if (!serializedPayload || (!serializedPayload.queries.length && !serializedPayload.counts.length)) return null\n\n resolved.clear()\n resolvedPageInfo.clear()\n resolvedTotalCount.clear()\n resolvedCounts.clear()\n for (const entry of serializedPayload.queries) {\n resolved.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.data)\n resolvedPageInfo.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.pageInfo)\n resolvedTotalCount.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.totalCount)\n }\n for (const entry of serializedPayload.counts) {\n resolvedCounts.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.count)\n }\n\n return serializedPayload\n }\n\n const hasRegistrations = (): boolean => registrations.size > 0 || countRegistrations.size > 0\n\n return { runtime, hasRegistrations, resolve }\n}\n\nexport const renderRtsHydrationScript = (\n data: StaticRpcbaseRtsHydrationData | null | undefined,\n): string => {\n if (!data) return \"\"\n const serialized = escapeForInlineScript(JSON.stringify(data))\n return `<script>window.${STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY}=${serialized};</script>`\n}\n","import { Writable } from \"node:stream\"\n\nimport * as express from \"express\"\nimport { ReactNode, StrictMode } from \"react\"\nimport { renderToPipeableStream } from \"react-dom/server\"\nimport {\n createStaticRouter,\n StaticRouterProvider,\n StaticHandler,\n} from \"@rpcbase/router\"\nimport {\n RtsSsrRuntimeProvider,\n type RtsSsrRuntime,\n type StaticRpcbaseRtsHydrationData,\n} from \"@rpcbase/client\"\n\n\nimport { applyRouteLoaders } from \"./applyRouteLoaders\"\nimport { createRtsSsrCollector } from \"./rts/ssrHydration\"\nimport { resolveRtsRequestTenantId } from \"./rts/queryExecutor\"\n\n\nconst RTS_SSR_PREPASS_TIMEOUT_MS = 4000\nconst SSR_IDENTIFIER_PREFIX = \"rb-\"\n\nexport const runRtsPrepass = async (element: ReactNode): Promise<boolean> => {\n return await new Promise<boolean>((resolve) => {\n let isDone = false\n let timeoutId: ReturnType<typeof setTimeout> | null = null\n\n const finish = (ok: boolean) => {\n if (isDone) return\n isDone = true\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n resolve(ok)\n }\n\n const sink = new Writable({\n write(_chunk, _encoding, callback) {\n callback()\n },\n })\n\n sink.on(\"finish\", () => {\n finish(true)\n })\n sink.on(\"error\", () => {\n finish(false)\n })\n\n const { pipe, abort } = renderToPipeableStream(element, {\n identifierPrefix: SSR_IDENTIFIER_PREFIX,\n onAllReady() {\n if (isDone) return\n pipe(sink)\n },\n onShellError() {\n finish(false)\n },\n onError() {\n //\n },\n })\n\n timeoutId = setTimeout(() => {\n finish(false)\n abort()\n }, RTS_SSR_PREPASS_TIMEOUT_MS)\n })\n}\n\n\n// https://api.reactrouter.com/v7/functions/react_router.StaticRouter.html\nexport async function renderSSR(\n req: express.Request,\n res: express.Response,\n dataRoutes: StaticHandler[\"dataRoutes\"],\n): Promise<{\n element: ReactNode | null\n isMatched: boolean\n statusCode: number\n rtsHydrationData?: StaticRpcbaseRtsHydrationData | null\n redirectResponse?: Response\n redirectRouteId?: string | null\n redirectRoutePath?: string | null\n}> {\n\n const routerContext = await applyRouteLoaders(req, res, dataRoutes)\n const isMatched = routerContext.matches.length > 0\n\n if (routerContext.redirectResponse) {\n return {\n element: null,\n isMatched,\n statusCode:\n routerContext.statusCode ?? routerContext.redirectResponse.status ?? 302,\n redirectResponse: routerContext.redirectResponse,\n redirectRouteId: routerContext.redirectRouteId,\n redirectRoutePath: routerContext.redirectRoutePath,\n rtsHydrationData: null,\n }\n }\n\n if (routerContext.errors) {\n if (routerContext.statusCode === 404) {\n if (req.method === \"GET\" || req.method === \"HEAD\") {\n console.warn(`SSR 404 ${req.method} ${req.originalUrl}`)\n } else {\n console.warn(`SSR 404 ${req.method} ${req.originalUrl}`, {\n errors: routerContext.errors,\n })\n }\n } else {\n const matchesSummary = routerContext.matches?.map((m) => ({\n routeId: m.route.id,\n routePath: m.route.path,\n pathname: m.pathname,\n pathnameBase: m.pathnameBase,\n }))\n console.error(\n `SSR ${routerContext.statusCode || 500} ${req.method} ${req.originalUrl}`,\n {\n errors: routerContext.errors,\n matches: matchesSummary,\n },\n )\n\n const errorEntries = Object.entries(routerContext.errors || {})\n const firstErrorEntry: any = errorEntries[0]?.[1]\n const firstReason = firstErrorEntry?.reason ?? firstErrorEntry\n if (errorEntries.length === 1 && firstReason instanceof Error) {\n ;(firstReason as any).details = routerContext.errors\n throw firstReason\n }\n\n const extra = firstErrorEntry?.id\n ? ` (route ${firstErrorEntry.id}${firstErrorEntry?.path ? ` ${firstErrorEntry.path}` : \"\"})`\n : \"\"\n const error = new Error(`SSR loader error${extra}`)\n ;(error as any).details = routerContext.errors\n throw error\n }\n }\n\n const buildElement = (runtime: RtsSsrRuntime | null) => {\n const router = createStaticRouter(dataRoutes, routerContext)\n const app = (\n <StaticRouterProvider\n router={router}\n context={routerContext}\n // TODO: setup CSP and use correct nonce\n // nonce=\"the-nonce\"\n />\n )\n\n return (\n <StrictMode>\n {runtime ? (\n <RtsSsrRuntimeProvider value={runtime}>\n {app}\n </RtsSsrRuntimeProvider>\n ) : app}\n </StrictMode>\n )\n }\n\n const tenantId = resolveRtsRequestTenantId(req)\n let rtsHydrationData: StaticRpcbaseRtsHydrationData | null = null\n let runtime: RtsSsrRuntime | null = null\n\n if (tenantId) {\n const collector = createRtsSsrCollector(req)\n // RTS hooks are synchronous and cannot await during render. We do a first\n // discovery pass to collect registrations, resolve them async, then render\n // again so the final SSR markup includes RTS data.\n const prepassOk = await runRtsPrepass(buildElement(collector.runtime))\n if (prepassOk && collector.hasRegistrations()) {\n rtsHydrationData = await collector.resolve()\n }\n runtime = collector.runtime\n }\n\n const element = buildElement(runtime)\n\n return {\n element,\n isMatched,\n statusCode: routerContext.statusCode ?? (routerContext.errors ? 500 : 200),\n rtsHydrationData,\n }\n}\n","const LEGACY_APP_HTML_PLACEHOLDER = \"<!--app-html-->\"\nconst TEMPLATE_ELEMENT_PATTERN = /<template\\b((?:\"[^\"]*\"|'[^']*'|[^'\">])*)>([\\s\\S]*?)<\\/template\\s*>/gi\nconst RPCBASE_OUTLET_ATTRIBUTE_PATTERN = /(?:^|\\s)data-rpcbase-outlet\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))(?=\\s|$)/gi\n\n\nexport type HtmlOutlets = {\n head?: string\n htmlAttributes?: {\n lang?: string\n dir?: \"ltr\" | \"rtl\" | \"auto\"\n }\n}\n\nexport type CompiledHtmlTemplate = {\n isLegacy: boolean\n render: (outlets?: HtmlOutlets) => {\n htmlStart: string\n htmlEnd: string\n }\n}\n\ntype OutletMatch = {\n name: string\n start: number\n end: number\n content: string\n}\n\ntype HtmlTagMatch = {\n start: number\n end: number\n}\n\nconst HTML_DIRECTIONS = new Set([\"ltr\", \"rtl\", \"auto\"])\nconst RAW_TEXT_ELEMENTS = new Set([\"script\", \"style\", \"textarea\", \"title\"])\n\nconst findTagEnd = (template: string, start: number) => {\n let quote: \"\\\"\" | \"'\" | null = null\n\n for (let index = start; index < template.length; index += 1) {\n const character = template[index]\n\n if (quote) {\n if (character === quote) quote = null\n continue\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character\n } else if (character === \">\") {\n return index + 1\n }\n }\n\n return template.length\n}\n\nconst findHtmlStartTags = (template: string): HtmlTagMatch[] => {\n const tags: HtmlTagMatch[] = []\n const lowerTemplate = template.toLowerCase()\n let index = 0\n\n while (index < template.length) {\n const start = template.indexOf(\"<\", index)\n if (start === -1) break\n\n if (template.startsWith(\"<!--\", start)) {\n const commentEnd = template.indexOf(\"-->\", start + 4)\n index = commentEnd === -1 ? template.length : commentEnd + 3\n continue\n }\n\n const firstCharacter = template[start + 1]\n if (firstCharacter === \"!\" || firstCharacter === \"?\" || firstCharacter === \"/\") {\n index = findTagEnd(template, start + 2)\n continue\n }\n\n const nameMatch = /^[A-Za-z][A-Za-z0-9:-]*/.exec(template.slice(start + 1))\n if (!nameMatch) {\n index = start + 1\n continue\n }\n\n const name = nameMatch[0].toLowerCase()\n const end = findTagEnd(template, start + 1 + nameMatch[0].length)\n\n if (name === \"html\") {\n tags.push({ start, end })\n }\n\n if (RAW_TEXT_ELEMENTS.has(name) && !template.slice(start, end).trimEnd().endsWith(\"/>\")) {\n const closingTagStart = lowerTemplate.indexOf(`</${name}`, end)\n index = closingTagStart === -1\n ? template.length\n : findTagEnd(template, closingTagStart + name.length + 2)\n } else {\n index = end\n }\n }\n\n return tags\n}\n\nconst escapeHtmlAttribute = (value: string) => value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"\\\"\", \"&quot;\")\n .replaceAll(\"'\", \"&#39;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n\nconst setHtmlTagAttributes = (\n tag: string,\n attributes: NonNullable<HtmlOutlets[\"htmlAttributes\"]>,\n) => {\n const values = new Map<string, string>()\n\n if (attributes.lang !== undefined) {\n if (typeof attributes.lang !== \"string\") {\n throw new Error(\"HTML attribute \\\"lang\\\" must be a string\")\n }\n values.set(\"lang\", attributes.lang)\n }\n\n if (attributes.dir !== undefined) {\n if (!HTML_DIRECTIONS.has(attributes.dir)) {\n throw new Error(\"HTML attribute \\\"dir\\\" must be one of \\\"ltr\\\", \\\"rtl\\\", or \\\"auto\\\"\")\n }\n values.set(\"dir\", attributes.dir)\n }\n\n if (values.size === 0) return tag\n\n const replacements: Array<{ start: number, end: number, value: string }> = []\n const replacedAttributes = new Set<string>()\n let index = 5\n\n while (index < tag.length - 1) {\n const whitespaceStart = index\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n if (tag[index] === \"/\" || tag[index] === \">\" || index >= tag.length - 1) break\n\n const attributeStart = index\n while (index < tag.length && !/[\\s=/>]/.test(tag[index])) index += 1\n const attributeName = tag.slice(attributeStart, index).toLowerCase()\n const attributeNameEnd = index\n\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n if (tag[index] === \"=\") {\n index += 1\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n\n const quote = tag[index]\n if (quote === \"\\\"\" || quote === \"'\") {\n index += 1\n while (index < tag.length && tag[index] !== quote) index += 1\n if (tag[index] === quote) index += 1\n } else {\n while (index < tag.length && !/[\\s>]/.test(tag[index])) index += 1\n }\n } else {\n index = attributeNameEnd\n }\n\n if (!values.has(attributeName)) continue\n\n replacements.push({\n start: replacedAttributes.has(attributeName) ? whitespaceStart : attributeStart,\n end: index,\n value: replacedAttributes.has(attributeName)\n ? \"\"\n : `${attributeName}=\"${escapeHtmlAttribute(values.get(attributeName)!)}\"`,\n })\n replacedAttributes.add(attributeName)\n }\n\n let renderedTag = tag\n for (const replacement of replacements.reverse()) {\n renderedTag = `${renderedTag.slice(0, replacement.start)}${replacement.value}${renderedTag.slice(replacement.end)}`\n }\n\n const missingAttributes = [...values]\n .filter(([name]) => !replacedAttributes.has(name))\n .map(([name, value]) => `${name}=\"${escapeHtmlAttribute(value)}\"`)\n\n if (missingAttributes.length === 0) return renderedTag\n\n return renderedTag.replace(/\\s*\\/?>$/, (ending) => {\n const suffix = ending.trimStart()\n return ` ${missingAttributes.join(\" \")}${suffix}`\n })\n}\n\nconst renderHtmlAttributes = (\n rendered: { htmlStart: string, htmlEnd: string },\n htmlAttributes: HtmlOutlets[\"htmlAttributes\"],\n) => {\n if (!htmlAttributes || (htmlAttributes.lang === undefined && htmlAttributes.dir === undefined)) {\n return rendered\n }\n\n const startTags = findHtmlStartTags(rendered.htmlStart)\n const endTags = findHtmlStartTags(rendered.htmlEnd)\n const htmlTagCount = startTags.length + endTags.length\n\n if (htmlTagCount === 0) {\n throw new Error(\"HTML template missing <html> element required by htmlAttributes\")\n }\n if (htmlTagCount > 1) {\n throw new Error(\"HTML template has multiple <html> elements\")\n }\n\n const target = startTags.length > 0 ? \"htmlStart\" : \"htmlEnd\"\n const match = startTags[0] ?? endTags[0]\n const value = rendered[target]\n\n return {\n ...rendered,\n [target]: `${value.slice(0, match.start)}${setHtmlTagAttributes(\n value.slice(match.start, match.end),\n htmlAttributes,\n )}${value.slice(match.end)}`,\n }\n}\n\nconst countOccurrences = (value: string, search: string) => {\n let count = 0\n let index = value.indexOf(search)\n\n while (index !== -1) {\n count += 1\n index = value.indexOf(search, index + search.length)\n }\n\n return count\n}\n\nconst getRpcbaseOutlets = (template: string): OutletMatch[] => {\n const outlets: OutletMatch[] = []\n\n for (const match of template.matchAll(TEMPLATE_ELEMENT_PATTERN)) {\n const outletAttributes = [...match[1].matchAll(RPCBASE_OUTLET_ATTRIBUTE_PATTERN)]\n if (outletAttributes.length === 0) continue\n if (outletAttributes.length > 1) {\n throw new Error(\"HTML template element has multiple data-rpcbase-outlet attributes\")\n }\n\n const outletAttribute = outletAttributes[0]\n outlets.push({\n name: outletAttribute[1] ?? outletAttribute[2] ?? outletAttribute[3],\n start: match.index,\n end: match.index + match[0].length,\n content: match[2],\n })\n }\n\n return outlets\n}\n\nexport const compileHtmlTemplate = (template: string): CompiledHtmlTemplate => {\n const legacyAppOutletCount = countOccurrences(template, LEGACY_APP_HTML_PLACEHOLDER)\n const rpcbaseOutlets = getRpcbaseOutlets(template)\n\n if (legacyAppOutletCount > 0 && rpcbaseOutlets.length > 0) {\n throw new Error(\"HTML template cannot mix rpcbase outlets with the legacy <!--app-html--> placeholder\")\n }\n\n if (rpcbaseOutlets.length === 0) {\n if (legacyAppOutletCount === 0) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"app\\\"></template> outlet\")\n }\n if (legacyAppOutletCount > 1) {\n throw new Error(\"HTML template has multiple legacy <!--app-html--> placeholders\")\n }\n\n const appOutletStart = template.indexOf(LEGACY_APP_HTML_PLACEHOLDER)\n\n return {\n isLegacy: true,\n render: (outlets = {}) => {\n if (outlets.head) {\n throw new Error(\"Cannot render the \\\"head\\\" outlet in a legacy HTML template\")\n }\n\n return renderHtmlAttributes({\n htmlStart: template.slice(0, appOutletStart),\n htmlEnd: template.slice(appOutletStart + LEGACY_APP_HTML_PLACEHOLDER.length),\n }, outlets.htmlAttributes)\n },\n }\n }\n\n const outletsByName = new Map<string, OutletMatch>()\n\n for (const outlet of rpcbaseOutlets) {\n if (outlet.name !== \"head\" && outlet.name !== \"app\") {\n throw new Error(`HTML template has unknown rpcbase outlet \"${outlet.name}\"`)\n }\n if (outletsByName.has(outlet.name)) {\n throw new Error(`HTML template has multiple rpcbase outlets named \"${outlet.name}\"`)\n }\n if (outlet.content.trim()) {\n throw new Error(`HTML template rpcbase outlet \"${outlet.name}\" must be empty`)\n }\n\n outletsByName.set(outlet.name, outlet)\n }\n\n const headOutlet = outletsByName.get(\"head\")\n const appOutlet = outletsByName.get(\"app\")\n\n if (!appOutlet) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"app\\\"></template> outlet\")\n }\n if (headOutlet && headOutlet.start > appOutlet.start) {\n throw new Error(\"HTML template rpcbase outlet \\\"head\\\" must appear before \\\"app\\\"\")\n }\n\n return {\n isLegacy: false,\n render: (outlets = {}) => {\n if (!headOutlet) {\n if (outlets.head) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"head\\\"></template> outlet\")\n }\n\n return renderHtmlAttributes({\n htmlStart: template.slice(0, appOutlet.start),\n htmlEnd: template.slice(appOutlet.end),\n }, outlets.htmlAttributes)\n }\n\n return renderHtmlAttributes({\n htmlStart: `${template.slice(0, headOutlet.start)}${outlets.head ?? \"\"}${template.slice(headOutlet.end, appOutlet.start)}`,\n htmlEnd: template.slice(appOutlet.end),\n }, outlets.htmlAttributes)\n },\n }\n}\n","import fs from \"node:fs/promises\"\nimport { readFileSync } from \"node:fs\"\nimport { Transform } from \"node:stream\"\n\nimport env from \"@rpcbase/env\"\nimport { SSR_ERROR_STATE_GLOBAL_KEY, SsrErrorFallback, serializeSsrErrorState, type SsrErrorStatePayload } from \"@rpcbase/client\"\nimport { StaticHandler } from \"@rpcbase/router\"\nimport { createElement, StrictMode, type ComponentType } from \"react\"\nimport { renderToPipeableStream, renderToStaticMarkup } from \"react-dom/server\"\nimport { NextFunction, Request, Response } from \"express\"\nimport type { PostHog } from \"posthog-node\"\n\nimport { renderSSR } from \"./renderSSR\"\nimport { captureServerException } from \"./posthog\"\nimport { renderRtsHydrationScript } from \"./rts/ssrHydration\"\nimport { compileHtmlTemplate, type HtmlOutlets } from \"./htmlTemplate\"\n\n\ntype ViteDevServer = {\n transformIndexHtml: (url: string, html: string) => Promise<string>\n ssrFixStacktrace: (error: Error) => void\n}\n\n\nconst ABORT_DELAY_MS = 10_000\nconst SSR_IDENTIFIER_PREFIX = \"rb-\"\nconst DEFAULT_SERVER_ERROR_MESSAGE = \"We couldn't render this page on the server. Please refresh and try again.\"\nconst 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>*{box-sizing:border-box}body{margin:0;background:#fff;color:#111827;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,\\\"Segoe UI\\\",sans-serif}#root,#root>div{min-height:100vh;background:#fff}main{display:flex;min-height:100vh;max-width:42rem;margin:0 auto;padding:3rem 1.5rem;flex-direction:column;align-items:center;justify-content:center;text-align:center}p{margin:0}main>p:first-child{font-size:1rem;line-height:1.5rem;font-weight:600;color:#e11d48}h1{margin:1rem 0 0;color:#111827;font-size:2.25rem;line-height:1.1;font-weight:600;letter-spacing:0;text-wrap:pretty}h1+p{margin-top:1.5rem;color:#4b5563;font-size:1.125rem;line-height:1.75rem}[class~=\\\"bg-gray-900/95\\\"]{width:100%;margin-top:2.5rem;border-radius:1rem;background:rgba(17,24,39,.96);padding:1.25rem;text-align:left;box-shadow:0 25px 50px -12px rgba(0,0,0,.25)}[class~=\\\"bg-gray-900/95\\\"] p{color:#9ca3af;font-size:.875rem;line-height:1.25rem;font-weight:600;letter-spacing:.025em;text-transform:uppercase}pre{max-height:16rem;overflow:auto;margin:.75rem 0 0;white-space:pre-wrap;color:#f3f4f6;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace;font-size:.875rem;line-height:1.25rem}main>div[class~=\\\"flex\\\"]{display:flex;margin-top:2.5rem;flex-direction:column;gap:1rem;align-items:center;justify-content:center}a{color:#111827;text-decoration:none}main>div[class~=\\\"flex\\\"] a:first-child{display:inline-flex;height:2.25rem;align-items:center;justify-content:center;border-radius:.375rem;background:#111827;padding:0 1rem;color:#f8fafc;font-size:.875rem;font-weight:500;box-shadow:0 1px 2px rgba(15,23,42,.08)}main>div[class~=\\\"flex\\\"] a:first-child:hover{background:#1f2937}main>div[class~=\\\"flex\\\"] a:not(:first-child){color:#111827;font-size:.875rem;font-weight:500;text-underline-offset:4px}main>div[class~=\\\"flex\\\"] a:not(:first-child):hover{text-decoration:underline}@media (min-width:640px){main{padding-top:6rem;padding-bottom:6rem}h1{font-size:3rem}h1+p{font-size:1.25rem;line-height:1.625}main>div[class~=\\\"flex\\\"]{flex-direction:row}}</style></head><body><div id=\\\"root\\\">\"\nconst FALLBACK_ERROR_TEMPLATE_END = \"</div></body></html>\"\n\nconst isProduction = env.NODE_ENV === \"production\"\n\n\n// Cached production assets\nconst templateHtml = isProduction\n ? readFileSync(\"./build/dist/client/src/client/index.html\", \"utf-8\")\n : \"\"\nconst compiledTemplate = isProduction\n ? compileHtmlTemplate(templateHtml)\n : null\n\nconst handleRedirectionResponse = (\n res: Response,\n redirectResponse: globalThis.Response,\n location?: string | null,\n) => {\n res.status(redirectResponse.status || 302)\n\n try {\n const headers = redirectResponse.headers as Headers & {\n getSetCookie?: () => string[]\n }\n // `Set-Cookie` is special: redirects commonly set multiple cookies (auth/session). Express\n // `setHeader` overwrites duplicates, and `Headers#get(\"set-cookie\")` joins values with commas\n // (unsafe for cookies), so we forward it once as an array via `getSetCookie()` when available.\n const setCookies = headers.getSetCookie?.()\n const fallbackSetCookies: string[] = []\n\n for (const [key, value] of headers) {\n if (key.toLowerCase() === \"set-cookie\") {\n if (!setCookies?.length) {\n fallbackSetCookies.push(value)\n }\n continue\n }\n res.setHeader(key, value)\n }\n\n if (setCookies?.length) {\n res.setHeader(\"Set-Cookie\", setCookies)\n } else if (fallbackSetCookies.length === 1) {\n res.setHeader(\"Set-Cookie\", fallbackSetCookies[0])\n } else if (fallbackSetCookies.length > 1) {\n res.setHeader(\"Set-Cookie\", fallbackSetCookies)\n }\n } catch {\n //\n }\n\n if (location) res.setHeader(\"Location\", location)\n res.end()\n}\n\nconst formatErrorDetails = (error: unknown): string | undefined => {\n if (isProduction) return undefined\n if (!error) return undefined\n if (error instanceof Error) {\n return error.stack || error.message\n }\n if (typeof error === \"string\") {\n return error\n }\n try {\n return JSON.stringify(error, null, 2)\n } catch {\n return undefined\n }\n}\n\nconst sendErrorResponse = ({\n res,\n htmlStart,\n htmlEnd,\n error,\n status = 500,\n title = \"Server rendering error\",\n message = DEFAULT_SERVER_ERROR_MESSAGE,\n errorExtraComponent,\n}: {\n res: Response\n htmlStart: string | null\n htmlEnd: string | null\n error?: unknown\n status?: number\n title?: string\n message?: string\n errorExtraComponent?: ComponentType<{ state?: SsrErrorStatePayload }>\n}) => {\n if (res.headersSent) return\n\n const start = htmlStart ?? FALLBACK_ERROR_TEMPLATE_START\n const end = htmlEnd ?? FALLBACK_ERROR_TEMPLATE_END\n\n res.status(status)\n res.set({ \"Content-Type\": \"text/html\" })\n\n const details = formatErrorDetails(error)\n const state = {\n statusCode: status,\n title,\n message,\n details,\n }\n\n const markup = renderToStaticMarkup(\n createElement(\n StrictMode,\n null,\n createElement(SsrErrorFallback, {\n state,\n renderErrorExtra: errorExtraComponent\n ? (payload) => createElement(errorExtraComponent, { state: payload })\n : undefined,\n }),\n ),\n )\n\n const serializedState = `<script>window.${SSR_ERROR_STATE_GLOBAL_KEY}=${serializeSsrErrorState({\n ...state,\n details: isProduction ? undefined : details,\n })};</script>`\n\n res.end(`${start}${markup}${serializedState}${end}`)\n}\n\nexport const ssrMiddleware = ({\n viteInstance,\n dataRoutes,\n errorExtraComponent,\n getHtmlOutlets,\n renderTemplateStart,\n posthog,\n}: {\n viteInstance: ViteDevServer,\n dataRoutes: StaticHandler[\"dataRoutes\"],\n errorExtraComponent?: ComponentType<{ state?: SsrErrorStatePayload }>,\n getHtmlOutlets?: (req: Request) => HtmlOutlets | Promise<HtmlOutlets>,\n renderTemplateStart?: (req: Request, templateStart: string) => Promise<string>,\n posthog?: PostHog | null,\n}) => async(req: Request, res: Response, next: NextFunction) => {\n let template: string\n let htmlStart: string | null = null\n let htmlEnd: string | null = null\n let responseCommitted = false\n\n const posthogClient = posthog ?? (req.app?.locals?.posthog as PostHog | undefined) ?? null\n\n const captureException = (error: unknown, extra?: Record<string, unknown>) => {\n if (!error) return\n captureServerException(error, posthogClient, {\n path: req.originalUrl,\n method: req.method,\n source: \"ssrMiddleware\",\n ...extra,\n })\n }\n\n const finalizeWithErrorPage = (error?: unknown, status = 500, message = DEFAULT_SERVER_ERROR_MESSAGE) => {\n if (responseCommitted) return\n sendErrorResponse({\n res,\n htmlStart,\n htmlEnd,\n error,\n status,\n message,\n errorExtraComponent,\n })\n responseCommitted = true\n\n if (error) {\n captureException(error, { phase: \"finalizeWithErrorPage\" })\n }\n }\n\n try {\n const base = \"/\"\n const url = req.originalUrl.replace(base, \"\")\n\n let requestTemplate = compiledTemplate\n\n if (!isProduction) {\n template = await fs.readFile(\"./src/client/index.html\", \"utf-8\")\n template = await viteInstance.transformIndexHtml(url, template)\n requestTemplate = compileHtmlTemplate(template)\n }\n\n if (!requestTemplate) {\n throw new Error(\"HTML template was not compiled\")\n }\n\n const outlets = await getHtmlOutlets?.(req)\n const renderedTemplate = requestTemplate.render(outlets)\n const templateStart = renderedTemplate.htmlStart\n if (renderTemplateStart && !requestTemplate.isLegacy) {\n throw new Error(\"renderTemplateStart can only be used with the legacy <!--app-html--> placeholder\")\n }\n if (renderTemplateStart) {\n htmlStart = await renderTemplateStart(req, templateStart)\n } else {\n htmlStart = templateStart\n }\n htmlEnd = renderedTemplate.htmlEnd\n\n const {\n element,\n isMatched,\n statusCode,\n rtsHydrationData,\n redirectResponse,\n redirectRouteId,\n redirectRoutePath,\n } = await renderSSR(req, res, dataRoutes)\n\n if (redirectResponse) {\n if (!responseCommitted) {\n const location = redirectResponse.headers?.get?.(\"Location\")\n\n if (!isProduction) {\n console.info(\"SSR redirect\", {\n method: req.method,\n url: req.originalUrl,\n status: redirectResponse.status,\n location,\n routeId: redirectRouteId ?? undefined,\n routePath: redirectRoutePath ?? undefined,\n })\n }\n\n responseCommitted = true\n handleRedirectionResponse(res, redirectResponse, location)\n }\n return\n }\n\n // TODO we should do this before the renderTemplateStart, so we have the isMatched handling?\n if (!isMatched) {\n next()\n return\n }\n\n let didError = false\n\n const {pipe, abort} = renderToPipeableStream(\n element,\n {\n identifierPrefix: SSR_IDENTIFIER_PREFIX,\n onShellError(error) {\n if (error instanceof Error) {\n viteInstance?.ssrFixStacktrace(error)\n }\n console.error(\"SSR shell error\", error)\n captureException(error, { phase: \"shell\" })\n finalizeWithErrorPage(error)\n },\n onError(error) {\n didError = true\n if (error instanceof Error) {\n viteInstance?.ssrFixStacktrace(error)\n }\n console.error(\"SSR rendering error\", error)\n captureException(error, { phase: \"render\" })\n },\n onShellReady() {\n if (responseCommitted) {\n return\n }\n\n if (!htmlStart || !htmlEnd) {\n finalizeWithErrorPage()\n return\n }\n\n responseCommitted = true\n const responseStatus = didError ? 500 : statusCode || 200\n res.status(responseStatus)\n res.set({ \"Content-Type\": \"text/html\" })\n\n const transformStream = new Transform({\n transform(chunk, encoding, callback) {\n res.write(chunk, encoding)\n callback()\n },\n })\n\n const start = htmlStart\n const end = htmlEnd\n const rtsHydrationScript = renderRtsHydrationScript(rtsHydrationData)\n\n res.write(start)\n\n transformStream.on(\"finish\", () => {\n res.end(`${rtsHydrationScript}${end}`)\n })\n\n pipe(transformStream)\n },\n },\n )\n\n setTimeout(() => {\n abort()\n }, ABORT_DELAY_MS)\n } catch (err: unknown) {\n if (err instanceof Error) {\n viteInstance?.ssrFixStacktrace(err)\n console.error(\"SSR middleware error:\", err.message)\n console.error(err.stack)\n } else {\n console.error(\"Unknown SSR middleware error\", err)\n }\n\n captureException(err, { phase: \"catch\" })\n\n finalizeWithErrorPage(err)\n }\n}\n","import { GridFSBucket, ObjectId, type Collection, type Db } from \"mongodb\"\nimport {\n getTenantFilesystemDb,\n models,\n type IRBUploadChunk,\n type IRBUploadSession,\n} from \"@rpcbase/db\"\nimport type { Connection, Model } from \"mongoose\"\n\nimport {\n deleteUploadFileReference,\n type UploadFileReference,\n} from \"./uploads/api/file-uploads/fileReferences\"\nimport {\n getBucketName,\n getFileReferencesCollectionName,\n resolveStoredUploadAccessScope,\n} from \"./uploads/api/file-uploads/shared\"\n\n\ntype UploadSessionDocument = Pick<IRBUploadSession, \"_id\">\ntype UploadChunkDocument = Omit<IRBUploadChunk, \"data\"> & { data: Buffer }\n\ntype GridFsFileDocument = {\n _id: ObjectId\n metadata?: Record<string, unknown>\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst getNativeDb = (connection: Connection): Db => {\n if (!connection.db) {\n throw new Error(`Mongo database '${connection.name}' is unavailable.`)\n }\n return connection.db\n}\n\nconst deleteGridFsFile = async (\n db: Db,\n bucket: GridFSBucket,\n bucketName: string,\n fileId: ObjectId,\n): Promise<void> => {\n const variants = await db.collection<GridFsFileDocument>(`${bucketName}.files`)\n .find(\n { \"metadata.variantOf\": fileId.toHexString() },\n { projection: { _id: 1 } },\n )\n .toArray()\n\n await bucket.delete(fileId)\n for (const variant of variants) {\n if (variant._id instanceof ObjectId) await bucket.delete(variant._id)\n }\n}\n\nconst removeUserFromSharedFile = async (\n files: Collection<GridFsFileDocument>,\n fileId: ObjectId,\n): Promise<void> => {\n await files.updateMany(\n {\n $or: [\n { _id: fileId },\n { \"metadata.variantOf\": fileId.toHexString() },\n ],\n },\n { $unset: { \"metadata.userId\": \"\" } },\n )\n}\n\nexport const deleteRpcbaseUserUploads = async (\n tenantId: string,\n userId: string,\n): Promise<void> => {\n const modelCtx = { tenantId }\n const [UploadSession, UploadChunk] = await Promise.all([\n models.getUnsafe(\"RBUploadSession\", modelCtx) as Promise<Model<IRBUploadSession>>,\n models.getUnsafe(\"RBUploadChunk\", modelCtx) as Promise<Model<UploadChunkDocument>>,\n ])\n const uploadSessions = await UploadSession.find(\n { userId },\n { _id: 1 },\n ).lean() as UploadSessionDocument[]\n const uploadIds = uploadSessions.map((session) => session._id)\n\n const filesystemConnection = await getTenantFilesystemDb(tenantId)\n const filesystemDb = getNativeDb(filesystemConnection)\n const bucketName = getBucketName()\n const references = filesystemDb.collection<UploadFileReference>(\n getFileReferencesCollectionName(bucketName),\n )\n const userReferences = await references.find({ userId }).toArray()\n\n for (const reference of userReferences) {\n if (resolveStoredUploadAccessScope(reference as unknown as Record<string, unknown>) === \"owner\") {\n await deleteUploadFileReference({\n tenantId,\n bucketName,\n referenceId: reference._id,\n })\n continue\n }\n\n await references.updateOne(\n { _id: reference._id },\n { $unset: { userId: \"\" } },\n )\n }\n\n const files = filesystemDb.collection<GridFsFileDocument>(`${bucketName}.files`)\n const userFiles = await files.find({ \"metadata.userId\": userId }).toArray()\n const bucket = userFiles.length > 0\n ? new GridFSBucket(filesystemDb, { bucketName })\n : null\n\n for (const file of userFiles) {\n if (!(file._id instanceof ObjectId) || !bucket) continue\n\n const metadata = file.metadata ?? {}\n const deduplication = metadata.deduplication\n const isDeduplicated = Boolean(\n deduplication\n && typeof deduplication === \"object\"\n && toTrimmedString((deduplication as Record<string, unknown>).key),\n )\n const accessScope = resolveStoredUploadAccessScope(metadata)\n\n if (accessScope === \"owner\" && !isDeduplicated) {\n await deleteGridFsFile(filesystemDb, bucket, bucketName, file._id)\n continue\n }\n\n await removeUserFromSharedFile(files, file._id)\n }\n\n await Promise.all([\n uploadIds.length > 0\n ? UploadChunk.deleteMany({ uploadId: { $in: uploadIds } })\n : Promise.resolve(),\n UploadSession.deleteMany({ userId }),\n ])\n}\n","import { type Collection, type Db } from \"mongodb\"\nimport { getTenantFilesystemDb, models } from \"@rpcbase/db\"\nimport type { ClientSession, Connection } from \"mongoose\"\n\nimport { deleteRpcbaseUserUploads } from \"./accountDeletionUploads\"\n\n\ntype UserAccountDocument = {\n _id?: unknown\n tenants?: unknown\n tenantRoles?: unknown\n}\n\nexport type DeleteRpcbaseTenantUserDataScope = {\n tenantId: string\n userId: string\n}\n\nexport type DeleteRpcbaseUserAccountOptions = {\n userId: string\n deleteTenantUserData?: (scope: DeleteRpcbaseTenantUserDataScope) => Promise<void>\n}\n\nexport type DeleteRpcbaseUserAccountResult = {\n tenantIds: string[]\n deletedTenantIds: string[]\n failedTenantDatabaseIds: string[]\n}\n\nexport class RpcbaseUserAccountNotFoundError extends Error {\n constructor(userId: string) {\n super(`RPCBase user account '${userId}' was not found.`)\n this.name = \"RpcbaseUserAccountNotFoundError\"\n }\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst normalizeRequiredId = (value: string, label: string): string => {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${label} is required.`)\n return normalized\n}\n\nconst toStringArray = (value: unknown): string[] => {\n if (!Array.isArray(value)) return []\n return value.map(toTrimmedString).filter(Boolean)\n}\n\nconst getTenantRoleIds = (value: unknown): string[] => {\n if (value instanceof Map) {\n return Array.from(value.keys()).map(toTrimmedString).filter(Boolean)\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return []\n return Object.keys(value).map(toTrimmedString).filter(Boolean)\n}\n\nconst getAccountTenantIds = (\n user: Pick<UserAccountDocument, \"tenants\" | \"tenantRoles\">,\n): string[] => Array.from(new Set([\n ...toStringArray(user.tenants),\n ...getTenantRoleIds(user.tenantRoles),\n]))\n\nconst getNativeDb = (connection: Connection): Db => {\n if (!connection.db) {\n throw new Error(`Mongo database '${connection.name}' is unavailable.`)\n }\n return connection.db\n}\n\nconst listCollectionNames = async (connection: Connection): Promise<string[]> => {\n const collections = await getNativeDb(connection)\n .listCollections({}, { nameOnly: true })\n .toArray()\n\n return collections\n .map((collection) => toTrimmedString(collection.name))\n .filter((collectionName) => collectionName && !collectionName.startsWith(\"system.\"))\n}\n\nconst buildTenantMembershipFilter = (tenantId: string): Record<string, unknown> => {\n const clauses: Array<Record<string, unknown>> = [{ tenants: tenantId }]\n if (!tenantId.includes(\".\") && !tenantId.startsWith(\"$\")) {\n clauses.push({ [`tenantRoles.${tenantId}`]: { $exists: true } })\n }\n return { $or: clauses }\n}\n\nconst deleteRpcbaseTenantUserData = async (\n tenantId: string,\n userId: string,\n): Promise<void> => {\n const modelCtx = { tenantId }\n const [Notification, NotificationDelivery, NotificationSettings] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n models.getUnsafe(\"RBNotificationSettings\", modelCtx),\n ])\n\n await Promise.all([\n Notification.deleteMany({ userId }),\n NotificationDelivery.deleteMany({ userId }),\n NotificationSettings.deleteMany({ userId }),\n deleteRpcbaseUserUploads(tenantId, userId),\n ])\n}\n\nconst deleteTenantGlobalData = async (\n connection: Connection,\n collectionNames: string[],\n userCollectionName: string,\n tenantId: string,\n session: ClientSession,\n): Promise<void> => {\n for (const collectionName of collectionNames) {\n if (collectionName === userCollectionName) continue\n\n const collection = connection.collection(collectionName)\n const hasTenantData = await collection.findOne(\n { tenantId },\n { projection: { _id: 1 }, session },\n )\n if (hasTenantData) {\n await collection.deleteMany({ tenantId }, { session })\n }\n }\n}\n\nconst deleteGlobalUserAccount = async ({\n connection,\n users,\n userDocumentId,\n}: {\n connection: Connection\n users: Collection<UserAccountDocument>\n userDocumentId: unknown\n}): Promise<{ tenantIds: string[]; deletedTenantIds: string[] }> => {\n const collectionNames = await listCollectionNames(connection)\n const session = await connection.startSession()\n let result = { tenantIds: [] as string[], deletedTenantIds: [] as string[] }\n\n try {\n await session.withTransaction(async () => {\n const user = await users.findOne(\n { _id: userDocumentId } as Record<string, unknown>,\n {\n projection: { _id: 1, tenants: 1, tenantRoles: 1 },\n session,\n },\n )\n if (!user) throw new RpcbaseUserAccountNotFoundError(String(userDocumentId))\n\n const tenantIds = getAccountTenantIds(user)\n const deletedTenantIds: string[] = []\n\n for (const tenantId of tenantIds) {\n const otherUser = await users.findOne(\n {\n _id: { $ne: userDocumentId },\n ...buildTenantMembershipFilter(tenantId),\n } as Record<string, unknown>,\n { projection: { _id: 1 }, session },\n )\n if (!otherUser) deletedTenantIds.push(tenantId)\n }\n\n for (const tenantId of deletedTenantIds) {\n await deleteTenantGlobalData(\n connection,\n collectionNames,\n users.collectionName,\n tenantId,\n session,\n )\n }\n\n const deletedUser = await users.deleteOne(\n { _id: userDocumentId } as Record<string, unknown>,\n { session },\n )\n if (deletedUser.deletedCount !== 1) {\n throw new Error(\"RPCBase user account was not deleted.\")\n }\n\n result = { tenantIds, deletedTenantIds }\n })\n\n return result\n } finally {\n await session.endSession()\n }\n}\n\nconst dropTenantDatabases = async (tenantId: string): Promise<boolean> => {\n const tenantModel = await models.getUnsafe(\"RBNotification\", { tenantId })\n const filesystemConnection = await getTenantFilesystemDb(tenantId)\n const results = await Promise.allSettled([\n tenantModel.db.dropDatabase(),\n filesystemConnection.dropDatabase(),\n ])\n return results.every((result) => result.status === \"fulfilled\")\n}\n\nexport const deleteRpcbaseUserAccount = async ({\n userId: rawUserId,\n deleteTenantUserData,\n}: DeleteRpcbaseUserAccountOptions): Promise<DeleteRpcbaseUserAccountResult> => {\n const userId = normalizeRequiredId(rawUserId, \"User ID\")\n const User = await models.getGlobal(\"RBUser\", { req: { session: null } })\n const account = await User.findById(\n userId,\n { _id: 1, tenants: 1, tenantRoles: 1 },\n ).lean() as UserAccountDocument | null\n\n if (!account?._id) throw new RpcbaseUserAccountNotFoundError(userId)\n\n const initialTenantIds = getAccountTenantIds(account)\n for (const tenantId of initialTenantIds) {\n await deleteTenantUserData?.({ tenantId, userId })\n await deleteRpcbaseTenantUserData(tenantId, userId)\n }\n\n const users = User.collection as unknown as Collection<UserAccountDocument>\n const globalDeletion = await deleteGlobalUserAccount({\n connection: User.db,\n users,\n userDocumentId: account._id,\n })\n const failedTenantDatabaseIds: string[] = []\n\n for (const tenantId of globalDeletion.deletedTenantIds) {\n if (!await dropTenantDatabases(tenantId)) {\n failedTenantDatabaseIds.push(tenantId)\n }\n }\n\n return {\n ...globalDeletion,\n failedTenantDatabaseIds,\n }\n}\n","type StoredSession = {\n id?: unknown\n user?: {\n id?: unknown\n }\n}\n\ntype SessionStoreLike = {\n all?: (\n callback: (\n error: unknown,\n sessions?: StoredSession[] | Record<string, StoredSession> | null,\n ) => void,\n ) => unknown\n destroy: (sessionId: string, callback?: (error?: unknown) => void) => unknown\n}\n\ntype CurrentSessionLike = {\n user?: unknown\n destroy: (callback: (error?: unknown) => void) => unknown\n}\n\nexport type DestroyRpcbaseUserSessionsInput = {\n request: {\n sessionID?: unknown\n sessionStore?: unknown\n session?: unknown\n }\n userId: string\n}\n\nexport type DestroyRpcbaseUserSessionsResult = {\n destroyedSessionCount: number\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst getSessionStore = (value: unknown): SessionStoreLike | null => {\n if (!value || typeof value !== \"object\") return null\n const candidate = value as Partial<SessionStoreLike>\n return typeof candidate.destroy === \"function\"\n ? candidate as SessionStoreLike\n : null\n}\n\nconst getCurrentSession = (value: unknown): CurrentSessionLike | null => {\n if (!value || typeof value !== \"object\") return null\n const candidate = value as Partial<CurrentSessionLike>\n return typeof candidate.destroy === \"function\"\n ? candidate as CurrentSessionLike\n : null\n}\n\nconst destroyStoredSession = async (\n store: SessionStoreLike,\n sessionId: string,\n): Promise<void> => {\n await new Promise<void>((resolve, reject) => {\n store.destroy(sessionId, (error) => {\n if (error) {\n reject(error)\n return\n }\n resolve()\n })\n })\n}\n\nconst loadStoredSessions = async (\n store: SessionStoreLike,\n): Promise<StoredSession[] | Record<string, StoredSession> | null> => {\n if (!store.all) return null\n\n return await new Promise((resolve, reject) => {\n store.all?.((error, sessions) => {\n if (error) {\n reject(error)\n return\n }\n resolve(sessions ?? null)\n })\n })\n}\n\nconst destroyOtherUserSessions = async (\n request: DestroyRpcbaseUserSessionsInput[\"request\"],\n userId: string,\n): Promise<number> => {\n const store = getSessionStore(request.sessionStore)\n if (!store?.all) return 0\n\n const storedSessions = await loadStoredSessions(store)\n if (!storedSessions) return 0\n\n const currentSessionId = toTrimmedString(request.sessionID)\n const entries = Array.isArray(storedSessions)\n ? storedSessions.map((session) => [toTrimmedString(session.id), session] as const)\n : Object.entries(storedSessions)\n const sessionIds = entries\n .filter(([, session]) => toTrimmedString(session.user?.id) === userId)\n .map(([sessionId]) => sessionId)\n .filter((sessionId) => sessionId && sessionId !== currentSessionId)\n\n await Promise.all(sessionIds.map((sessionId) => destroyStoredSession(store, sessionId)))\n return sessionIds.length\n}\n\nconst destroyCurrentSession = async (\n request: DestroyRpcbaseUserSessionsInput[\"request\"],\n): Promise<number> => {\n const session = getCurrentSession(request.session)\n if (!session) return 0\n\n session.user = undefined\n await new Promise<void>((resolve, reject) => {\n session.destroy((error) => {\n if (error) {\n reject(error)\n return\n }\n resolve()\n })\n })\n return 1\n}\n\nexport const destroyRpcbaseUserSessions = async ({\n request,\n userId: rawUserId,\n}: DestroyRpcbaseUserSessionsInput): Promise<DestroyRpcbaseUserSessionsResult> => {\n const userId = rawUserId.trim()\n if (!userId) throw new Error(\"User ID is required.\")\n\n const errors: unknown[] = []\n let destroyedSessionCount = 0\n\n try {\n destroyedSessionCount += await destroyOtherUserSessions(request, userId)\n } catch (error) {\n errors.push(error)\n }\n\n try {\n destroyedSessionCount += await destroyCurrentSession(request)\n } catch (error) {\n errors.push(error)\n }\n\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) {\n throw new AggregateError(errors, \"Could not destroy every RPCBase user session.\")\n }\n\n return { destroyedSessionCount }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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,YAAY,CAAC,gBAAgB,QAAQ,EAAE,GAAG,OAAO,CAAU,IAC/E,OAAO,QAAQ,cAAc,EAAA,CAE9B,QAAQ,GAAG,aAAa,gBAAgB,QAAQ,MAAM,EAAE,MAAM,MAAM,CAAC,CACrE,KAAK,CAAC,eAAe,SAAS,CAAC,CAC/B,QAAQ,cAAc,aAAa,cAAc,gBAAgB;CAEpE,MAAM,QAAQ,IAAI,WAAW,KAAK,cAAc,qBAAqB,OAAO,SAAS,CAAC,CAAC;CACvF,OAAO,WAAW;AACpB;AAEA,IAAM,wBAAwB,OAC5B,YACoB;CACpB,MAAM,UAAU,kBAAkB,QAAQ,OAAO;CACjD,IAAI,CAAC,SAAS,OAAO;CAErB,QAAQ,OAAO,KAAA;CACf,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,QAAQ,SAAS,UAAU;GACzB,IAAI,OAAO;IACT,OAAO,KAAK;IACZ;GACF;GACA,QAAQ;EACV,CAAC;CACH,CAAC;CACD,OAAO;AACT;AAEA,IAAa,6BAA6B,OAAO,EAC/C,SACA,QAAQ,gBACwE;CAChF,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,sBAAsB;CAEnD,MAAM,SAAoB,CAAA;CAC1B,IAAI,wBAAwB;CAE5B,IAAI;EACF,yBAAyB,MAAM,yBAAyB,SAAS,MAAM;CACzE,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEA,IAAI;EACF,yBAAyB,MAAM,sBAAsB,OAAO;CAC9D,SAAS,OAAO;EACd,OAAO,KAAK,KAAK;CACnB;CAEA,IAAI,OAAO,WAAW,GAAG,MAAM,OAAO;CACtC,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,eAAe,QAAQ,+CAA+C;CAGlF,OAAO,EAAE,sBAAsB;AACjC"}
1
+ {"version":3,"file":"index.js","names":["gzipCompress","PostHogPersistedProperty","gzipCompress","ErrorTracking.ReduceableCache","promises_open","isAbsolute","ErrorTracking.getInjectedReleaseId","gzipCompress","error_tracking","PostHogPersistedProperty","ErrorTracking.getInjectedReleaseId","#_","error_tracking","ErrorTracking.ErrorPropertiesBuilder","ErrorTracking.EventCoercer","ErrorTracking.ErrorCoercer","ErrorTracking.ObjectCoercer","ErrorTracking.StringCoercer","ErrorTracking.PrimitiveCoercer","ErrorTracking.createStackParser","ErrorTracking.nodeStackLineParser"],"sources":["../../../node_modules/request-ip/lib/is.js","../../../node_modules/request-ip/lib/index.js","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs","../../../node_modules/@posthog/core/dist/featureFlagUtils.mjs","../../../node_modules/@posthog/core/dist/types.mjs","../../../node_modules/@posthog/core/dist/gzip.mjs","../../../node_modules/@posthog/core/dist/utils/json-utils.mjs","../../../node_modules/@posthog/core/dist/utils/bot-detection.mjs","../../../node_modules/@posthog/core/dist/utils/string-utils.mjs","../../../node_modules/@posthog/core/dist/utils/type-utils.mjs","../../../node_modules/@posthog/core/dist/utils/number-utils.mjs","../../../node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs","../../../node_modules/@posthog/core/dist/vendor/uuidv7.mjs","../../../node_modules/@posthog/core/dist/utils/promise-queue.mjs","../../../node_modules/@posthog/core/dist/utils/logger.mjs","../../../node_modules/@posthog/core/dist/utils/user-agent-utils.mjs","../../../node_modules/@posthog/core/dist/utils/index.mjs","../../../node_modules/@posthog/core/dist/logs/logs-utils.mjs","../../../node_modules/@posthog/core/dist/metrics/metrics-utils.mjs","../../../node_modules/@posthog/core/dist/metrics/config.mjs","../../../node_modules/@posthog/core/dist/metrics/index.mjs","../../../node_modules/@posthog/core/dist/eventemitter.mjs","../../../node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs","../../../node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs","../../../node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/types.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs","../../../node_modules/@posthog/core/dist/error-tracking/utils.mjs","../../../node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs","../../../node_modules/@posthog/core/dist/error-tracking/release.mjs","../../../node_modules/@posthog/core/dist/posthog-core-stateless.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs","../../../node_modules/posthog-node/dist/version.mjs","../../../node_modules/posthog-node/dist/types.mjs","../../../node_modules/posthog-node/dist/feature-flag-evaluations.mjs","../../../node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs","../../../node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs","../../../node_modules/posthog-node/dist/extensions/error-tracking/index.mjs","../../../node_modules/posthog-node/dist/storage-memory.mjs","../../../node_modules/posthog-node/dist/capture-v1/config.mjs","../../../node_modules/posthog-node/dist/capture-v1/routing.mjs","../../../node_modules/posthog-node/dist/capture-v1/errors.mjs","../../../node_modules/posthog-node/dist/capture-v1/transform.mjs","../../../node_modules/posthog-node/dist/capture-v1/sender.mjs","../../../node_modules/posthog-node/dist/ai-capture/routing.mjs","../../../node_modules/posthog-node/dist/ai-capture/batching.mjs","../../../node_modules/posthog-node/dist/client.mjs","../../../node_modules/posthog-node/dist/extensions/context/context.mjs","../../../node_modules/posthog-node/dist/gzip.node.mjs","../../../node_modules/posthog-node/dist/extensions/sentry-integration.mjs","../../../node_modules/posthog-node/dist/extensions/tracing-headers.mjs","../../../node_modules/posthog-node/dist/extensions/url-utils.mjs","../../../node_modules/posthog-node/dist/extensions/express.mjs","../../../node_modules/posthog-node/dist/entrypoints/index.node.mjs","../src/shutdown.ts","../src/posthog.ts","../src/metricsIngestProxyMiddleware.ts","../src/checkInitReplicaSet.ts","../src/dev/coverage.ts","../src/developmentSessionMiddleware.ts","../src/serviceWorker.ts","../src/initServer.ts","../src/hashPassword.ts","../src/passwordHashStorage.ts","../src/applyRouteLoaders.ts","../src/rts/ssrHydration.ts","../src/renderSSR.tsx","../src/htmlTemplate.ts","../src/ssrMiddleware.ts","../src/accountDeletionUploads.ts","../src/accountDeletion.ts","../src/userSessionDeletion.ts"],"sourcesContent":["\"use strict\";\n\nvar regexes = {\n ipv4: /^(?:(?:\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])$/,\n ipv6: /^((?=.*::)(?!.*::.+::)(::)?([\\dA-F]{1,4}:(:|\\b)|){5}|([\\dA-F]{1,4}:){6})((([\\dA-F]{1,4}((?!\\3)::|:\\b|$))|(?!\\2\\3)){2}|(((2[0-4]|1\\d|[1-9])?\\d|25[0-5])\\.?\\b){4})$/i\n};\n\nfunction not(func) {\n return function () {\n return !func.apply(null, Array.prototype.slice.call(arguments));\n };\n}\n\nfunction existy(value) {\n return value != null;\n}\n\nfunction ip(value) {\n return existy(value) && regexes.ipv4.test(value) || regexes.ipv6.test(value);\n}\n\nfunction object(value) {\n return Object(value) === value;\n}\n\nfunction string(value) {\n return Object.prototype.toString.call(value) === '[object String]';\n}\n\nvar is = {\n existy: existy,\n ip: ip,\n object: object,\n string: string,\n not: {\n existy: not(existy),\n ip: not(ip),\n object: not(object),\n string: not(string)\n }\n};\nmodule.exports = is;","\"use strict\";\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }, _typeof(obj); }\n\nvar is = require('./is');\n\nfunction getClientIpFromXForwardedFor(value) {\n if (!is.existy(value)) {\n return null;\n }\n\n if (is.not.string(value)) {\n throw new TypeError(\"Expected a string, got \\\"\".concat(_typeof(value), \"\\\"\"));\n }\n\n var forwardedIps = value.split(',').map(function (e) {\n var ip = e.trim();\n\n if (ip.includes(':')) {\n var splitted = ip.split(':');\n\n if (splitted.length === 2) {\n return splitted[0];\n }\n }\n\n return ip;\n });\n\n for (var i = 0; i < forwardedIps.length; i++) {\n if (is.ip(forwardedIps[i])) {\n return forwardedIps[i];\n }\n }\n\n return null;\n}\n\nfunction getClientIp(req) {\n if (req.headers) {\n if (is.ip(req.headers['x-client-ip'])) {\n return req.headers['x-client-ip'];\n }\n\n var xForwardedFor = getClientIpFromXForwardedFor(req.headers['x-forwarded-for']);\n\n if (is.ip(xForwardedFor)) {\n return xForwardedFor;\n }\n\n if (is.ip(req.headers['cf-connecting-ip'])) {\n return req.headers['cf-connecting-ip'];\n }\n\n if (is.ip(req.headers['fastly-client-ip'])) {\n return req.headers['fastly-client-ip'];\n }\n\n if (is.ip(req.headers['true-client-ip'])) {\n return req.headers['true-client-ip'];\n }\n\n if (is.ip(req.headers['x-real-ip'])) {\n return req.headers['x-real-ip'];\n }\n\n if (is.ip(req.headers['x-cluster-client-ip'])) {\n return req.headers['x-cluster-client-ip'];\n }\n\n if (is.ip(req.headers['x-forwarded'])) {\n return req.headers['x-forwarded'];\n }\n\n if (is.ip(req.headers['forwarded-for'])) {\n return req.headers['forwarded-for'];\n }\n\n if (is.ip(req.headers.forwarded)) {\n return req.headers.forwarded;\n }\n\n if (is.ip(req.headers['x-appengine-user-ip'])) {\n return req.headers['x-appengine-user-ip'];\n }\n }\n\n if (is.existy(req.connection)) {\n if (is.ip(req.connection.remoteAddress)) {\n return req.connection.remoteAddress;\n }\n\n if (is.existy(req.connection.socket) && is.ip(req.connection.socket.remoteAddress)) {\n return req.connection.socket.remoteAddress;\n }\n }\n\n if (is.existy(req.socket) && is.ip(req.socket.remoteAddress)) {\n return req.socket.remoteAddress;\n }\n\n if (is.existy(req.info) && is.ip(req.info.remoteAddress)) {\n return req.info.remoteAddress;\n }\n\n if (is.existy(req.requestContext) && is.existy(req.requestContext.identity) && is.ip(req.requestContext.identity.sourceIp)) {\n return req.requestContext.identity.sourceIp;\n }\n\n if (req.headers) {\n if (is.ip(req.headers['Cf-Pseudo-IPv4'])) {\n return req.headers['Cf-Pseudo-IPv4'];\n }\n }\n\n if (is.existy(req.raw)) {\n return getClientIp(req.raw);\n }\n\n return null;\n}\n\nfunction mw(options) {\n var configuration = is.not.existy(options) ? {} : options;\n\n if (is.not.object(configuration)) {\n throw new TypeError('Options must be an object!');\n }\n\n var attributeName = configuration.attributeName || 'clientIp';\n return function (req, res, next) {\n var ip = getClientIp(req);\n Object.defineProperty(req, attributeName, {\n get: function get() {\n return ip;\n },\n configurable: true\n });\n next();\n };\n}\n\nmodule.exports = {\n getClientIpFromXForwardedFor: getClientIpFromXForwardedFor,\n getClientIp: getClientIp,\n mw: mw\n};","import { dirname, posix, sep } from \"path\";\nfunction createModulerModifier() {\n const getModuleFromFileName = createGetModuleFromFilename();\n return async (frames)=>{\n for (const frame of frames)frame.module = getModuleFromFileName(frame.filename);\n return frames;\n };\n}\nfunction createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = '\\\\' === sep) {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n return (filename)=>{\n if (!filename) return;\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n if ('.js' === ext || '.mjs' === ext || '.cjs' === ext) file = file.slice(0, -1 * ext.length);\n const decodedFile = decodeURIComponent(file);\n if (!dir) dir = '.';\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n return decodedFile;\n };\n}\nfunction normalizeWindowsPath(path) {\n return path.replace(/^[A-Z]:/, '').replace(/\\\\/g, '/');\n}\nexport { createModulerModifier };\n","const normalizeFlagsResponse = (flagsResponse)=>{\n if ('flags' in flagsResponse) {\n const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);\n const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads\n };\n }\n {\n const featureFlags = flagsResponse.featureFlags ?? {};\n const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v])=>[\n k,\n parsePayload(v)\n ]));\n const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value])=>[\n key,\n getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])\n ]));\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads,\n flags\n };\n }\n};\nfunction getFlagDetailFromFlagAndPayload(key, value, payload) {\n return {\n key: key,\n enabled: 'string' == typeof value ? true : value,\n variant: 'string' == typeof value ? value : void 0,\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n payload: payload ? JSON.stringify(payload) : void 0,\n description: void 0\n }\n };\n}\nconst getFlagValuesFromFlags = (flags)=>Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail])=>[\n key,\n getFeatureFlagValue(detail)\n ]).filter(([, value])=>void 0 !== value));\nconst getPayloadsFromFlags = (flags)=>{\n const safeFlags = flags ?? {};\n return Object.fromEntries(Object.keys(safeFlags).filter((flag)=>{\n const details = safeFlags[flag];\n return details.enabled && details.metadata && void 0 !== details.metadata.payload;\n }).map((flag)=>{\n const payload = safeFlags[flag].metadata?.payload;\n return [\n flag,\n payload ? parsePayload(payload) : void 0\n ];\n }));\n};\nconst getFeatureFlagValue = (detail)=>void 0 === detail ? void 0 : detail.variant ?? detail.enabled;\nconst parsePayload = (response)=>{\n if ('string' != typeof response) return response;\n try {\n return JSON.parse(response);\n } catch {\n return response;\n }\n};\nconst createFlagsResponseFromFlagsAndPayloads = (featureFlags, featureFlagPayloads)=>{\n const allKeys = [\n ...new Set([\n ...Object.keys(featureFlags ?? {}),\n ...Object.keys(featureFlagPayloads ?? {})\n ])\n ];\n const enabledFlags = allKeys.filter((flag)=>!!featureFlags[flag] || !!featureFlagPayloads[flag]).reduce((res, key)=>(res[key] = featureFlags[key] ?? true, res), {});\n const flagDetails = {\n featureFlags: enabledFlags,\n featureFlagPayloads: featureFlagPayloads ?? {}\n };\n return normalizeFlagsResponse(flagDetails);\n};\nconst updateFlagValue = (flag, value)=>({\n ...flag,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value)\n });\nfunction getEnabledFromValue(value) {\n return 'string' == typeof value ? true : value;\n}\nfunction getVariantFromValue(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst flagDetailsToResults = (flagDetails)=>Object.values(flagDetails).map((detail)=>{\n const value = detail.variant ?? detail.enabled;\n const rawPayload = detail.metadata?.payload;\n return {\n key: detail.key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n payload: void 0 !== rawPayload ? parsePayload(rawPayload) : null\n };\n });\nconst MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [\n 'utm_source',\n 'utm_medium',\n 'utm_campaign',\n 'utm_content',\n 'utm_term',\n 'gad_source',\n 'mc_cid',\n 'gclid',\n 'gclsrc',\n 'dclid',\n 'gbraid',\n 'wbraid',\n 'fbclid',\n 'msclkid',\n 'twclid',\n 'li_fat_id',\n 'igshid',\n 'ttclid',\n 'rdt_cid',\n 'epik',\n 'qclid',\n 'sccid',\n 'irclid',\n '_kx'\n];\nconst MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [\n '$feature_flag',\n '$feature_flag_response',\n '$feature_flag_has_experiment',\n '$feature_flag_id',\n '$feature_flag_version',\n '$feature_flag_reason',\n '$feature_flag_request_id',\n '$feature_flag_evaluated_at',\n '$feature_flag_error',\n 'locally_evaluated',\n '$groups',\n '$process_person_profile',\n '$geoip_disable',\n '$current_url',\n '$pathname',\n '$referring_domain',\n ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,\n '$session_id',\n '$window_id',\n '$lib',\n '$lib_version',\n '$device_id',\n '$is_server'\n];\nconst minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{\n const minimal = {};\n const copyKey = (key)=>{\n if (void 0 !== properties[key]) minimal[key] = properties[key];\n };\n MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);\n transportKeys.forEach(copyKey);\n return minimal;\n};\nexport { MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse, parsePayload, updateFlagValue };\n","var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {\n PostHogPersistedProperty[\"AnonymousId\"] = \"anonymous_id\";\n PostHogPersistedProperty[\"DistinctId\"] = \"distinct_id\";\n PostHogPersistedProperty[\"Props\"] = \"props\";\n PostHogPersistedProperty[\"EnablePersonProcessing\"] = \"enable_person_processing\";\n PostHogPersistedProperty[\"PersonMode\"] = \"person_mode\";\n PostHogPersistedProperty[\"FeatureFlagDetails\"] = \"feature_flag_details\";\n PostHogPersistedProperty[\"FeatureFlags\"] = \"feature_flags\";\n PostHogPersistedProperty[\"FeatureFlagPayloads\"] = \"feature_flag_payloads\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagDetails\"] = \"bootstrap_feature_flag_details\";\n PostHogPersistedProperty[\"BootstrapFeatureFlags\"] = \"bootstrap_feature_flags\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagPayloads\"] = \"bootstrap_feature_flag_payloads\";\n PostHogPersistedProperty[\"OverrideFeatureFlags\"] = \"override_feature_flags\";\n PostHogPersistedProperty[\"Queue\"] = \"queue\";\n PostHogPersistedProperty[\"AiQueue\"] = \"ai_queue\";\n PostHogPersistedProperty[\"AiCaptureQueue\"] = \"ai_capture_queue\";\n PostHogPersistedProperty[\"LogsQueue\"] = \"logs_queue\";\n PostHogPersistedProperty[\"OptedOut\"] = \"opted_out\";\n PostHogPersistedProperty[\"SessionId\"] = \"session_id\";\n PostHogPersistedProperty[\"SessionStartTimestamp\"] = \"session_start_timestamp\";\n PostHogPersistedProperty[\"SessionLastTimestamp\"] = \"session_timestamp\";\n PostHogPersistedProperty[\"PersonProperties\"] = \"person_properties\";\n PostHogPersistedProperty[\"GroupProperties\"] = \"group_properties\";\n PostHogPersistedProperty[\"InstalledAppBuild\"] = \"installed_app_build\";\n PostHogPersistedProperty[\"InstalledAppVersion\"] = \"installed_app_version\";\n PostHogPersistedProperty[\"SessionReplay\"] = \"session_replay\";\n PostHogPersistedProperty[\"PushRegistered\"] = \"push_registered\";\n PostHogPersistedProperty[\"SessionReplayEventTriggerActivatedSession\"] = \"session_replay_event_trigger_activated_session\";\n PostHogPersistedProperty[\"SurveyLastSeenDate\"] = \"survey_last_seen_date\";\n PostHogPersistedProperty[\"SurveysSeen\"] = \"surveys_seen\";\n PostHogPersistedProperty[\"Surveys\"] = \"surveys\";\n PostHogPersistedProperty[\"RemoteConfig\"] = \"remote_config\";\n PostHogPersistedProperty[\"FlagsEndpointWasHit\"] = \"flags_endpoint_was_hit\";\n PostHogPersistedProperty[\"DeviceId\"] = \"device_id\";\n return PostHogPersistedProperty;\n}({});\nvar types_Compression = /*#__PURE__*/ function(Compression) {\n Compression[\"GZipJS\"] = \"gzip-js\";\n Compression[\"Base64\"] = \"base64\";\n return Compression;\n}({});\nconst FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status)=>`api_error_${status}`\n};\nconst SurveyPosition = {\n TopLeft: 'top_left',\n TopCenter: 'top_center',\n TopRight: 'top_right',\n MiddleLeft: 'middle_left',\n MiddleCenter: 'middle_center',\n MiddleRight: 'middle_right',\n Left: 'left',\n Right: 'right',\n Center: 'center'\n};\nconst SurveyWidgetType = {\n Button: 'button',\n Tab: 'tab',\n Selector: 'selector'\n};\nconst SurveyType = {\n Popover: 'popover',\n API: 'api',\n Widget: 'widget',\n ExternalSurvey: 'external_survey'\n};\nconst SurveyQuestionDescriptionContentType = {\n Html: 'html',\n Text: 'text'\n};\nconst SurveyValidationType = {\n MinLength: 'min_length',\n MaxLength: 'max_length'\n};\nconst SurveyRatingDisplay = {\n Number: 'number',\n Emoji: 'emoji'\n};\nconst SurveyQuestionType = {\n Open: 'open',\n MultipleChoice: 'multiple_choice',\n SingleChoice: 'single_choice',\n Rating: 'rating',\n Link: 'link'\n};\nconst SurveyQuestionBranchingType = {\n NextQuestion: 'next_question',\n End: 'end',\n ResponseBased: 'response_based',\n SpecificQuestion: 'specific_question'\n};\nconst SurveyMatchType = {\n Regex: 'regex',\n NotRegex: 'not_regex',\n Exact: 'exact',\n IsNot: 'is_not',\n Icontains: 'icontains',\n NotIcontains: 'not_icontains'\n};\nconst SurveySchedule = {\n Once: 'once',\n Recurring: 'recurring',\n Always: 'always'\n};\nconst ActionStepStringMatching = {\n Contains: 'contains',\n Exact: 'exact',\n Regex: 'regex'\n};\nconst knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called'\n];\nconst knownUnsafeEditableEventProperty = [\n 'token'\n];\nexport { ActionStepStringMatching, types_Compression as Compression, FeatureFlagError, types_PostHogPersistedProperty as PostHogPersistedProperty, SurveyMatchType, SurveyPosition, SurveyQuestionBranchingType, SurveyQuestionDescriptionContentType, SurveyQuestionType, SurveyRatingDisplay, SurveySchedule, SurveyType, SurveyValidationType, SurveyWidgetType, knownUnsafeEditableEvent, knownUnsafeEditableEventProperty };\n","import { Compression } from \"./types.mjs\";\nfunction isGzipSupported() {\n return 'CompressionStream' in globalThis && 'TextEncoder' in globalThis && 'Response' in globalThis && 'function' == typeof Response.prototype.blob;\n}\nconst NATIVE_GZIP_VALIDATION_ERROR = 'NativeGzipValidationError';\nconst GZIP_MAGIC_FIRST_BYTE = 0x1f;\nconst GZIP_MAGIC_SECOND_BYTE = 0x8b;\nconst GZIP_DEFLATE_METHOD = 0x08;\nconst hasGzipMagic = (bytes)=>bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;\nconst isGzipData = (body)=>{\n if (body instanceof ArrayBuffer) return hasGzipMagic(new Uint8Array(body));\n if (ArrayBuffer.isView(body)) return hasGzipMagic(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return false;\n};\nconst isGzipRequest = (compression, urlCompression)=>compression === Compression.GZipJS || urlCompression === Compression.GZipJS || 'gzip' === urlCompression;\nconst isNativeAsyncGzipReadError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return 'NotReadableError' === name;\n};\nconst isNativeAsyncGzipError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return isNativeAsyncGzipReadError(error) || name === NATIVE_GZIP_VALIDATION_ERROR;\n};\nlet crc32Table;\nconst getCrc32Table = ()=>{\n if (crc32Table) return crc32Table;\n crc32Table = [];\n for(let i = 0; i < 256; i++){\n let crc = i;\n for(let j = 0; j < 8; j++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;\n crc32Table[i] = crc >>> 0;\n }\n return crc32Table;\n};\nconst crc32 = (bytes)=>{\n const table = getCrc32Table();\n let crc = 0xffffffff;\n for(let i = 0; i < bytes.length; i++)crc = table[(crc ^ bytes[i]) & 0xff] ^ crc >>> 8;\n return (0xffffffff ^ crc) >>> 0;\n};\nconst throwNativeGzipValidationError = (reason)=>{\n const error = new Error(`Native gzip produced invalid output: ${reason}`);\n error.name = NATIVE_GZIP_VALIDATION_ERROR;\n throw error;\n};\nconst validateNativeGzip = async (compressed, inputBytes)=>{\n if (compressed.size < 18) throwNativeGzipValidationError('too-short');\n const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());\n if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD) throwNativeGzipValidationError('invalid-header');\n const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());\n if (trailer.getUint32(0, true) !== crc32(inputBytes)) throwNativeGzipValidationError('invalid-crc');\n const inputSize = inputBytes.length >>> 0;\n if (trailer.getUint32(4, true) !== inputSize) throwNativeGzipValidationError('invalid-size');\n};\nasync function gzipCompress(input, isDebug = true, options) {\n try {\n const inputBytes = new TextEncoder().encode(input);\n const compressedStream = new globalThis.CompressionStream('gzip');\n const writer = compressedStream.writable.getWriter();\n const writePromise = writer.write(inputBytes).then(()=>writer.close()).catch(async (err)=>{\n try {\n await writer.abort(err);\n } catch {}\n throw err;\n });\n const responsePromise = new Response(compressedStream.readable).blob();\n const [compressed] = await Promise.all([\n responsePromise,\n writePromise\n ]);\n await validateNativeGzip(compressed, inputBytes);\n return compressed;\n } catch (error) {\n if (options?.rethrow) throw error;\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError };\n","const MAX_JSON_SAFE_VALUE_DEPTH = 20;\nconst MAX_JSON_SAFE_VALUE_ITEMS = 1000;\nconst MAX_JSON_SAFE_VALUE_NODES = 10000;\nconst CIRCULAR_VALUE = '[Circular]';\nconst TRUNCATED_VALUE = '[Truncated]';\nconst UNSERIALIZABLE_VALUE = '[Unserializable]';\nconst FUNCTION_VALUE = '[Function]';\nconst dateGetTime = Date.prototype.getTime;\nconst dateToISOString = Date.prototype.toISOString;\nconst propertyIsEnumerable = Object.prototype.propertyIsEnumerable;\nfunction sanitizeString(value) {\n let output = '';\n for(let index = 0; index < value.length; index++){\n const codeUnit = value.charCodeAt(index);\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const nextCodeUnit = value.charCodeAt(index + 1);\n if (nextCodeUnit >= 0xdc00 && nextCodeUnit <= 0xdfff) {\n output += value[index] + value[index + 1];\n index++;\n } else output += '\\ufffd';\n } else output += codeUnit >= 0xdc00 && codeUnit <= 0xdfff ? '\\ufffd' : value[index];\n }\n return output;\n}\nfunction toJsonSafeValue(value) {\n const state = {\n ancestors: new WeakSet(),\n remainingNodes: MAX_JSON_SAFE_VALUE_NODES\n };\n const convert = (current, depth)=>{\n if (state.remainingNodes <= 0) return TRUNCATED_VALUE;\n state.remainingNodes--;\n try {\n if (null == current || 'boolean' == typeof current) return current;\n if ('string' == typeof current) return sanitizeString(current);\n if ('number' == typeof current) return Number.isFinite(current) ? current : null;\n if ('bigint' == typeof current) return current.toString();\n if ('function' == typeof current) return FUNCTION_VALUE;\n if ('symbol' == typeof current) return current.description ? `Symbol(${current.description})` : 'Symbol()';\n if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) return TRUNCATED_VALUE;\n if (state.ancestors.has(current)) return CIRCULAR_VALUE;\n state.ancestors.add(current);\n try {\n if (current instanceof Date) return Number.isFinite(dateGetTime.call(current)) ? dateToISOString.call(current) : null;\n let hasToJSONResult = false;\n let toJSONResult;\n try {\n const toJSON = current.toJSON;\n if ('function' == typeof toJSON) {\n toJSONResult = toJSON.call(current);\n hasToJSONResult = true;\n }\n } catch {\n hasToJSONResult = false;\n }\n if (hasToJSONResult) return convert(toJSONResult, depth + 1);\n if (Array.isArray(current)) {\n const itemCount = Math.min(current.length, MAX_JSON_SAFE_VALUE_ITEMS);\n const output = [];\n let index = 0;\n for(; index < itemCount && state.remainingNodes > 0; index++)output.push(convert(current[index], depth + 1));\n if (current.length > index) output.push(TRUNCATED_VALUE);\n return output;\n }\n const output = {};\n let itemCount = 0;\n let truncated = false;\n for(const key in current){\n if (!propertyIsEnumerable.call(current, key)) break;\n if (itemCount >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {\n truncated = true;\n break;\n }\n const converted = convert(current[key], depth + 1);\n Object.defineProperty(output, key, {\n value: converted,\n enumerable: true,\n configurable: true,\n writable: true\n });\n itemCount++;\n }\n if (truncated) output[TRUNCATED_VALUE] = 'Additional properties omitted';\n return output;\n } finally{\n state.ancestors.delete(current);\n }\n } catch {\n return UNSERIALIZABLE_VALUE;\n }\n };\n return convert(value, 0);\n}\nexport { CIRCULAR_VALUE, FUNCTION_VALUE, MAX_JSON_SAFE_VALUE_DEPTH, MAX_JSON_SAFE_VALUE_ITEMS, MAX_JSON_SAFE_VALUE_NODES, TRUNCATED_VALUE, UNSERIALIZABLE_VALUE, sanitizeString, toJsonSafeValue };\n","const DEFAULT_BLOCKED_UA_STRS = [\n 'amazonbot',\n 'amazonproductbot',\n 'app.hypefactors.com',\n 'applebot',\n 'archive.org_bot',\n 'awariobot',\n 'backlinksextendedbot',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'dataforseobot',\n 'deepscan',\n 'duckduckbot',\n 'facebookexternal',\n 'facebookcatalog',\n 'http://yandex.com/bots',\n 'hubspot',\n 'ia_archiver',\n 'leikibot',\n 'linkedinbot',\n 'meta-externalagent',\n 'mj12bot',\n 'msnbot',\n 'nessus',\n 'petalbot',\n 'pinterest',\n 'prerender',\n 'rogerbot',\n 'screaming frog',\n 'sebot-wa',\n 'sitebulb',\n 'slackbot',\n 'slurp',\n 'trendictionbot',\n 'turnitin',\n 'twitterbot',\n 'vercel-screenshot',\n 'vercelbot',\n 'yahoo! slurp',\n 'yandexbot',\n 'zoombot',\n 'bot.htm',\n 'bot.php',\n '(bot;',\n 'bot/',\n 'crawler',\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'semrushbot',\n 'siteauditbot',\n 'splitsignalbot',\n 'gptbot',\n 'oai-searchbot',\n 'chatgpt-user',\n 'perplexitybot',\n 'better uptime bot',\n 'sentryuptimebot',\n 'uptimerobot',\n 'headlesschrome',\n 'cypress',\n 'google-hoteladsverifier',\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleother',\n 'google-cloudvertexbot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google',\n 'google-inspectiontool',\n 'bytespider'\n];\nconst isBlockedUA = function(ua, customBlockedUserAgents = []) {\n if (!ua) return false;\n const uaLower = ua.toLowerCase();\n return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA)=>{\n const blockedUaLower = blockedUA.toLowerCase();\n return -1 !== uaLower.indexOf(blockedUaLower);\n });\n};\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA };\n","function includes(str, needle) {\n return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n return [\n 'distinct_id',\n 'distinctid'\n ].includes(value.toLowerCase());\n}\nfunction safeJsonStringify(value) {\n const ancestors = [];\n return JSON.stringify(value, function(_key, replacementValue) {\n if ('bigint' == typeof replacementValue) return replacementValue.toString();\n if ('function' == typeof replacementValue || 'symbol' == typeof replacementValue) return;\n if (replacementValue instanceof Error) return {\n name: replacementValue.name,\n message: replacementValue.message,\n stack: replacementValue.stack\n };\n if (replacementValue && 'object' == typeof replacementValue) {\n while(ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)ancestors.pop();\n if (ancestors.includes(replacementValue)) return '[Circular]';\n ancestors.push(replacementValue);\n }\n return replacementValue;\n }) ?? 'null';\n}\nfunction deepSortKeys(value) {\n if (null === value || 'object' != typeof value) return value;\n if (Array.isArray(value)) return value.map(deepSortKeys);\n return Object.keys(value).sort().reduce((acc, key)=>{\n acc[key] = deepSortKeys(value[key]);\n return acc;\n }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n return JSON.stringify({\n distinct_id,\n userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, safeJsonStringify, stripLeadingDollar, trim };\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n if (min > max) {\n logger.warn('min cannot be greater than max.');\n min = max;\n }\n if (isNumber(value)) if (value > max) {\n logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');\n return max;\n } else {\n if (!(value < min)) return value;\n logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n return min;\n }\n logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n if (null == field) return defaultValue;\n if ('boolean' == typeof field) return field;\n if ('object' == typeof field) {\n const value = field[key];\n return 'boolean' == typeof value ? value : defaultValue;\n }\n return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n if (null == field || 'object' != typeof field) return;\n const value = field[key];\n if ('number' == typeof value && Number.isFinite(value)) return value;\n if ('string' == typeof value) {\n const trimmed = value.trim();\n if ('' === trimmed) return;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : void 0;\n }\n}\nfunction isValidSampleRate(value) {\n return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n","import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;\nfunction resolveExceptionRateLimiterConfig(config = {}) {\n return {\n refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,\n bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE\n };\n}\nclass BucketedRateLimiter {\n constructor(options){\n this._buckets = {};\n this._onBucketRateLimited = options._onBucketRateLimited;\n this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n }\n _applyRefill(bucket, now) {\n const elapsedMs = now - bucket.lastAccess;\n const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n if (refillIntervals > 0) {\n const tokensToAdd = refillIntervals * this._refillRate;\n bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n }\n }\n consumeRateLimit(key) {\n const now = Date.now();\n const keyStr = String(key);\n let bucket = this._buckets[keyStr];\n if (bucket) this._applyRefill(bucket, now);\n else {\n bucket = {\n tokens: this._bucketSize,\n lastAccess: now\n };\n this._buckets[keyStr] = bucket;\n }\n if (0 === bucket.tokens) return true;\n bucket.tokens--;\n if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n return 0 === bucket.tokens;\n }\n stop() {\n this._buckets = {};\n }\n}\nexport { BucketedRateLimiter, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE, resolveExceptionRateLimiterConfig };\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n */ const DIGITS = \"0123456789abcdef\";\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n }\n static ofInner(bytes) {\n if (16 === bytes.length) return new UUID(bytes);\n throw new TypeError(\"not 128-bit length\");\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError(\"invalid field value\");\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n static parse(uuid) {\n let hex;\n switch(uuid.length){\n case 32:\n hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];\n break;\n case 36:\n 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(\"\");\n break;\n case 38:\n 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(\"\");\n break;\n case 45:\n 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(\"\");\n break;\n default:\n break;\n }\n if (hex) {\n const inner = new Uint8Array(16);\n for(let i = 0; i < 16; i += 4){\n const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);\n inner[i + 0] = n >>> 24;\n inner[i + 1] = n >>> 16;\n inner[i + 2] = n >>> 8;\n inner[i + 3] = n;\n }\n return new UUID(inner);\n }\n throw new SyntaxError(\"could not parse UUID string\");\n }\n toString() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += \"-\";\n }\n return text;\n }\n toHex() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n }\n return text;\n }\n toJSON() {\n return this.toString();\n }\n getVariant() {\n const n = this.bytes[8] >>> 4;\n if (n < 0) throw new Error(\"unreachable\");\n if (n <= 7) return this.bytes.every((e)=>0 === e) ? \"NIL\" : \"VAR_0\";\n if (n <= 11) return \"VAR_10\";\n if (n <= 13) return \"VAR_110\";\n if (n <= 15) return this.bytes.every((e)=>0xff === e) ? \"MAX\" : \"VAR_RESERVED\";\n else throw new Error(\"unreachable\");\n }\n getVersion() {\n return \"VAR_10\" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n constructor(randomNumberGenerator){\n this.timestamp = 0;\n this.counter = 0;\n this.random = randomNumberGenerator ?? getDefaultRandom();\n }\n generate() {\n return this.generateOrResetCore(Date.now(), 10000);\n }\n generateOrAbort() {\n return this.generateOrAbortCore(Date.now(), 10000);\n }\n generateOrResetCore(unixTsMs, rollbackAllowance) {\n let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n if (void 0 === value) {\n this.timestamp = 0;\n value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n }\n return value;\n }\n generateOrAbortCore(unixTsMs, rollbackAllowance) {\n const MAX_COUNTER = 0x3ffffffffff;\n if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 0xffffffffffff) throw new RangeError(\"`unixTsMs` must be a 48-bit positive integer\");\n if (rollbackAllowance < 0 || rollbackAllowance > 0xffffffffffff) throw new RangeError(\"`rollbackAllowance` out of reasonable range\");\n if (unixTsMs > this.timestamp) {\n this.timestamp = unixTsMs;\n this.resetCounter();\n } else {\n if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;\n this.counter++;\n if (this.counter > MAX_COUNTER) {\n this.timestamp++;\n this.resetCounter();\n }\n }\n return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());\n }\n resetCounter() {\n this.counter = 0x400 * this.random.nextUint32() + (0x3ff & this.random.nextUint32());\n }\n generateV4() {\n const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);\n bytes[6] = 0x40 | bytes[6] >>> 4;\n bytes[8] = 0x80 | bytes[8] >>> 2;\n return UUID.ofInner(bytes);\n }\n}\nconst getDefaultRandom = ()=>({\n nextUint32: ()=>0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random())\n });\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuidv4 = ()=>uuidv4obj().toString();\nconst uuidv4obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generateV4();\nexport { UUID, V7Generator, uuidv4, uuidv4obj, uuidv7, uuidv7obj };\n","import { uuidv7 } from \"../vendor/uuidv7.mjs\";\nclass PromiseQueue {\n add(promise) {\n const promiseUUID = uuidv7();\n const id = ++this.nextId;\n this.promiseByIds[promiseUUID] = {\n id,\n promise\n };\n promise.catch(()=>{}).finally(()=>{\n delete this.promiseByIds[promiseUUID];\n });\n return promise;\n }\n async join() {\n let promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n let length = promises.length;\n while(length > 0){\n await Promise.all(promises);\n promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n length = promises.length;\n }\n }\n getPromises(ignoredPromises = [], maxId = this.nextId) {\n const ignoredPromiseSet = new Set(ignoredPromises);\n return Object.values(this.promiseByIds).filter((item)=>item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item)=>item.promise);\n }\n get maxId() {\n return this.nextId;\n }\n get length() {\n return Object.keys(this.promiseByIds).length;\n }\n constructor(){\n this.promiseByIds = {};\n this.nextId = 0;\n }\n}\nexport { PromiseQueue };\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { includes } from \"./string-utils.mjs\";\nimport { isFunction, isUndefined } from \"./type-utils.mjs\";\nconst FACEBOOK = 'Facebook';\nconst MOBILE = 'Mobile';\nconst IOS = 'iOS';\nconst ANDROID = 'Android';\nconst TABLET = 'Tablet';\nconst ANDROID_TABLET = ANDROID + ' ' + TABLET;\nconst IPAD = 'iPad';\nconst APPLE = 'Apple';\nconst APPLE_WATCH = APPLE + ' Watch';\nconst SAFARI = 'Safari';\nconst BLACKBERRY = 'BlackBerry';\nconst SAMSUNG = 'Samsung';\nconst SAMSUNG_BROWSER = SAMSUNG + 'Browser';\nconst SAMSUNG_INTERNET = SAMSUNG + ' Internet';\nconst CHROME = 'Chrome';\nconst CHROME_OS = CHROME + ' OS';\nconst CHROME_IOS = CHROME + ' ' + IOS;\nconst INTERNET_EXPLORER = 'Internet Explorer';\nconst INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;\nconst OPERA = 'Opera';\nconst OPERA_MINI = OPERA + ' Mini';\nconst EDGE = 'Edge';\nconst MICROSOFT_EDGE = 'Microsoft ' + EDGE;\nconst FIREFOX = 'Firefox';\nconst FIREFOX_IOS = FIREFOX + ' ' + IOS;\nconst NINTENDO = 'Nintendo';\nconst PLAYSTATION = 'PlayStation';\nconst XBOX = 'Xbox';\nconst ANDROID_MOBILE = ANDROID + ' ' + MOBILE;\nconst MOBILE_SAFARI = MOBILE + ' ' + SAFARI;\nconst WINDOWS = 'Windows';\nconst WINDOWS_PHONE = WINDOWS + ' Phone';\nconst NOKIA = 'Nokia';\nconst OUYA = 'Ouya';\nconst GENERIC = 'Generic';\nconst GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();\nconst GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();\nconst KONQUEROR = 'Konqueror';\nconst OCULUS_BROWSER = 'Oculus Browser';\nconst VIVALDI = 'Vivaldi';\nconst YANDEX = 'Yandex';\nconst WHALE = 'Whale';\nconst DUCKDUCKGO = 'DuckDuckGo';\nconst PALE_MOON = 'Pale Moon';\nconst WATERFOX = 'Waterfox';\nconst BRAVE = 'Brave';\nconst GOOGLE_SEARCH_APP = 'Google Search App';\nconst BROWSER_VERSION_REGEX_SUFFIX = '(\\\\d+(\\\\.\\\\d+)?)';\nconst DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);\nfunction browserFromHints(hints) {\n if (hints?.brave) return BRAVE;\n return null;\n}\nconst XBOX_REGEX = new RegExp(XBOX, 'i');\nconst PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\\\w+', 'i');\nconst NINTENDO_REGEX = new RegExp(NINTENDO + ' \\\\w+', 'i');\nconst BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');\nconst windowsVersionMap = {\n 'NT3.51': 'NT 3.11',\n 'NT4.0': 'NT 4.0',\n '5.0': '2000',\n '5.1': 'XP',\n '5.2': 'XP',\n '6.0': 'Vista',\n '6.1': '7',\n '6.2': '8',\n '6.3': '8.1',\n '6.4': '10',\n '10.0': '10'\n};\nfunction isSafari(userAgent) {\n return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);\n}\nconst safariCheck = (ua, vendor)=>vendor && includes(vendor, APPLE) || isSafari(ua);\nconst detectBrowser = function(user_agent, vendor, hints, options) {\n vendor = vendor || '';\n const fromHints = browserFromHints(hints);\n if (fromHints) return fromHints;\n if (options?.detectGoogleSearchApp && includes(user_agent, 'GSA/')) return GOOGLE_SEARCH_APP;\n if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) return OPERA_MINI;\n if (includes(user_agent, ' OPR/')) return OPERA;\n if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) return INTERNET_EXPLORER_MOBILE;\n if (includes(user_agent, 'OculusBrowser')) return OCULUS_BROWSER;\n else if (includes(user_agent, SAMSUNG_BROWSER)) return SAMSUNG_INTERNET;\n else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) return MICROSOFT_EDGE;\n else if (includes(user_agent, VIVALDI + '/')) return VIVALDI;\n else if (includes(user_agent, 'YaBrowser/')) return YANDEX;\n else if (includes(user_agent, WHALE + '/')) return WHALE;\n else if (includes(user_agent, DUCKDUCKGO + '/') || includes(user_agent, 'Ddg/')) return DUCKDUCKGO;\n else if (includes(user_agent, 'FBIOS')) return FACEBOOK + ' ' + MOBILE;\n else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) return 'UC Browser';\n else if (includes(user_agent, 'CriOS')) return CHROME_IOS;\n else if (includes(user_agent, 'CrMo')) return CHROME;\n else if (includes(user_agent, CHROME)) return CHROME;\n else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) return ANDROID_MOBILE;\n else if (includes(user_agent, 'FxiOS')) return FIREFOX_IOS;\n else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) return KONQUEROR;\n else if (includes(user_agent, BRAVE + '/')) return BRAVE;\n else if (safariCheck(user_agent, vendor)) return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;\n else if (includes(user_agent, 'PaleMoon/')) return PALE_MOON;\n else if (includes(user_agent, WATERFOX + '/')) return WATERFOX;\n else if (includes(user_agent, FIREFOX)) return FIREFOX;\n else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) return INTERNET_EXPLORER;\n else if (includes(user_agent, 'Gecko')) return FIREFOX;\n return '';\n};\nconst versionRegexes = {\n [INTERNET_EXPLORER_MOBILE]: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [MICROSOFT_EDGE]: [\n new RegExp(EDGE + '?\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME]: [\n new RegExp('(' + CHROME + '|CrMo)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME_IOS]: [\n new RegExp('CriOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n 'UC Browser': [\n new RegExp('(UCBrowser|UCWEB)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [MOBILE_SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [OPERA]: [\n new RegExp('(' + OPERA + '|OPR)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX]: [\n new RegExp(FIREFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX_IOS]: [\n new RegExp('FxiOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [KONQUEROR]: [\n new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [BLACKBERRY]: [\n new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX),\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [ANDROID_MOBILE]: [\n new RegExp('android\\\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [SAMSUNG_INTERNET]: [\n new RegExp(SAMSUNG_BROWSER + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [OCULUS_BROWSER]: [\n new RegExp('OculusBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [VIVALDI]: [\n new RegExp(VIVALDI + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [YANDEX]: [\n new RegExp('YaBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WHALE]: [\n new RegExp(WHALE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [BRAVE]: [\n new RegExp(BRAVE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [DUCKDUCKGO]: [\n new RegExp('(DuckDuckGo|Ddg)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [PALE_MOON]: [\n new RegExp('PaleMoon\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WATERFOX]: [\n new RegExp(WATERFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [GOOGLE_SEARCH_APP]: [\n new RegExp('GSA\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [INTERNET_EXPLORER]: [\n new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n Mozilla: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ]\n};\nconst detectBrowserVersion = function(userAgent, vendor, hints, options) {\n const browser = detectBrowser(userAgent, vendor, hints, options);\n const regexes = versionRegexes[browser];\n if (isUndefined(regexes)) return null;\n for(let i = 0; i < regexes.length; i++){\n const regex = regexes[i];\n const matches = userAgent.match(regex);\n if (matches) return parseFloat(matches[matches.length - 2]);\n }\n return null;\n};\nconst osMatchers = [\n [\n new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'),\n (match)=>[\n XBOX,\n match && match[1] || ''\n ]\n ],\n [\n new RegExp(NINTENDO, 'i'),\n [\n NINTENDO,\n ''\n ]\n ],\n [\n new RegExp(PLAYSTATION, 'i'),\n [\n PLAYSTATION,\n ''\n ]\n ],\n [\n BLACKBERRY_REGEX,\n [\n BLACKBERRY,\n ''\n ]\n ],\n [\n new RegExp(WINDOWS, 'i'),\n (_, user_agent)=>{\n if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [\n WINDOWS_PHONE,\n ''\n ];\n if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\\b/.test(user_agent)) return [\n WINDOWS + ' ' + MOBILE,\n ''\n ];\n const match = /Windows NT ([0-9.]+)/i.exec(user_agent);\n if (match && match[1]) {\n const version = match[1];\n let osVersion = windowsVersionMap[version] || '';\n if (/arm/i.test(user_agent)) osVersion = 'RT';\n return [\n WINDOWS,\n osVersion\n ];\n }\n return [\n WINDOWS,\n ''\n ];\n }\n ],\n [\n /((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,\n (match)=>{\n if (match && match[3]) {\n const versionParts = [\n match[3],\n match[4],\n match[5] || '0'\n ];\n return [\n IOS,\n versionParts.join('.')\n ];\n }\n return [\n IOS,\n ''\n ];\n }\n ],\n [\n /(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,\n (match)=>{\n let version = '';\n if (match && match.length >= 3) version = isUndefined(match[2]) ? match[3] : match[2];\n return [\n 'watchOS',\n version\n ];\n }\n ],\n [\n new RegExp('(' + ANDROID + ' (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|' + ANDROID + ')', 'i'),\n (match)=>{\n if (match && match[2]) {\n const versionParts = [\n match[2],\n match[3],\n match[4] || '0'\n ];\n return [\n ANDROID,\n versionParts.join('.')\n ];\n }\n return [\n ANDROID,\n ''\n ];\n }\n ],\n [\n /Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,\n (match)=>{\n const result = [\n 'Mac OS X',\n ''\n ];\n if (match && match[1]) {\n const versionParts = [\n match[1],\n match[2],\n match[3] || '0'\n ];\n result[1] = versionParts.join('.');\n }\n return result;\n }\n ],\n [\n /Mac/i,\n [\n 'Mac OS X',\n ''\n ]\n ],\n [\n /CrOS/,\n [\n CHROME_OS,\n ''\n ]\n ],\n [\n /Linux|debian/i,\n [\n 'Linux',\n ''\n ]\n ]\n];\nconst detectOS = function(user_agent) {\n for(let i = 0; i < osMatchers.length; i++){\n const [rgex, resultOrFn] = osMatchers[i];\n const match = rgex.exec(user_agent);\n const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);\n if (result) return result;\n }\n return [\n '',\n ''\n ];\n};\nconst detectDevice = function(user_agent) {\n if (NINTENDO_REGEX.test(user_agent)) return NINTENDO;\n if (PLAYSTATION_REGEX.test(user_agent)) return PLAYSTATION;\n if (XBOX_REGEX.test(user_agent)) return XBOX;\n if (new RegExp(OUYA, 'i').test(user_agent)) return OUYA;\n if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) return WINDOWS_PHONE;\n else if (/iPad/.test(user_agent)) return IPAD;\n else if (/iPod/.test(user_agent)) return 'iPod Touch';\n else if (/iPhone/.test(user_agent)) return 'iPhone';\n else if (/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(user_agent)) return APPLE_WATCH;\n else if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n else if (/(kobo)\\s(ereader|touch)/i.test(user_agent)) return 'Kobo';\n else if (new RegExp(NOKIA, 'i').test(user_agent)) return NOKIA;\n else if (/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(user_agent) || /(kf[a-z]+)( bui|\\)).+silk\\//i.test(user_agent)) return 'Kindle Fire';\n else if (/(Android|ZTE)/i.test(user_agent)) if (!(!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent))) return ANDROID;\n else {\n if (/pixel[\\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) return ANDROID;\n return ANDROID_TABLET;\n }\n else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) return GENERIC_MOBILE;\n else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) return GENERIC_TABLET;\n else return '';\n};\nconst detectDeviceType = function(user_agent, options) {\n const device = detectDevice(user_agent);\n if (device === IPAD || device === ANDROID_TABLET || 'Kobo' === device || 'Kindle Fire' === device || device === GENERIC_TABLET) return TABLET;\n if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) return 'Console';\n if (device === APPLE_WATCH) return 'Wearable';\n if (device) return MOBILE;\n if (options?.userAgentDataPlatform === 'Android' && (options?.maxTouchPoints ?? 0) > 0) {\n const shortSide = Math.min(options?.screenWidth ?? 0, options?.screenHeight ?? 0);\n const shortSideDp = shortSide / (options?.devicePixelRatio ?? 1);\n return shortSideDp >= 600 ? TABLET : MOBILE;\n }\n return 'Desktop';\n};\nexport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS };\n","import { toJsonSafeValue } from \"./json-utils.mjs\";\nexport * from \"./bot-detection.mjs\";\nexport * from \"./browser-utils.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isValidUUID(value) {\n return 'string' == typeof value && UUID_REGEX.test(value);\n}\nfunction getEventUuid(uuid, generateUuid) {\n return isValidUUID(uuid) ? uuid : generateUuid();\n}\nfunction assert(truthyValue, message) {\n if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n if (0 === truthyValue.trim().length) return true;\n return false;\n}\nfunction removeTrailingSlash(url) {\n return url?.replace(/\\/+$/, '');\n}\nfunction stripUrlHash(url) {\n if (!url) return url;\n return url.split('#')[0];\n}\nasync function retriable(fn, props) {\n let lastError = null;\n for(let i = 0; i < props.retryCount + 1; i++){\n if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n try {\n const res = await fn();\n return res;\n } catch (e) {\n lastError = e;\n if (!props.retryCheck(e)) throw e;\n }\n }\n throw lastError;\n}\nfunction currentTimestamp() {\n return new Date().getTime();\n}\nfunction currentISOTime() {\n return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n const t = setTimeout(fn, timeout);\n t?.unref && t?.unref();\n return t;\n}\nasync function raceWithTimeout(promise, timeoutMs, onTimeout) {\n let timeoutHandle;\n try {\n return await Promise.race([\n promise,\n new Promise((resolve, reject)=>{\n timeoutHandle = safeSetTimeout(()=>{\n try {\n onTimeout?.();\n resolve();\n } catch (error) {\n reject(error);\n }\n }, timeoutMs);\n })\n ]);\n } finally{\n clearTimeout(timeoutHandle);\n }\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nfunction getFetch() {\n return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n status: 'fulfilled',\n value\n }), (reason)=>({\n status: 'rejected',\n reason\n }))));\n}\nexport { STRING_FORMAT, UUID_REGEX, allSettled, assert, currentISOTime, currentTimestamp, getEventUuid, getFetch, isPromise, isValidUUID, raceWithTimeout, removeTrailingSlash, retriable, safeSetTimeout, stripUrlHash, toJsonSafeValue };\n","import { isArray, isBoolean, isNull, isNullish, isUndefined } from \"../utils/index.mjs\";\nimport { CIRCULAR_VALUE, FUNCTION_VALUE, MAX_JSON_SAFE_VALUE_DEPTH, MAX_JSON_SAFE_VALUE_ITEMS, MAX_JSON_SAFE_VALUE_NODES, TRUNCATED_VALUE, UNSERIALIZABLE_VALUE, sanitizeString } from \"../utils/json-utils.mjs\";\nconst OTLP_SEVERITY_MAP = {\n trace: {\n text: 'TRACE',\n number: 1\n },\n debug: {\n text: 'DEBUG',\n number: 5\n },\n info: {\n text: 'INFO',\n number: 9\n },\n warn: {\n text: 'WARN',\n number: 13\n },\n error: {\n text: 'ERROR',\n number: 17\n },\n fatal: {\n text: 'FATAL',\n number: 21\n }\n};\nconst DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;\nfunction getOtlpSeverityText(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).text;\n}\nfunction getOtlpSeverityNumber(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number;\n}\nconst INT64_RANGE_LIMIT = 9223372036854775808;\nconst propertyIsEnumerable = Object.prototype.propertyIsEnumerable;\nfunction newState() {\n return {\n ancestors: new WeakSet(),\n remainingNodes: MAX_JSON_SAFE_VALUE_NODES\n };\n}\nfunction toOtlpAnyValue(value, logger) {\n try {\n return encodeAnyValue(value, logger, newState(), 0);\n } catch {\n return {\n stringValue: UNSERIALIZABLE_VALUE\n };\n }\n}\nfunction toOtlpKeyValueList(attrs, logger) {\n try {\n return encodeKeyValueList(attrs, logger, newState(), 0);\n } catch {\n return [];\n }\n}\nfunction encodeAnyValue(value, logger, state, depth) {\n if (state.remainingNodes <= 0) return {\n stringValue: TRUNCATED_VALUE\n };\n state.remainingNodes--;\n if (isBoolean(value)) return {\n boolValue: value\n };\n if ('number' == typeof value) {\n if (!Number.isFinite(value)) return {\n stringValue: String(value)\n };\n if (Number.isInteger(value)) {\n if (Number.isSafeInteger(value)) return {\n intValue: String(value)\n };\n if ('undefined' == typeof BigInt) return {\n stringValue: String(value)\n };\n const decimal = BigInt(value).toString();\n if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {\n logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);\n return {\n stringValue: decimal\n };\n }\n return {\n intValue: decimal\n };\n }\n return {\n doubleValue: value\n };\n }\n if ('string' == typeof value) return {\n stringValue: sanitizeString(value)\n };\n if ('function' == typeof value) return {\n stringValue: FUNCTION_VALUE\n };\n if ('symbol' == typeof value) return {\n stringValue: String(value)\n };\n if ('object' == typeof value && null !== value) {\n if (state.ancestors.has(value)) return {\n stringValue: CIRCULAR_VALUE\n };\n if (depth >= MAX_JSON_SAFE_VALUE_DEPTH) return {\n stringValue: TRUNCATED_VALUE\n };\n if (value instanceof Date) {\n const time = value.getTime();\n const iso = Number.isFinite(time) ? value.toISOString() : String(value);\n return {\n stringValue: 'string' == typeof iso ? sanitizeString(iso) : String(iso)\n };\n }\n state.ancestors.add(value);\n try {\n try {\n const toJSON = value.toJSON;\n if ('function' == typeof toJSON) return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);\n } catch {}\n if (isArray(value)) return {\n arrayValue: {\n values: encodeArrayValues(value, logger, state, depth + 1)\n }\n };\n return {\n kvlistValue: {\n values: encodeKeyValueList(value, logger, state, depth + 1)\n }\n };\n } finally{\n state.ancestors.delete(value);\n }\n }\n return {\n stringValue: sanitizeString(String(value))\n };\n}\nfunction encodeArrayValues(values, logger, state, depth) {\n const result = [];\n const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);\n let index = 0;\n for(; index < itemCount && state.remainingNodes > 0; index++)try {\n const element = index in values ? values[index] : void 0;\n if (isNullish(element)) continue;\n result.push(encodeAnyValue(element, logger, state, depth));\n } catch {\n result.push({\n stringValue: UNSERIALIZABLE_VALUE\n });\n }\n if (values.length > index) result.push({\n stringValue: TRUNCATED_VALUE\n });\n return result;\n}\nfunction encodeKeyValueList(attrs, logger, state, depth) {\n const result = [];\n for(const key in attrs)if (propertyIsEnumerable.call(attrs, key)) {\n if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {\n logger?.debug('Attributes truncated: the value exceeds the OTLP encoder budget');\n break;\n }\n try {\n const value = attrs[key];\n if (isNull(value) || isUndefined(value)) continue;\n result.push({\n key: sanitizeString(key),\n value: encodeAnyValue(value, logger, state, depth)\n });\n } catch {\n result.push({\n key: sanitizeString(key),\n value: {\n stringValue: UNSERIALIZABLE_VALUE\n }\n });\n }\n }\n return result;\n}\nfunction timestampToUnixNano() {\n return String(Date.now()) + '000000';\n}\nfunction encodeBody(body) {\n try {\n return sanitizeString(String(body));\n } catch {\n return UNSERIALIZABLE_VALUE;\n }\n}\nfunction buildOtlpLogRecord(options, sdkContext, logger) {\n const level = options.level || 'info';\n const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY;\n const now = timestampToUnixNano();\n const autoAttributes = {};\n if (sdkContext.distinctId) autoAttributes.posthogDistinctId = sdkContext.distinctId;\n if (sdkContext.sessionId) autoAttributes.sessionId = sdkContext.sessionId;\n if (sdkContext.windowId) autoAttributes['window.id'] = sdkContext.windowId;\n if (!isNullish(sdkContext.sessionStartTimestamp)) autoAttributes.sessionStartTimestamp = String(sdkContext.sessionStartTimestamp);\n if (!isNullish(sdkContext.lastActivityTimestamp)) autoAttributes.lastActivityTimestamp = String(sdkContext.lastActivityTimestamp);\n if (sdkContext.currentUrl) autoAttributes['url.full'] = sdkContext.currentUrl;\n if (sdkContext.screenName) autoAttributes['screen.name'] = sdkContext.screenName;\n if (sdkContext.appState) autoAttributes['app.state'] = sdkContext.appState;\n if (sdkContext.activeFeatureFlags && sdkContext.activeFeatureFlags.length > 0) autoAttributes.feature_flags = sdkContext.activeFeatureFlags;\n const mergedAttributes = {\n ...autoAttributes\n };\n const userAttributes = options.attributes;\n if (userAttributes) {\n let keys = [];\n try {\n keys = Object.keys(userAttributes);\n } catch {\n keys = [];\n }\n for (const key of keys){\n let value;\n try {\n value = userAttributes[key];\n } catch {\n value = UNSERIALIZABLE_VALUE;\n }\n Object.defineProperty(mergedAttributes, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true\n });\n }\n }\n const record = {\n timeUnixNano: now,\n observedTimeUnixNano: now,\n severityNumber,\n severityText,\n body: {\n stringValue: encodeBody(options.body)\n },\n attributes: toOtlpKeyValueList(mergedAttributes, logger)\n };\n if (options.trace_id) record.traceId = options.trace_id;\n if (options.span_id) record.spanId = options.span_id;\n if (!isUndefined(options.trace_flags)) record.flags = options.trace_flags;\n return record;\n}\nfunction buildResourceAttributes(config, sdkName, sdkVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': sdkName,\n 'telemetry.sdk.version': sdkVersion\n };\n}\nfunction buildOtlpLogsPayload(logRecords, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceLogs: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeLogs: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n logRecords\n }\n ]\n }\n ]\n };\n}\nexport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList };\n","import { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nconst DEFAULT_HISTOGRAM_BOUNDS = [\n 0,\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000\n];\nfunction msToUnixNano(ms) {\n return String(ms) + '000000';\n}\nfunction seriesKey(type, name, unit, attributes) {\n let attrsKey = '';\n if (attributes) {\n const keys = Object.keys(attributes).sort();\n attrsKey = keys.map((k)=>`${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(',');\n }\n return `${type}\\u0000${name}\\u0000${unit ?? ''}\\u0000${attrsKey}`;\n}\nfunction bucketIndexFor(value, bounds) {\n for(let i = 0; i < bounds.length; i++)if (value <= bounds[i]) return i;\n return bounds.length;\n}\nfunction buildMetricsResourceAttributes(config, scopeName, scopeVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': scopeName,\n 'telemetry.sdk.version': scopeVersion\n };\n}\nfunction buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceMetrics: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeMetrics: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n metrics\n }\n ]\n }\n ]\n };\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey };\n","const DEFAULT_FLUSH_INTERVAL_MS = 10000;\nconst DEFAULT_MAX_SERIES_PER_FLUSH = 1000;\nfunction resolveMetricsConfig(config) {\n const resourceAttributes = config?.resourceAttributes;\n return {\n serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,\n serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,\n environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,\n resourceAttributes,\n beforeSend: config?.beforeSend,\n flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH\n };\n}\nexport { resolveMetricsConfig };\n","import { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nimport { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey } from \"./metrics-utils.mjs\";\nimport { resolveMetricsConfig } from \"./config.mjs\";\nconst OTLP_TEMPORALITY_DELTA = 1;\nclass PostHogMetrics {\n constructor(_instance, _config, _logger){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n this._generation = 0;\n }\n count(name, value = 1, options) {\n this._capture({\n name,\n type: 'count',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n gauge(name, value, options) {\n this._capture({\n name,\n type: 'gauge',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n histogram(name, value, options) {\n this._capture({\n name,\n type: 'histogram',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n flush() {\n const prev = this._flushPromise;\n const run = async ()=>{\n if (prev) await prev.catch(()=>{});\n await this._doFlush();\n };\n const p = run().finally(()=>{\n if (this._flushPromise === p) this._flushPromise = null;\n });\n this._flushPromise = p;\n return p;\n }\n drainWindow() {\n if (0 === this._series.size) return null;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n return this._buildPayload(window);\n }\n reset() {\n this._generation++;\n this._clearFlushTimer();\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n }\n _capture(sample) {\n if (this._instance.isDisabled || this._instance.optedOut) return;\n const filtered = this._runBeforeSend(sample);\n if (null === filtered) return;\n if (!filtered.name || 'string' != typeof filtered.name) return void this._logger.warn('Dropping metric with empty name');\n if ('number' != typeof filtered.value || !Number.isFinite(filtered.value)) return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);\n if ('count' === filtered.type && filtered.value < 0) return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);\n let attributes;\n let key;\n try {\n attributes = filtered.attributes ? {\n ...filtered.attributes\n } : void 0;\n key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);\n } catch (e) {\n this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);\n return;\n }\n let state = this._series.get(key);\n if (!state) {\n if (!this._admitNewSeries()) return;\n state = {\n name: filtered.name,\n type: filtered.type,\n unit: filtered.unit,\n attributes,\n windowStartMs: Date.now()\n };\n this._series.set(key, state);\n }\n const seenType = this._typeByName.get(filtered.name);\n if (void 0 === seenType) this._typeByName.set(filtered.name, filtered.type);\n else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {\n this._typeCollisionWarned.add(filtered.name);\n this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);\n }\n this._fold(state, filtered.value);\n this._armFlushTimer();\n }\n _admitNewSeries() {\n if (this._series.size < this._config.maxSeriesPerFlush) return true;\n if (!this._seriesCapWarned) {\n this._seriesCapWarned = true;\n this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);\n }\n return false;\n }\n _fold(state, value) {\n switch(state.type){\n case 'count':\n state.total = (state.total ?? 0) + value;\n break;\n case 'gauge':\n state.last = value;\n break;\n case 'histogram':\n {\n if (!state.hist) state.hist = {\n count: 0,\n sum: 0,\n min: value,\n max: value,\n bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)\n };\n const hist = state.hist;\n hist.count += 1;\n hist.sum += value;\n hist.min = Math.min(hist.min, value);\n hist.max = Math.max(hist.max, value);\n hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;\n break;\n }\n }\n }\n _runBeforeSend(sample) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return sample;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = sample;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Metric was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for metric:\", e);\n return null;\n }\n return result;\n }\n _armFlushTimer() {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this.flush().catch((e)=>{\n this._logger.error('Metrics flush failed:', e);\n });\n }, this._config.flushIntervalMs);\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n async _doFlush() {\n if (0 === this._series.size) return;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n const generation = this._generation;\n const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));\n if (generation !== this._generation) return;\n switch(outcome.kind){\n case 'ok':\n return;\n case 'retry-later':\n this._mergeWindowBack(window);\n this._armFlushTimer();\n return;\n case 'too-large':\n this._logger.warn('Metrics batch exceeded the server size limit and was dropped');\n return;\n case 'fatal':\n this._logger.error('Failed to send metrics batch:', outcome.error);\n return;\n }\n }\n _buildPayload(window) {\n return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _buildMetrics(window) {\n const nowNano = msToUnixNano(Date.now());\n const byMetric = new Map();\n for (const state of window.values()){\n const metricKey = seriesKey(state.type, state.name, state.unit, void 0);\n let metric = byMetric.get(metricKey);\n if (!metric) {\n metric = {\n name: state.name,\n ...state.unit && {\n unit: state.unit\n }\n };\n if ('count' === state.type) metric.sum = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n isMonotonic: true,\n dataPoints: []\n };\n else if ('gauge' === state.type) metric.gauge = {\n dataPoints: []\n };\n else metric.histogram = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n dataPoints: []\n };\n byMetric.set(metricKey, metric);\n }\n const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);\n const startNano = msToUnixNano(state.windowStartMs);\n if ('count' === state.type) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n asDouble: state.total ?? 0\n };\n metric.sum.dataPoints.push(dp);\n } else if ('gauge' === state.type) {\n const dp = {\n attributes,\n timeUnixNano: nowNano,\n asDouble: state.last ?? 0\n };\n metric.gauge.dataPoints.push(dp);\n } else if (state.hist) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n count: state.hist.count,\n sum: state.hist.sum,\n min: state.hist.min,\n max: state.hist.max,\n bucketCounts: state.hist.bucketCounts,\n explicitBounds: DEFAULT_HISTOGRAM_BOUNDS\n };\n metric.histogram.dataPoints.push(dp);\n }\n }\n return Array.from(byMetric.values());\n }\n _mergeWindowBack(window) {\n for (const [key, old] of window){\n const current = this._series.get(key);\n if (!current) {\n if (this._admitNewSeries()) this._series.set(key, old);\n continue;\n }\n current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);\n switch(current.type){\n case 'count':\n current.total = (current.total ?? 0) + (old.total ?? 0);\n break;\n case 'gauge':\n break;\n case 'histogram':\n if (old.hist) if (current.hist) {\n current.hist.count += old.hist.count;\n current.hist.sum += old.hist.sum;\n current.hist.min = Math.min(current.hist.min, old.hist.min);\n current.hist.max = Math.max(current.hist.max, old.hist.max);\n for(let i = 0; i < current.hist.bucketCounts.length; i++)current.hist.bucketCounts[i] += old.hist.bucketCounts[i];\n } else current.hist = old.hist;\n break;\n }\n }\n }\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig };\n","class SimpleEventEmitter {\n constructor(){\n this.events = {};\n this.events = {};\n }\n on(event, listener) {\n if (!this.events[event]) this.events[event] = [];\n this.events[event].push(listener);\n return ()=>{\n this.events[event] = this.events[event].filter((x)=>x !== listener);\n };\n }\n emit(event, payload) {\n for (const listener of this.events[event] || [])listener(payload);\n for (const listener of this.events['*'] || [])listener(event, payload);\n }\n}\nexport { SimpleEventEmitter };\n","let parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameChunkIds;\nfunction getFilenameToChunkIdMap(stackParser) {\n const chunkIdMap = globalThis._posthogChunkIds;\n if (!chunkIdMap) return;\n const chunkIdKeys = Object.keys(chunkIdMap);\n if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;\n lastKeysCount = chunkIdKeys.length;\n cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{\n if (!parsedStackResults) parsedStackResults = {};\n const result = parsedStackResults[stackKey];\n if (result) acc[result[0]] = result[1];\n else {\n const parsedStack = stackParser(stackKey);\n for(let i = parsedStack.length - 1; i >= 0; i--){\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const chunkId = chunkIdMap[stackKey];\n if (filename && chunkId) {\n acc[filename] = chunkId;\n parsedStackResults[stackKey] = [\n filename,\n chunkId\n ];\n break;\n }\n }\n }\n return acc;\n }, {});\n return cachedFilenameChunkIds;\n}\nexport { getFilenameToChunkIdMap };\n","import { isArray } from \"../utils/index.mjs\";\nimport { getFilenameToChunkIdMap } from \"./chunk-ids.mjs\";\nconst MAX_CAUSE_RECURSION = 4;\nclass ErrorPropertiesBuilder {\n constructor(coercers, stackParser, modifiers = []){\n this.coercers = coercers;\n this.stackParser = stackParser;\n this.modifiers = modifiers;\n }\n buildFromUnknown(input, hint = {}) {\n const providedMechanism = hint && hint.mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic'\n };\n const coercingContext = this.buildCoercingContext(mechanism, hint, 0);\n const exceptionWithCause = coercingContext.apply(input);\n const parsingContext = this.buildParsingContext(hint);\n const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);\n const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);\n return {\n $exception_list: exceptionList,\n $exception_level: 'error'\n };\n }\n async modifyFrames(exceptionList) {\n for (const exc of exceptionList)if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);\n return exceptionList;\n }\n coerceFallback(ctx) {\n return {\n type: 'Error',\n value: 'Unknown error',\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n parseStacktrace(err, ctx) {\n let cause;\n if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);\n let stack;\n if ('' != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);\n return {\n ...err,\n cause,\n stack\n };\n }\n applyChunkIds(frames, chunkIdMap) {\n return frames.map((frame)=>{\n if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];\n return frame;\n });\n }\n applyCoercers(input, ctx) {\n for (const adapter of this.coercers)if (adapter.match(input)) return adapter.coerce(input, ctx);\n return this.coerceFallback(ctx);\n }\n async applyModifiers(frames) {\n let newFrames = frames;\n for (const modifier of this.modifiers)newFrames = await modifier(newFrames);\n return newFrames;\n }\n convertToExceptionList(exceptionWithStack, mechanism) {\n const currentException = {\n type: exceptionWithStack.type,\n value: exceptionWithStack.value,\n mechanism: {\n type: mechanism.type ?? 'generic',\n handled: mechanism.handled ?? true,\n synthetic: exceptionWithStack.synthetic ?? false\n }\n };\n if (exceptionWithStack.stack) currentException.stacktrace = {\n type: 'raw',\n frames: exceptionWithStack.stack\n };\n const exceptionList = [\n currentException\n ];\n if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {\n ...mechanism,\n handled: true\n }));\n return exceptionList;\n }\n buildParsingContext(hint) {\n const context = {\n chunkIdMap: getFilenameToChunkIdMap(this.stackParser),\n skipFirstLines: hint.skipFirstLines ?? 1\n };\n return context;\n }\n buildCoercingContext(mechanism, hint, depth = 0) {\n const coerce = (input, depth)=>{\n if (!(depth <= MAX_CAUSE_RECURSION)) return;\n {\n const ctx = this.buildCoercingContext(mechanism, hint, depth);\n return this.applyCoercers(input, ctx);\n }\n };\n const context = {\n ...hint,\n syntheticException: 0 == depth ? hint.syntheticException : void 0,\n mechanism,\n apply: (input)=>coerce(input, depth),\n next: (input)=>coerce(input, depth + 1)\n };\n return context;\n }\n}\nexport { ErrorPropertiesBuilder };\n","import { isUndefined } from \"../../utils/index.mjs\";\nconst UNKNOWN_FUNCTION = '?';\nconst MASKED_URL_PREFIX = 'webkit-masked-url://';\nconst ANONYMOUS_FILENAME = '<anonymous>';\nfunction createFrame(platform, filename, func, lineno, colno) {\n const frame = {\n platform,\n filename,\n function: '<anonymous>' === func ? UNKNOWN_FUNCTION : func,\n in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME\n };\n if (!isUndefined(lineno)) frame.lineno = lineno;\n if (!isUndefined(colno)) frame.colno = colno;\n return frame;\n}\nexport { UNKNOWN_FUNCTION, createFrame };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst extractSafariExtensionDetails = (func, filename)=>{\n const isSafariExtension = -1 !== func.indexOf('safari-extension');\n const isSafariWebExtension = -1 !== func.indexOf('safari-web-extension');\n return isSafariExtension || isSafariWebExtension ? [\n -1 !== func.indexOf('@') ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`\n ] : [\n func,\n filename\n ];\n};\nexport { extractSafariExtensionDetails };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\nconst chromeRegex = /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\nconst chromeStackLineParser = (line, platform)=>{\n const noFnParts = chromeRegexNoFnName.exec(line);\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);\n }\n const parts = chromeRegex.exec(line);\n if (parts) {\n const isEval = parts[2] && 0 === parts[2].indexOf('eval');\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n if (subMatch) {\n parts[2] = subMatch[1];\n parts[3] = subMatch[2];\n parts[4] = subMatch[3];\n }\n }\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);\n }\n};\nexport { chromeStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst geckoREgex = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst geckoStackLineParser = (line, platform)=>{\n const parts = geckoREgex.exec(line);\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n if (subMatch) {\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = '';\n }\n }\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);\n }\n};\nexport { geckoStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst FILENAME_MATCH = /^\\s*[-]{4,}$/;\nconst FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\nconst PROMISE_COMBINATOR = /^Promise\\.(?:all|any)$/;\nconst PROMISE_INDEX = /^index \\d+$/;\nconst PROMISE_FRAME_FILENAME = 'node:internal/promise';\nconst nodeStackLineParser = (line, platform)=>{\n const lineMatch = line.match(FULL_MATCH);\n if (lineMatch) {\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if ('.' === functionName[methodStart - 1]) methodStart--;\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = void 0;\n }\n if (method) {\n typeName = object;\n methodName = method;\n }\n if ('<anonymous>' === method) {\n methodName = void 0;\n functionName = void 0;\n }\n if (void 0 === functionName) {\n methodName = methodName || UNKNOWN_FUNCTION;\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = 'native' === lineMatch[5];\n if (filename?.match(/\\/[A-Z]:/)) filename = filename.slice(1);\n if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];\n if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || '')) filename = PROMISE_FRAME_FILENAME;\n return {\n filename: filename ? decodeURI(filename) : void 0,\n module: void 0,\n function: functionName,\n lineno: _parseIntOrUndefined(lineMatch[3]),\n colno: _parseIntOrUndefined(lineMatch[4]),\n in_app: filenameIsInApp(filename || '', isNative),\n platform: platform\n };\n }\n if (line.match(FILENAME_MATCH)) return {\n filename: line,\n platform: platform\n };\n};\nfunction filenameIsInApp(filename, isNative = false) {\n const isInternal = isNative || filename && !filename.startsWith('/') && !filename.match(/^[A-Z]:/) && !filename.startsWith('.') && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//);\n return !isInternal && void 0 !== filename && !filename.includes('node_modules/');\n}\nfunction _parseIntOrUndefined(input) {\n return parseInt(input || '', 10) || void 0;\n}\nexport { nodeStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nimport { chromeStackLineParser } from \"./chrome.mjs\";\nimport { geckoStackLineParser } from \"./gecko.mjs\";\nimport { winjsStackLineParser } from \"./winjs.mjs\";\nimport { opera10StackLineParser, opera11StackLineParser } from \"./opera.mjs\";\nimport { nodeStackLineParser } from \"./node.mjs\";\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STACKTRACE_FRAME_LIMIT = 50;\nfunction reverseAndStripFrames(stack) {\n if (!stack.length) return [];\n const localStack = Array.from(stack);\n localStack.reverse();\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame)=>({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION\n }));\n}\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\nfunction createDefaultStackParser() {\n return createStackParser(\"web:javascript\", chromeStackLineParser, geckoStackLineParser);\n}\nfunction createStackParser(platform, ...parsers) {\n return (stack, skipFirstLines = 0)=>{\n const frames = [];\n const lines = stack.split('\\n');\n for(let i = skipFirstLines; i < lines.length; i++){\n const line = lines[i];\n if (line.length > 1024) continue;\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n if (!cleanedLine.match(/\\S*Error: /)) {\n for (const parser of parsers){\n const frame = parser(cleanedLine, platform);\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n if (frames.length >= STACKTRACE_FRAME_LIMIT) break;\n }\n }\n return reverseAndStripFrames(frames);\n };\n}\nexport { chromeStackLineParser, createDefaultStackParser, createStackParser, geckoStackLineParser, nodeStackLineParser, opera10StackLineParser, opera11StackLineParser, reverseAndStripFrames, winjsStackLineParser };\n","import { isError } from \"../../utils/type-utils.mjs\";\nclass ErrorCoercer {\n match(err) {\n return isError(err);\n }\n coerce(err, ctx) {\n const stack = this.getStack(err);\n const synthetic = void 0 === stack;\n return {\n type: this.getType(err),\n value: this.getMessage(err, ctx),\n stack: stack ?? ctx.syntheticException?.stack,\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic\n };\n }\n getType(err) {\n return err.name || err.constructor.name;\n }\n getMessage(err, _ctx) {\n const message = err.message;\n if (message.error && 'string' == typeof message.error.message) return String(message.error.message);\n return String(message);\n }\n getStack(err) {\n return err.stacktrace || err.stack || void 0;\n }\n}\nexport { ErrorCoercer };\n","const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\nclass StringCoercer {\n match(input) {\n return 'string' == typeof input;\n }\n coerce(input, ctx) {\n const [type, value] = this.getInfos(input);\n return {\n type: type ?? 'Error',\n value: value ?? input,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n getInfos(candidate) {\n let type = 'Error';\n let value = candidate;\n const groups = candidate.match(ERROR_TYPES_PATTERN);\n if (groups) {\n type = groups[1];\n value = groups[2];\n }\n return [\n type,\n value\n ];\n }\n}\nexport { StringCoercer };\n","const severityLevels = [\n 'fatal',\n 'error',\n 'warning',\n 'log',\n 'info',\n 'debug'\n];\nexport { severityLevels };\n","function truncate(str, max = 0) {\n if ('string' != typeof str || 0 === max) return str;\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction extractExceptionKeysForMessage(err, maxLength = 40) {\n const keys = Object.keys(err);\n keys.sort();\n if (!keys.length) return '[object has no keys]';\n for(let i = keys.length; i > 0; i--){\n const serialized = keys.slice(0, i).join(', ');\n if (!(serialized.length > maxLength)) {\n if (i === keys.length) return serialized;\n return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;\n }\n }\n return '';\n}\nexport { extractExceptionKeysForMessage, truncate };\n","import { isEmptyString, isError, isEvent, isString } from \"../../utils/index.mjs\";\nimport { severityLevels } from \"../types.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass ObjectCoercer {\n match(candidate) {\n return 'object' == typeof candidate && null !== candidate;\n }\n coerce(candidate, ctx) {\n const errorProperty = this.getErrorPropertyFromObject(candidate);\n if (errorProperty) return ctx.apply(errorProperty);\n return {\n type: this.getType(candidate),\n value: this.getValue(candidate),\n stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,\n level: this.isSeverityLevel(candidate.level) ? candidate.level : 'error',\n synthetic: true\n };\n }\n getType(err) {\n if (isEvent(err)) return err.constructor.name;\n const name = 'name' in err ? err.name : void 0;\n return isString(name) && !isEmptyString(name) ? name : 'Error';\n }\n getValue(err) {\n if ('name' in err && 'string' == typeof err.name) {\n let message = `'${err.name}' captured as exception`;\n if ('message' in err && 'string' == typeof err.message) message += ` with message: '${err.message}'`;\n return message;\n }\n if ('message' in err && 'string' == typeof err.message) return err.message;\n const className = this.getObjectClassName(err);\n const keys = extractExceptionKeysForMessage(err);\n return `${className && 'Object' !== className ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;\n }\n isSeverityLevel(x) {\n return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;\n }\n getStack(candidate) {\n try {\n if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0) return candidate.stacktrace;\n return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : void 0;\n } catch {\n return;\n }\n }\n getErrorPropertyFromObject(obj) {\n for(const prop in obj)if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (isError(value)) return value;\n }\n }\n getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : void 0;\n } catch (e) {\n return;\n }\n }\n}\nexport { ObjectCoercer };\n","import { isEvent } from \"../../utils/index.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass EventCoercer {\n match(err) {\n return isEvent(err);\n }\n coerce(evt, ctx) {\n const constructorName = evt.constructor.name;\n return {\n type: constructorName,\n value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { EventCoercer };\n","import { isPrimitive } from \"../../utils/index.mjs\";\nclass PrimitiveCoercer {\n match(candidate) {\n return isPrimitive(candidate);\n }\n coerce(value, ctx) {\n return {\n type: 'Error',\n value: `Primitive value captured as exception: ${String(value)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { PrimitiveCoercer };\n","class ReduceableCache {\n constructor(_maxSize){\n this._maxSize = _maxSize;\n this._cache = new Map();\n }\n get(key) {\n const value = this._cache.get(key);\n if (void 0 === value) return;\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n set(key, value) {\n this._cache.set(key, value);\n }\n reduce() {\n while(this._cache.size >= this._maxSize){\n const value = this._cache.keys().next().value;\n if (value) this._cache.delete(value);\n }\n }\n}\nexport { ReduceableCache };\n","import { isNumber, isObject, isString, safeJsonStringify } from \"../utils/index.mjs\";\nconst EXCEPTION_STEP_INTERNAL_FIELDS = {\n MESSAGE: '$message',\n TIMESTAMP: '$timestamp'\n};\nconst RESERVED_EXCEPTION_STEP_KEYS = new Set([\n EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,\n EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP\n]);\nconst DEFAULT_EXCEPTION_STEPS_CONFIG = {\n enabled: true,\n max_bytes: 32768\n};\nfunction resolveExceptionStepsConfig(config) {\n if (!config) return {\n ...DEFAULT_EXCEPTION_STEPS_CONFIG\n };\n return {\n enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,\n max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)\n };\n}\nfunction stripReservedExceptionStepFields(properties) {\n if (!properties) return {\n sanitizedProperties: {},\n droppedKeys: []\n };\n const droppedKeys = [];\n const sanitizedProperties = Object.keys(properties).reduce((acc, key)=>{\n if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {\n droppedKeys.push(key);\n return acc;\n }\n acc[key] = properties[key];\n return acc;\n }, {});\n return {\n sanitizedProperties,\n droppedKeys\n };\n}\nclass ExceptionStepsBuffer {\n constructor(config){\n this._entries = [];\n this._totalBytes = 0;\n this._config = resolveExceptionStepsConfig(config);\n }\n setConfig(config) {\n this._config = resolveExceptionStepsConfig(config);\n this._trimToMaxBytes();\n }\n add(step) {\n const serialized = normalizeAndSerializeStep(step);\n if (!serialized) return;\n const bytes = getUtf8ByteLength(serialized.json);\n if (bytes > this._config.max_bytes) return;\n this._entries.push({\n step: serialized.step,\n bytes\n });\n this._totalBytes += bytes;\n this._trimToMaxBytes();\n }\n getAttachable() {\n return this._entries.map((e)=>e.step);\n }\n clear() {\n this._entries = [];\n this._totalBytes = 0;\n }\n size() {\n return this._entries.length;\n }\n _trimToMaxBytes() {\n while(this._totalBytes > this._config.max_bytes && this._entries.length > 0){\n const evicted = this._entries.shift();\n if (evicted) this._totalBytes -= evicted.bytes;\n }\n }\n}\nfunction normalizePositiveInteger(input, fallback) {\n if (!isNumber(input) || input === 1 / 0 || input === -1 / 0) return fallback;\n const normalized = Math.floor(input);\n if (normalized < 0) return fallback;\n return normalized;\n}\nfunction normalizeAndSerializeStep(step) {\n let json;\n try {\n json = safeJsonStringify(step);\n } catch {\n return;\n }\n try {\n const parsed = JSON.parse(json);\n if (!isObject(parsed)) return;\n const parsedStep = parsed;\n const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];\n const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];\n if (!isString(message) || 0 === message.trim().length) return;\n if (!isString(timestamp) && !isNumber(timestamp)) return;\n return {\n step: parsedStep,\n json\n };\n } catch {\n return;\n }\n}\nfunction getUtf8ByteLength(value) {\n if ('undefined' != typeof TextEncoder) return new TextEncoder().encode(value).length;\n const encoded = encodeURIComponent(value);\n let byteLength = 0;\n for(let i = 0; i < encoded.length; i++)if ('%' === encoded[i]) {\n byteLength += 1;\n i += 2;\n } else byteLength += 1;\n return byteLength;\n}\nexport { DEFAULT_EXCEPTION_STEPS_CONFIG, EXCEPTION_STEP_INTERNAL_FIELDS, ExceptionStepsBuffer, getUtf8ByteLength, resolveExceptionStepsConfig, stripReservedExceptionStepFields };\n","function getInjectedReleaseId() {\n const injected = globalThis._posthogReleaseId;\n return 'string' == typeof injected && injected.length > 0 ? injected : void 0;\n}\nexport { getInjectedReleaseId };\n","import { SimpleEventEmitter } from \"./eventemitter.mjs\";\nimport { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipSupported } from \"./gzip.mjs\";\nimport { PostHogPersistedProperty } from \"./types.mjs\";\nimport { PromiseQueue, STRING_FORMAT, allSettled, createLogger, currentISOTime, getEventUuid, raceWithTimeout, removeTrailingSlash, retriable, safeJsonStringify, safeSetTimeout } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { ErrorCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, StringCoercer, createDefaultStackParser } from \"./error-tracking/index.mjs\";\nclass PostHogFetchHttpError extends Error {\n constructor(response, reqByteLength, responseBodyDeadline, abortController){\n super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = 'PostHogFetchHttpError', this._bodyReadTimedOut = false;\n }\n get status() {\n return this.response.status;\n }\n get bodyReadTimedOut() {\n return this._bodyReadTimedOut;\n }\n get text() {\n if (!this.responseBodyTextPromise) if (Date.now() >= this.responseBodyDeadline) {\n this._bodyReadTimedOut = true;\n const timeoutError = new Error('Response body read timed out');\n timeoutError.name = 'AbortError';\n this.cancelResponseBody(timeoutError);\n this.responseBodyTextPromise = Promise.reject(timeoutError);\n } else {\n const responseBodyTimeout = new Promise((_resolve, reject)=>{\n this.responseBodyTimer = safeSetTimeout(()=>{\n this._bodyReadTimedOut = true;\n const timeoutError = new Error('Response body read timed out');\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n this.cancelResponseBody(timeoutError);\n }, this.responseBodyDeadline - Date.now());\n });\n let responseBodyText;\n try {\n responseBodyText = Promise.resolve(this.response.text());\n } catch (error) {\n responseBodyText = Promise.reject(error);\n }\n this.responseBodyTextPromise = Promise.race([\n responseBodyText,\n responseBodyTimeout\n ]).finally(()=>clearTimeout(this.responseBodyTimer));\n }\n return this.responseBodyTextPromise;\n }\n get json() {\n return this.text.then((text)=>JSON.parse(text));\n }\n cancelResponseBody(reason) {\n clearTimeout(this.responseBodyTimer);\n if (!this.abortController.signal.aborted) this.abortController.abort(reason);\n (async ()=>{\n try {\n await this.response.body?.cancel();\n } catch {}\n })();\n }\n}\nclass PostHogFetchNetworkError extends Error {\n constructor(error){\n super('Network error while fetching PostHog', error instanceof Error ? {\n cause: error\n } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';\n }\n}\nconst maybeAdd = (key, value)=>void 0 !== value ? {\n [key]: value\n } : {};\nconst applyCallerFeatureFlagOverrides = (target, callerProperties)=>{\n for (const key of Object.keys(callerProperties))if (key.startsWith('$feature/') || '$active_feature_flags' === key) target[key] = callerProperties[key];\n};\nasync function logFlushError(err) {\n if (err instanceof PostHogFetchHttpError) {\n let text = '';\n try {\n text = await err.text;\n } catch {\n if (err.bodyReadTimedOut) text = '<response body read timed out>';\n }\n console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);\n } else console.error('Error while flushing PostHog', err);\n return Promise.resolve();\n}\nfunction isPostHogFetchError(err) {\n return 'object' == typeof err && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));\n}\nfunction isPostHogFetchNetworkError(err) {\n return err instanceof PostHogFetchNetworkError;\n}\nfunction isRetryableFlagsFetchError(err) {\n if (err instanceof PostHogFetchHttpError) return 502 === err.status || 504 === err.status;\n if (!(err instanceof PostHogFetchNetworkError)) return false;\n const cause = err.error;\n const code = cause?.code ?? cause?.cause?.code;\n return 'ECONNREFUSED' !== code;\n}\nfunction isPostHogFetchContentTooLargeError(err) {\n return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;\n}\nfunction isPostHogFetchRetryableError(err) {\n if (err instanceof PostHogFetchHttpError) return 408 === err.status || 429 === err.status || err.status >= 500;\n return isPostHogFetchNetworkError(err);\n}\nfunction isPostHogEventProperties(value) {\n return null !== value && 'object' == typeof value && !Array.isArray(value);\n}\nvar posthog_core_stateless_QuotaLimitedFeature = /*#__PURE__*/ function(QuotaLimitedFeature) {\n QuotaLimitedFeature[\"FeatureFlags\"] = \"feature_flags\";\n QuotaLimitedFeature[\"Recordings\"] = \"recordings\";\n return QuotaLimitedFeature;\n}({});\nconst DEFAULT_QUEUE_ROUTE = 'default';\nclass PostHogCoreStateless {\n getErrorPropertiesBuilder() {\n if (!this._errorPropertiesBuilder) this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();\n return this._errorPropertiesBuilder;\n }\n createErrorPropertiesBuilder() {\n return new ErrorPropertiesBuilder([\n new ErrorCoercer(),\n new ObjectCoercer(),\n new StringCoercer(),\n new PrimitiveCoercer()\n ], createDefaultStackParser());\n }\n constructor(apiKey, options = {}){\n this.flushPromise = null;\n this.pendingFlushPromise = null;\n this.flushPromises = new Set();\n this._dequeuedMessagesCount = 0;\n this.shutdownPromise = null;\n this.promiseQueue = new PromiseQueue();\n this._events = new SimpleEventEmitter();\n this._isInitialized = false;\n const normalizedApiKey = 'string' == typeof apiKey ? apiKey.trim() : '';\n const normalizedHost = 'string' == typeof options.host ? options.host.trim() : '';\n const missingApiKey = !normalizedApiKey;\n this._logger = createLogger('[PostHog]', this.logMsgIfDebug.bind(this));\n if (missingApiKey) this._logger.error(\"You must pass your PostHog project's api key. The client will be disabled.\");\n this.apiKey = normalizedApiKey;\n this.host = removeTrailingSlash(normalizedHost || 'https://us.i.posthog.com');\n this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;\n this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);\n this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);\n this.flushInterval = options.flushInterval ?? 10000;\n this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;\n this.defaultOptIn = options.defaultOptIn ?? true;\n this.disableSurveys = options.disableSurveys ?? false;\n this._retryOptions = {\n retryCount: options.fetchRetryCount ?? 3,\n retryDelay: options.fetchRetryDelay ?? 3000,\n retryCheck: isPostHogFetchRetryableError\n };\n this.requestTimeout = options.requestTimeout ?? 10000;\n this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;\n this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;\n this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;\n this.disableGeoip = options.disableGeoip ?? true;\n this.disabled = (options.disabled ?? false) || missingApiKey;\n this.historicalMigration = options?.historicalMigration ?? false;\n this._initPromise = Promise.resolve();\n this._isInitialized = true;\n this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;\n if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');\n this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);\n }\n logMsgIfDebug(fn) {\n if (this.isDebug) fn();\n }\n wrap(fn) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (this._isInitialized) return fn();\n this._initPromise.then(()=>fn());\n }\n getCommonEventProperties() {\n return {\n $lib: this.getLibraryId(),\n $lib_version: this.getLibraryVersion()\n };\n }\n get optedOut() {\n return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;\n }\n async optIn() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);\n });\n }\n async optOut() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);\n });\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n debug(enabled = true) {\n this.removeDebugCallback?.();\n if (enabled) {\n const removeDebugCallback = this.on('*', (event, payload)=>this._logger.info(event, payload));\n this.removeDebugCallback = ()=>{\n removeDebugCallback();\n this.removeDebugCallback = void 0;\n };\n }\n }\n get isDebug() {\n return !!this.removeDebugCallback;\n }\n get isDisabled() {\n return this.disabled;\n }\n buildPayload(payload) {\n const userProperties = payload.properties || {};\n let properties = {\n ...userProperties,\n ...this.getCommonEventProperties()\n };\n applyCallerFeatureFlagOverrides(properties, userProperties);\n if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties);\n return {\n distinct_id: payload.distinct_id,\n event: payload.event,\n properties\n };\n }\n isMinimalFlagCalledEventsEnabled() {\n return false;\n }\n addPendingPromise(promise) {\n return this.promiseQueue.add(promise);\n }\n identifyStateless(distinctId, properties, options) {\n this.wrap(()=>{\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n this.enqueue('identify', payload, options);\n });\n }\n async identifyStatelessImmediate(distinctId, properties, options) {\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n await this.sendImmediate('identify', payload, options);\n }\n captureStateless(distinctId, event, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n this.enqueue('capture', payload, options);\n });\n }\n async captureStatelessImmediate(distinctId, event, properties, options) {\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n await this.sendImmediate('capture', payload, options);\n }\n aliasStateless(alias, distinctId, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n this.enqueue('alias', payload, options);\n });\n }\n async aliasStatelessImmediate(alias, distinctId, properties, options) {\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n await this.sendImmediate('alias', payload, options);\n }\n groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n this.enqueue('capture', payload, options);\n });\n }\n async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n await this.sendImmediate('capture', payload, options);\n }\n async getRemoteConfig() {\n await this._initPromise;\n let host = this.host;\n if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';\n else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';\n const url = `${host}/array/${this.apiKey}/config`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n return this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>response.json()\n }, {\n retryCount: 0\n }, this.remoteConfigRequestTimeoutMs).catch((error)=>{\n this._logger.error('Remote config could not be loaded', error);\n this._events.emit('error', error);\n });\n }\n async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {\n await this._initPromise;\n const configParam = fetchConfig ? '&config=true' : '';\n const url = `${this.host}/flags/?v=2${configParam}`;\n const requestData = {\n token: this.apiKey,\n distinct_id: distinctId,\n groups,\n person_properties: personProperties,\n group_properties: groupProperties,\n ...extraPayload\n };\n if (personProperties.$device_id) requestData.$device_id = personProperties.$device_id;\n if (this.evaluationContexts && this.evaluationContexts.length > 0) requestData.evaluation_contexts = this.evaluationContexts;\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(requestData)\n };\n this._logger.info('Flags URL', url);\n return this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>response.json()\n }, {\n retryCount: this.featureFlagsRequestMaxRetries,\n retryCheck: isRetryableFlagsFetchError\n }, this.featureFlagsRequestTimeoutMs).then((response)=>({\n success: true,\n response: normalizeFlagsResponse(response)\n })).catch((error)=>{\n this._events.emit('error', error);\n return {\n success: false,\n error: this.categorizeRequestError(error)\n };\n });\n }\n categorizeRequestError(error) {\n if (error instanceof PostHogFetchHttpError) return {\n type: 'api_error',\n statusCode: error.status\n };\n if (error instanceof PostHogFetchNetworkError) {\n const cause = error.error;\n if (cause instanceof Error && ('AbortError' === cause.name || 'TimeoutError' === cause.name)) return {\n type: 'timeout'\n };\n return {\n type: 'connection_error'\n };\n }\n return {\n type: 'unknown_error'\n };\n }\n async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);\n if (void 0 === flagDetailResponse) return {\n response: void 0,\n requestId: void 0\n };\n let response = getFeatureFlagValue(flagDetailResponse.response);\n if (void 0 === response) response = false;\n return {\n response,\n requestId: flagDetailResponse.requestId\n };\n }\n async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) return;\n const featureFlags = flagsResponse.flags;\n const flagDetail = featureFlags[key];\n return {\n response: flagDetail,\n requestId: flagsResponse.requestId,\n evaluatedAt: flagsResponse.evaluatedAt\n };\n }\n async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (!payloads) return;\n const response = payloads[key];\n if (void 0 === response) return null;\n return response;\n }\n async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;\n return payloads;\n }\n async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n }\n async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n if (!featureFlagDetails) return {\n flags: void 0,\n payloads: void 0,\n requestId: void 0\n };\n return {\n flags: featureFlagDetails.featureFlags,\n payloads: featureFlagDetails.featureFlagPayloads,\n requestId: featureFlagDetails.requestId\n };\n }\n async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const extraPayload = {\n geoip_disable: disableGeoip ?? this.disableGeoip\n };\n if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;\n const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);\n if (!result.success) return;\n const flagsResponse = result.response;\n 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');\n if (flagsResponse.quotaLimited?.includes(\"feature_flags\")) {\n 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');\n return {\n flags: {},\n featureFlags: {},\n featureFlagPayloads: {},\n requestId: flagsResponse?.requestId,\n quotaLimited: flagsResponse.quotaLimited\n };\n }\n return flagsResponse;\n }\n async getSurveysStateless() {\n await this._initPromise;\n if (this.disabled) return [];\n if (true === this.disableSurveys) {\n this._logger.info('Loading surveys is disabled.');\n return [];\n }\n const url = `${this.host}/api/surveys/?token=${this.apiKey}`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n const response = await this.fetchWithRetry(url, fetchOptions, {\n type: 'required',\n consume: (response)=>{\n if (200 !== response.status || !response.json) {\n const msg = `Surveys API could not be loaded: ${response.status}`;\n const error = new Error(msg);\n this._logger.error(error);\n this._events.emit('error', new Error(msg));\n return Promise.resolve(void 0);\n }\n return response.json();\n }\n }).catch((error)=>{\n this._logger.error('Surveys API could not be loaded', error);\n this._events.emit('error', error);\n });\n const newSurveys = response?.surveys;\n if (newSurveys) this._logger.info('Surveys fetched from API: ', JSON.stringify(newSurveys));\n return newSurveys ?? [];\n }\n get props() {\n if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);\n return this._props || {};\n }\n set props(val) {\n this._props = val;\n }\n async register(properties) {\n this.wrap(()=>{\n this.props = {\n ...this.props,\n ...properties\n };\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n async unregister(property) {\n this.wrap(()=>{\n delete this.props[property];\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n processBeforeEnqueue(message) {\n return message;\n }\n async flushStorage() {}\n getQueueRouteKey(_message) {\n return DEFAULT_QUEUE_ROUTE;\n }\n persistedQueueKeyForRoute(_route) {\n return PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return [\n DEFAULT_QUEUE_ROUTE\n ];\n }\n getRouteQueue(route) {\n return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];\n }\n enqueue(type, _message, options, explicitRoute) {\n this.wrap(()=>{\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));\n const queue = this.getPersistedProperty(queueKey) || [];\n if (queue.length >= this.maxQueueSize) {\n queue.shift();\n this._logger.warn('Queue is full, the oldest event is dropped.');\n }\n queue.push({\n message\n });\n this.setPersistedProperty(queueKey, queue);\n this._events.emit(type, message);\n if (queue.length >= this.flushAt) this.flushBackground();\n if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(()=>this.flushBackground(), this.flushInterval);\n });\n }\n async sendImmediate(type, _message, options, explicitRoute) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this._isInitialized) await this._initPromise;\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n try {\n await this.sendBatch([\n message\n ], void 0, explicitRoute ?? this.getQueueRouteKey(message));\n } catch (err) {\n this._events.emit('error', err);\n }\n }\n normalizeMessage(message) {\n const { type: _type, library, library_version, ...sanitizedMessage } = message;\n let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;\n if (void 0 !== library && properties?.$lib === void 0) properties = {\n ...properties || {},\n $lib: library\n };\n if (void 0 !== library_version && properties?.$lib_version === void 0) properties = {\n ...properties || {},\n $lib_version: library_version\n };\n if (properties) sanitizedMessage.properties = properties;\n sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);\n return sanitizedMessage;\n }\n normalizeTimestampForWire(timestamp) {\n const parsedTimestamp = timestamp instanceof Date ? timestamp : 'string' == typeof timestamp ? new Date(timestamp) : null;\n if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime())) return timestamp;\n const normalized = parsedTimestamp.toISOString();\n const fractionalSeconds = 'string' == typeof timestamp ? timestamp.match(/\\.(\\d+)(?:Z|[+-]\\d{2}:?\\d{2})?$/i)?.[1] : void 0;\n return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\\.\\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;\n }\n prepareMessage(_message, options) {\n const message = {\n ..._message,\n timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),\n uuid: getEventUuid(options?.uuid, uuidv7)\n };\n const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;\n if (addGeoipDisableProperty) {\n if (!isPostHogEventProperties(message.properties)) message.properties = {};\n message.properties['$geoip_disable'] = true;\n }\n if (message.distinctId) {\n message.distinct_id = message.distinctId;\n delete message.distinctId;\n }\n return message;\n }\n clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n flushBackground() {\n if (this.pendingFlushPromise) return;\n this.flush().catch(async (err)=>{\n await logFlushError(err);\n });\n }\n async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {\n const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);\n let iteration = 0;\n while(true){\n const promises = this.promiseQueue.getPromises([\n ...ignoredPendingPromises,\n ...this.flushPromises\n ], maxPromiseId);\n if (0 === promises.length) return;\n if (iteration > 0) this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);\n await Promise.all(promises.map((promise)=>promise.catch(()=>{})));\n iteration++;\n }\n }\n flushWithPendingPromises() {\n return this.flushInternal(true);\n }\n flush() {\n return this.flushInternal(false);\n }\n flushInternal(waitForPendingPromises) {\n if (this.disabled) return Promise.resolve();\n if (!waitForPendingPromises && this.pendingFlushPromise) return this.pendingFlushPromise;\n const previousFlushPromise = this.flushPromise;\n const maxPromiseId = this.promiseQueue.maxId;\n const nextFlushPromise = Promise.resolve().then(()=>{\n if (waitForPendingPromises) return this.waitForPendingPromises(maxPromiseId, [\n previousFlushPromise,\n nextFlushPromise\n ]);\n }).then(()=>allSettled([\n previousFlushPromise\n ])).then(()=>{\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n return this._flush();\n });\n this.pendingFlushPromise = nextFlushPromise;\n this.flushPromise = nextFlushPromise;\n this.flushPromises.add(nextFlushPromise);\n this.addPendingPromise(nextFlushPromise);\n allSettled([\n nextFlushPromise\n ]).then(()=>{\n this.flushPromises.delete(nextFlushPromise);\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n if (this.flushPromise === nextFlushPromise) this.flushPromise = null;\n });\n return nextFlushPromise;\n }\n getCustomHeaders() {\n const customUserAgent = this.getCustomUserAgent();\n const headers = {};\n if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;\n return headers;\n }\n compressPayload(payload) {\n return gzipCompress(payload, this.isDebug);\n }\n getBatchEndpointPath(_route) {\n return '/batch/';\n }\n async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {\n const data = {\n api_key: this.apiKey,\n batch: batchMessages.map((message)=>{\n if (!message) return message;\n const timestamp = this.normalizeTimestampForWire(message.timestamp);\n return timestamp === message.timestamp ? message : {\n ...message,\n timestamp\n };\n }),\n sent_at: currentISOTime()\n };\n if (this.historicalMigration) data.historical_migration = true;\n const payload = safeJsonStringify(data);\n const url = `${this.host}${this.getBatchEndpointPath(route)}`;\n const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || payload\n };\n await this.fetchWithRetry(url, fetchOptions, {\n type: 'successful-write'\n }, retryOptions);\n }\n async _flush() {\n this.clearFlushTimer();\n await this._initPromise;\n const routes = this.getActiveQueueRoutes();\n if (!routes.some((route)=>this.getRouteQueue(route).length > 0)) return;\n const sentMessages = [];\n let firstError;\n for (const route of routes)try {\n await this._flushRoute(route, sentMessages);\n } catch (err) {\n if (void 0 === firstError) firstError = err;\n }\n if (void 0 !== firstError) throw firstError;\n this._events.emit('flush', sentMessages);\n }\n async _flushRoute(route, sentMessages) {\n const queueKey = this.persistedQueueKeyForRoute(route);\n let queue = this.getPersistedProperty(queueKey) || [];\n if (!queue.length) return;\n const originalQueueLength = queue.length;\n let sentFromRoute = 0;\n while(queue.length > 0 && sentFromRoute < originalQueueLength){\n const batchItems = queue.slice(0, this.maxBatchSize);\n const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));\n const persistQueueChange = async ()=>{\n const refreshedQueue = this.getPersistedProperty(queueKey) || [];\n const remainingBatchItems = [\n ...batchItems\n ];\n const newQueue = refreshedQueue.filter((item)=>{\n const itemUuid = item.message?.uuid;\n const batchItemIndex = remainingBatchItems.findIndex((batchItem)=>batchItem === item || 'string' == typeof itemUuid && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);\n if (-1 === batchItemIndex) return true;\n remainingBatchItems.splice(batchItemIndex, 1);\n return false;\n });\n this.setPersistedProperty(queueKey, newQueue);\n queue = newQueue;\n this._dequeuedMessagesCount += batchItems.length;\n await this.flushStorage();\n };\n const retryOptions = {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n };\n try {\n await this.sendBatch(batchMessages, retryOptions, route);\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {\n this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));\n this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);\n continue;\n }\n if (!(err instanceof PostHogFetchNetworkError)) await persistQueueChange();\n this._events.emit('error', err);\n throw err;\n }\n await persistQueueChange();\n sentMessages.push(...batchMessages);\n sentFromRoute += batchMessages.length;\n }\n }\n async _sendOtlpBatch({ path, payload }) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n type: 'successful-write'\n }, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (isPostHogFetchRetryableError(err)) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async _sendLogsBatch(payload) {\n return this._sendOtlpBatch({\n path: 'logs',\n payload\n });\n }\n async _sendMetricsBatch(payload) {\n return this._sendOtlpBatch({\n path: 'metrics',\n payload\n });\n }\n async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {\n const body = options.body ? options.body : '';\n let reqByteLength = -1;\n try {\n reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);\n } catch {\n if (body instanceof Blob) reqByteLength = body.size;\n else if (body instanceof Uint8Array) reqByteLength = body.byteLength;\n else {\n const encoded = new TextEncoder().encode(body);\n reqByteLength = encoded.length;\n }\n }\n const retriableOptions = {\n ...this._retryOptions,\n ...retryOptions\n };\n let attempt = 0;\n return await retriable(async ()=>{\n attempt++;\n const ctrl = new AbortController();\n const timeoutMs = requestTimeout ?? this.requestTimeout;\n const requestDeadline = Date.now() + timeoutMs;\n let timer;\n const deadline = new Promise((_resolve, reject)=>{\n timer = safeSetTimeout(()=>{\n const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n ctrl.abort(timeoutError);\n }, timeoutMs);\n });\n let res;\n let responseAccepted = false;\n let cancellation;\n const cancelBody = ()=>cancellation ??= (async ()=>{\n try {\n await res?.body?.cancel();\n } catch {}\n })();\n try {\n let fetchPromise;\n try {\n fetchPromise = this.fetch(url, {\n signal: ctrl.signal,\n ...options\n });\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n }\n fetchPromise.then((lateResponse)=>{\n if (ctrl.signal.aborted && !responseAccepted) Promise.resolve(lateResponse.body?.cancel()).catch(()=>{});\n }).catch(()=>{});\n try {\n res = await Promise.race([\n fetchPromise,\n deadline\n ]);\n responseAccepted = true;\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n }\n const isNoCors = 'no-cors' === options.mode;\n if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);\n if ('successful-write' === responseHandling.type) {\n try {\n await Promise.race([\n cancelBody(),\n deadline\n ]);\n } catch {}\n return;\n }\n try {\n return await Promise.race([\n responseHandling.consume(res),\n deadline\n ]);\n } catch (e) {\n if (ctrl.signal.aborted) throw new PostHogFetchNetworkError(e);\n throw e;\n }\n } finally{\n clearTimeout(timer);\n if (ctrl.signal.aborted && res) cancelBody();\n }\n }, {\n ...retriableOptions,\n retryCheck: (error)=>{\n const shouldRetry = retriableOptions.retryCheck(error);\n if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError) error.cancelResponseBody();\n return shouldRetry;\n }\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n await this._initPromise;\n let hasTimedOut = false;\n this.clearFlushTimer();\n if (this.disabled) return;\n const doShutdown = async ()=>{\n try {\n await this.promiseQueue.join();\n while(true){\n const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);\n if (!hasQueuedEvents) break;\n const dequeuedBeforeFlush = this._dequeuedMessagesCount;\n await this.flush();\n if (hasTimedOut) break;\n if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {\n this._logger.warn('Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.');\n break;\n }\n }\n } catch (e) {\n if (!isPostHogFetchError(e)) throw e;\n await logFlushError(e);\n }\n };\n return raceWithTimeout(doShutdown(), shutdownTimeoutMs, ()=>{\n this._logger.critical('Timeout while shutting down PostHog. Some events may not have been sent.', {\n shutdownTimeoutMs\n });\n hasTimedOut = true;\n });\n }\n async shutdown(shutdownTimeoutMs = 30000) {\n 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');\n else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{\n this.shutdownPromise = null;\n });\n return this.shutdownPromise;\n }\n}\nexport { PostHogCoreStateless, posthog_core_stateless_QuotaLimitedFeature as QuotaLimitedFeature, applyCallerFeatureFlagOverrides, isPostHogFetchContentTooLargeError, isPostHogFetchNetworkError, logFlushError, maybeAdd };\n","import { ErrorTracking } from \"@posthog/core\";\nimport { constants } from \"node:fs\";\nimport { open as promises_open } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nconst LRU_FILE_CONTENTS_CACHE = new ErrorTracking.ReduceableCache(25);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new ErrorTracking.ReduceableCache(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst MAX_CONTEXTLINES_COLNO = 1000;\nconst MAX_CONTEXTLINES_LINENO = 10000;\nconst MAX_CONTEXTLINES_FILE_SIZE = 10485760;\nasync function addSourceContext(frames, openSourceFile = promises_open, logger) {\n const filesToLines = {};\n let basePath;\n try {\n basePath = process.cwd();\n } catch {}\n for(let i = frames.length - 1; i >= 0; i--){\n const frame = frames[i];\n const filename = frame?.filename;\n if (!frame || 'string' != typeof filename || 'number' != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;\n if (!isAbsolute(filename) && void 0 === basePath) continue;\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n filesToLines[filename].push(frame.lineno);\n }\n const files = Object.keys(filesToLines);\n if (0 == files.length) return frames;\n const readlinePromises = [];\n for (const file of files){\n const cacheKey = makeSourceCacheKey(file, basePath);\n if (void 0 === cacheKey) continue;\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey)) continue;\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) continue;\n filesToLineRanges.sort((a, b)=>a - b);\n const ranges = makeLineReaderRanges(filesToLineRanges);\n if (ranges.every((r)=>rangeExistsInContentCache(cacheKey, r))) continue;\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger));\n }\n await Promise.all(readlinePromises).catch(()=>{});\n if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);\n LRU_FILE_CONTENTS_CACHE.reduce();\n return frames;\n}\nasync function openRegularSourceFile(path, openSourceFile, logger) {\n let fileHandle;\n let isValid = false;\n try {\n fileHandle = await openSourceFile(path, constants.O_RDONLY | constants.O_NONBLOCK);\n const fileStat = await fileHandle.stat();\n if (!fileStat.isFile()) return;\n if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE) return void logger?.debug(`Skipping source context for oversized file ${path}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);\n isValid = true;\n return fileHandle;\n } catch {\n return;\n } finally{\n if (fileHandle && !isValid) await fileHandle.close().catch(()=>{});\n }\n}\nasync function getContextLinesFromFile(path, ranges, output, cacheKey, openSourceFile, logger) {\n const fileHandle = await openRegularSourceFile(path, openSourceFile, logger);\n if (void 0 === fileHandle) return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n const openedFileHandle = fileHandle;\n return new Promise((resolve)=>{\n let finished = false;\n function destroyStreamAndResolve(stream) {\n if (finished) return;\n finished = true;\n stream?.destroy();\n openedFileHandle.close().then(resolve, resolve);\n }\n let stream;\n try {\n stream = openedFileHandle.createReadStream({\n autoClose: false,\n start: 0,\n end: MAX_CONTEXTLINES_FILE_SIZE - 1\n });\n } catch {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n destroyStreamAndResolve();\n return;\n }\n let lineReaded;\n try {\n lineReaded = createInterface({\n input: stream\n });\n } catch {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n destroyStreamAndResolve(stream);\n return;\n }\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) return void destroyStreamAndResolve(stream);\n let rangeStart = range[0];\n let rangeEnd = range[1];\n function onStreamError() {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve(stream);\n }\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', ()=>destroyStreamAndResolve(stream));\n lineReaded.on('line', (line)=>{\n lineNumber++;\n if (lineNumber < rangeStart) return;\n output[lineNumber] = snipLine(line, 0);\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\nfunction addSourceContextToFrames(frames, cache, basePath) {\n for (const frame of frames)if (frame.filename && void 0 === frame.context_line && 'number' == typeof frame.lineno) {\n const cacheKey = makeSourceCacheKey(frame.filename, basePath);\n const contents = void 0 === cacheKey ? void 0 : cache.get(cacheKey);\n if (void 0 === contents) continue;\n addContextToFrame(frame.lineno, frame, contents);\n }\n}\nfunction addContextToFrame(lineno, frame, contents) {\n if (void 0 === frame.lineno || void 0 === contents) return;\n frame.pre_context = [];\n for(let i = makeRangeStart(lineno); i < lineno; i++){\n const line = contents[i];\n if (void 0 === line) return void clearLineContext(frame);\n frame.pre_context.push(line);\n }\n if (void 0 === contents[lineno]) return void clearLineContext(frame);\n frame.context_line = contents[lineno];\n const end = makeRangeEnd(lineno);\n frame.post_context = [];\n for(let i = lineno + 1; i <= end; i++){\n const line = contents[i];\n if (void 0 === line) break;\n frame.post_context.push(line);\n }\n}\nfunction clearLineContext(frame) {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\nfunction shouldSkipContextLinesForFile(path) {\n return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');\n}\nfunction shouldSkipContextLinesForFrame(frame) {\n if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\nfunction makeSourceCacheKey(path, basePath) {\n if (isAbsolute(path)) return JSON.stringify([\n null,\n path\n ]);\n return void 0 === basePath ? void 0 : JSON.stringify([\n basePath,\n path\n ]);\n}\nfunction rangeExistsInContentCache(cacheKey, range) {\n const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);\n if (void 0 === contents) return false;\n for(let i = range[0]; i <= range[1]; i++)if (void 0 === contents[i]) return false;\n return true;\n}\nfunction makeLineReaderRanges(lines) {\n if (!lines.length) return [];\n let i = 0;\n const line = lines[0];\n if ('number' != typeof line) return [];\n let current = makeContextRange(line);\n const out = [];\n while(true){\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n const next = lines[i + 1];\n if ('number' != typeof next) break;\n if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;\n else {\n out.push(current);\n current = makeContextRange(next);\n }\n i++;\n }\n return out;\n}\nfunction makeContextRange(line) {\n return [\n makeRangeStart(line),\n makeRangeEnd(line)\n ];\n}\nfunction makeRangeStart(line) {\n return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);\n}\nfunction makeRangeEnd(line) {\n return line + DEFAULT_LINES_OF_CONTEXT;\n}\nfunction emplace(map, key, contents) {\n const value = map.get(key);\n if (void 0 === value) {\n map.set(key, contents);\n return contents;\n }\n return value;\n}\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) return newLine;\n if (colno > lineLength) colno = lineLength;\n let start = Math.max(colno - 60, 0);\n if (start < 5) start = 0;\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) end = lineLength;\n if (end === lineLength) start = Math.max(end - 140, 0);\n newLine = newLine.slice(start, end);\n if (start > 0) newLine = `...${newLine}`;\n if (end < lineLength) newLine += '...';\n return newLine;\n}\nexport { MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_FILE_SIZE, MAX_CONTEXTLINES_LINENO, addSourceContext };\n","import { isAbsolute, relative, sep } from \"path\";\nfunction createRelativePathModifier(basePath = process.cwd()) {\n const isWindows = '\\\\' === sep;\n const toUnix = (p)=>isWindows ? p.replace(/\\\\/g, '/') : p;\n const normalizedBase = toUnix(basePath);\n return async (frames)=>{\n for (const frame of frames)if (!(!frame.filename || frame.filename.startsWith('node:') || frame.filename.startsWith('data:'))) {\n if (isAbsolute(frame.filename)) frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));\n }\n return frames;\n };\n}\nexport { createRelativePathModifier };\n","const version = '5.51.1';\nexport { version };\n","const FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n UNKNOWN_ERROR: 'unknown_error'\n};\nexport { FeatureFlagError };\n","import { FeatureFlagError } from \"./types.mjs\";\nclass FeatureFlagEvaluations {\n constructor(init){\n this._host = init.host;\n this._distinctId = init.distinctId;\n this._groups = init.groups;\n this._disableGeoip = init.disableGeoip;\n this._flags = init.flags;\n this._requestId = init.requestId;\n this._evaluatedAt = init.evaluatedAt;\n this._flagDefinitionsLoadedAt = init.flagDefinitionsLoadedAt;\n this._errorsWhileComputing = init.errorsWhileComputing ?? false;\n this._quotaLimited = init.quotaLimited ?? false;\n this._accessed = init.accessed ?? new Set();\n this._isSlice = init.isSlice ?? false;\n }\n isEnabled(key, options = {}) {\n const flag = this._flags[key];\n this._recordAccess(key);\n return flag?.enabled ?? options.defaultValue ?? false;\n }\n getFlag(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n if (!flag) return;\n if (!flag.enabled) return false;\n return flag.variant ?? true;\n }\n getFlagPayload(key) {\n return this._flags[key]?.payload;\n }\n onlyAccessed() {\n const filtered = {};\n for (const key of this._accessed){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n }\n return this._cloneWith(filtered);\n }\n only(keys) {\n const filtered = {};\n const missing = [];\n for (const key of keys){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n else missing.push(key);\n }\n if (missing.length > 0) this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${missing.join(', ')}`);\n return this._cloneWith(filtered);\n }\n get keys() {\n return Object.keys(this._flags);\n }\n _getEventProperties() {\n const properties = {};\n const activeFlags = [];\n for (const [key, flag] of Object.entries(this._flags)){\n const value = false === flag.enabled ? false : flag.variant ?? true;\n properties[`$feature/${key}`] = value;\n if (flag.enabled) activeFlags.push(key);\n }\n if (activeFlags.length > 0) {\n activeFlags.sort();\n properties['$active_feature_flags'] = activeFlags;\n }\n return properties;\n }\n _cloneWith(flags) {\n return new FeatureFlagEvaluations({\n host: this._host,\n distinctId: this._distinctId,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n flags,\n requestId: this._requestId,\n evaluatedAt: this._evaluatedAt,\n flagDefinitionsLoadedAt: this._flagDefinitionsLoadedAt,\n errorsWhileComputing: this._errorsWhileComputing,\n quotaLimited: this._quotaLimited,\n accessed: new Set(this._accessed),\n isSlice: true\n });\n }\n _recordAccess(key) {\n this._accessed.add(key);\n if ('' === this._distinctId) return;\n if (this._isSlice && !(key in this._flags)) return;\n const flag = this._flags[key];\n const response = void 0 === flag ? void 0 : false === flag.enabled ? false : flag.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flag?.id,\n $feature_flag_version: flag?.version,\n $feature_flag_reason: flag?.reason,\n locally_evaluated: flag?.locallyEvaluated ?? false,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: this._requestId,\n $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt\n };\n if (flag?.hasExperiment !== void 0) properties.$feature_flag_has_experiment = flag.hasExperiment;\n if (flag?.locallyEvaluated && void 0 !== this._flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;\n const errors = [];\n if (this._errorsWhileComputing) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (this._quotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n if (void 0 === flag) errors.push(FeatureFlagError.FLAG_MISSING);\n if (errors.length > 0) properties.$feature_flag_error = errors.join(',');\n this._host.captureFlagCalledEventIfNeeded({\n distinctId: this._distinctId,\n key,\n response,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n properties\n });\n }\n}\nexport { FeatureFlagEvaluations };\n","async function hashSHA1(text) {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('SubtleCrypto API not available');\n const hashBuffer = await subtle.digest('SHA-1', new TextEncoder().encode(text));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((byte)=>byte.toString(16).padStart(2, '0')).join('');\n}\nexport { hashSHA1 };\n","import { raceWithTimeout, safeSetTimeout } from \"@posthog/core\";\nimport { hashSHA1 } from \"./crypto.mjs\";\nconst SIXTY_SECONDS = 60000;\nconst LONG_SCALE = 0xfffffffffffffff;\nconst NULL_VALUES_ALLOWED_OPERATORS = [\n 'is_not',\n 'is_set'\n];\nclass ClientError extends Error {\n constructor(message){\n super();\n Error.captureStackTrace(this, this.constructor);\n this.name = 'ClientError';\n this.message = message;\n Object.setPrototypeOf(this, ClientError.prototype);\n }\n}\nfunction setCustomErrorPrototype(error, constructor) {\n error.name = constructor.name;\n Error.captureStackTrace(error, constructor);\n Object.setPrototypeOf(error, constructor.prototype);\n}\nclass InconclusiveMatchError extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, InconclusiveMatchError);\n }\n}\nclass RequiresServerEvaluation extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, RequiresServerEvaluation);\n }\n}\nclass FeatureFlagsPoller {\n constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }){\n this.debugMode = false;\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.pollerStopped = false;\n this.pollingInterval = pollingInterval;\n this.personalApiKey = personalApiKey;\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.loadedSuccessfullyOnce = false;\n this.timeout = timeout;\n this.projectApiKey = projectApiKey;\n this.host = host;\n this.poller = void 0;\n this.fetch = options.fetch || fetch;\n this.onError = options.onError;\n this.customHeaders = customHeaders;\n this.onLoad = options.onLoad;\n this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;\n this.cacheProvider = options.cacheProvider;\n this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;\n this.loadFeatureFlags();\n }\n debug(enabled = true) {\n this.debugMode = enabled;\n }\n logMsgIfDebug(fn) {\n if (this.debugMode) fn();\n }\n createEvaluationContext(distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {\n return {\n distinctId,\n groups,\n personProperties,\n groupProperties,\n evaluationCache\n };\n }\n async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {\n await this.loadFeatureFlags();\n let response;\n let featureFlag;\n if (!this.loadedSuccessfullyOnce) return response;\n featureFlag = this.featureFlagsByKey[key];\n if (void 0 !== featureFlag) {\n const evaluationContext = this.createEvaluationContext(distinctId, groups, personProperties, groupProperties);\n try {\n const result = await this.computeFlagAndPayloadLocally(featureFlag, evaluationContext);\n response = result.value;\n this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${key} -> ${response}`));\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));\n }\n }\n return response;\n }\n async getAllFlagsAndPayloads(evaluationContext, flagKeysToExplicitlyEvaluate) {\n await this.loadFeatureFlags();\n const response = {};\n const payloads = {};\n let fallbackToFlags = 0 == this.featureFlags.length;\n const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key)=>this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;\n const sharedEvaluationContext = {\n ...evaluationContext,\n evaluationCache: evaluationContext.evaluationCache ?? {}\n };\n await Promise.all(flagsToEvaluate.map(async (flag)=>{\n try {\n const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext);\n response[flag.key] = matchValue;\n if (matchPayload) payloads[flag.key] = matchPayload;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));\n fallbackToFlags = true;\n }\n }));\n return {\n response,\n payloads,\n fallbackToFlags\n };\n }\n async computeFlagAndPayloadLocally(flag, evaluationContext, options = {}) {\n const { matchValue, skipLoadCheck = false } = options;\n if (!skipLoadCheck) await this.loadFeatureFlags();\n if (!this.loadedSuccessfullyOnce) return {\n value: false,\n payload: null\n };\n let flagValue;\n flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, evaluationContext);\n const payload = this.getFeatureFlagPayload(flag.key, flagValue);\n return {\n value: flagValue,\n payload\n };\n }\n async computeFlagValueLocally(flag, evaluationContext) {\n const { distinctId, groups, personProperties, groupProperties } = evaluationContext;\n if (!flag.active) return false;\n if (flag.ensure_experience_continuity) throw new InconclusiveMatchError('Flag has experience continuity enabled');\n const flagFilters = flag.filters || {};\n const aggregation_group_type_index = flagFilters.aggregation_group_type_index;\n if (void 0 != aggregation_group_type_index) {\n const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];\n if (!groupName) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));\n throw new InconclusiveMatchError('Flag has unknown group type index');\n }\n if (!(groupName in groups)) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));\n return false;\n }\n if ('device_id' === flag.bucketing_identifier && (personProperties?.$device_id === void 0 || personProperties?.$device_id === null || personProperties?.$device_id === '')) this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${flag.key}`));\n const focusedGroupProperties = groupProperties[groupName];\n return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext);\n }\n {\n const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties);\n if (void 0 === bucketingValue) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${flag.key} without $device_id, falling back to server evaluation`));\n throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`);\n }\n return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext);\n }\n }\n getBucketingValueForFlag(flag, distinctId, properties) {\n if (flag.filters?.aggregation_group_type_index != void 0) return distinctId;\n if ('device_id' === flag.bucketing_identifier) {\n const deviceId = properties?.$device_id;\n if (null == deviceId || '' === deviceId) return;\n return deviceId;\n }\n return distinctId;\n }\n getFeatureFlagPayload(key, flagValue) {\n let payload = null;\n if (false !== flagValue && null != flagValue) {\n if ('boolean' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;\n else if ('string' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;\n if (null != payload) {\n if ('object' == typeof payload) return payload;\n if ('string' == typeof payload) try {\n return JSON.parse(payload);\n } catch {}\n return payload;\n }\n }\n return null;\n }\n async evaluateFlagDependency(property, properties, evaluationContext) {\n const { evaluationCache } = evaluationContext;\n const targetFlagKey = property.key;\n if (!this.featureFlagsByKey) throw new InconclusiveMatchError('Feature flags not available for dependency evaluation');\n if (!('dependency_chain' in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);\n const dependencyChain = property.dependency_chain;\n if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);\n if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);\n for (const depFlagKey of dependencyChain){\n if (!(depFlagKey in evaluationCache)) {\n const depFlag = this.featureFlagsByKey[depFlagKey];\n if (depFlag) if (depFlag.active) try {\n const depResult = await this.computeFlagValueLocally(depFlag, evaluationContext);\n evaluationCache[depFlagKey] = depResult;\n } catch (error) {\n throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);\n }\n else evaluationCache[depFlagKey] = false;\n else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);\n }\n const cachedResult = evaluationCache[depFlagKey];\n if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);\n }\n const targetFlagValue = evaluationCache[targetFlagKey];\n return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);\n }\n flagEvaluatesToExpectedValue(expectedValue, flagValue) {\n if ('boolean' == typeof expectedValue) return expectedValue === flagValue || 'string' == typeof flagValue && '' !== flagValue && true === expectedValue;\n if ('string' == typeof expectedValue) return flagValue === expectedValue;\n return false;\n }\n async matchFeatureFlagProperties(flag, bucketingValue, properties, evaluationContext) {\n const flagFilters = flag.filters || {};\n const flagConditions = flagFilters.groups || [];\n const flagAggregation = flagFilters.aggregation_group_type_index;\n const earlyExitEnabled = flagFilters.early_exit ?? false;\n const { groups, groupProperties } = evaluationContext;\n let isInconclusive = false;\n let result;\n for (const condition of flagConditions)try {\n const conditionAggregation = void 0 !== condition.aggregation_group_type_index ? condition.aggregation_group_type_index : flagAggregation;\n let effectiveProperties = properties;\n let effectiveBucketingValue = bucketingValue;\n if (conditionAggregation !== flagAggregation) {\n if (null != conditionAggregation) {\n const groupName = this.groupTypeMapping[String(conditionAggregation)];\n if (!groupName || !(groupName in groups)) {\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`));\n continue;\n }\n if (!(groupName in groupProperties)) {\n isInconclusive = true;\n continue;\n }\n effectiveProperties = groupProperties[groupName];\n effectiveBucketingValue = groups[groupName];\n }\n }\n const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);\n if ('match' === matchResult) {\n const variantOverride = condition.variant;\n const flagVariants = flagFilters.multivariate?.variants || [];\n result = variantOverride && flagVariants.some((variant)=>variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;\n break;\n }\n if (earlyExitEnabled && 'out_of_rollout_bound' === matchResult) return false;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation) throw e;\n if (e instanceof InconclusiveMatchError) isInconclusive = true;\n else throw e;\n }\n if (void 0 !== result) return result;\n if (isInconclusive) throw new InconclusiveMatchError(\"Can't determine if feature flag is enabled or not with given properties\");\n return false;\n }\n async isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext) {\n const rolloutPercentage = condition.rollout_percentage;\n const warnFunction = (msg)=>{\n this.logMsgIfDebug(()=>console.warn(msg));\n };\n if ((condition.properties || []).length > 0) {\n for (const prop of condition.properties){\n const propertyType = prop.type;\n let matches = false;\n if ('cohort' === propertyType) {\n const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp)=>this.evaluateFlagDependency(depProp, properties, evaluationContext));\n matches = 'not_in' === prop.operator ? !inCohort : inCohort;\n } else matches = 'flag' === propertyType ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);\n if (!matches) return 'no_match';\n }\n if (void 0 == rolloutPercentage) return 'match';\n }\n if (void 0 != rolloutPercentage && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100.0) return 'out_of_rollout_bound';\n return 'match';\n }\n async getMatchingVariant(flag, bucketingValue) {\n const hashValue = await _hash(flag.key, bucketingValue, 'variant');\n const matchingVariant = this.variantLookupTable(flag).find((variant)=>hashValue >= variant.valueMin && hashValue < variant.valueMax);\n if (matchingVariant) return matchingVariant.key;\n }\n variantLookupTable(flag) {\n const lookupTable = [];\n let valueMin = 0;\n let valueMax = 0;\n const flagFilters = flag.filters || {};\n const multivariates = flagFilters.multivariate?.variants || [];\n multivariates.forEach((variant)=>{\n valueMax = valueMin + variant.rollout_percentage / 100.0;\n lookupTable.push({\n valueMin,\n valueMax,\n key: variant.key\n });\n valueMin = valueMax;\n });\n return lookupTable;\n }\n updateFlagState(flagData) {\n this.featureFlags = flagData.flags;\n this.featureFlagsByKey = flagData.flags.reduce((acc, curr)=>(acc[curr.key] = curr, acc), {});\n this.groupTypeMapping = flagData.groupTypeMapping;\n this.cohorts = flagData.cohorts;\n this.loadedSuccessfullyOnce = true;\n this.onMinimalFlagCalledEvents?.(true === flagData.minimalFlagCalledEvents);\n }\n warnAboutExperienceContinuityFlags(flags) {\n if (this.strictLocalEvaluation) return;\n const experienceContinuityFlags = flags.filter((f)=>f.ensure_experience_continuity);\n if (experienceContinuityFlags.length > 0) console.warn(`[PostHog] You are using local evaluation but ${experienceContinuityFlags.length} flag(s) have experience continuity enabled: ${experienceContinuityFlags.map((f)=>f.key).join(', ')}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`);\n }\n async loadFromCache(debugMessage) {\n if (!this.cacheProvider) return false;\n try {\n const cached = await this.cacheProvider.getFlagDefinitions();\n if (cached) {\n this.updateFlagState(cached);\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(cached.flags);\n return true;\n }\n return false;\n } catch (err) {\n this.onError?.(new Error(`Failed to load from cache: ${err}`));\n return false;\n }\n }\n async loadFeatureFlags(forceReload = false) {\n if (this.loadedSuccessfullyOnce && !forceReload) return;\n if (!forceReload && this.nextFetchAllowedAt && Date.now() < this.nextFetchAllowedAt) return void this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Skipping fetch, in backoff period'));\n if (!this.loadingPromise) this.loadingPromise = this._loadFeatureFlags().catch((err)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(()=>{\n this.loadingPromise = void 0;\n });\n return this.loadingPromise;\n }\n isLocalEvaluationReady() {\n return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;\n }\n getFlagDefinitionsLoadedAt() {\n return this.flagDefinitionsLoadedAt;\n }\n getPollingInterval() {\n if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;\n return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);\n }\n beginBackoff() {\n this.shouldBeginExponentialBackoff = true;\n this.backOffCount += 1;\n this.nextFetchAllowedAt = Date.now() + this.getPollingInterval();\n }\n clearBackoff() {\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.nextFetchAllowedAt = void 0;\n }\n async _loadFeatureFlags() {\n if (this.poller) {\n clearTimeout(this.poller);\n this.poller = void 0;\n }\n try {\n let shouldFetch = true;\n if (this.cacheProvider) try {\n shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();\n } catch (err) {\n this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));\n }\n if (!shouldFetch) {\n const loaded = await this.loadFromCache('Loaded flags from cache (skipped fetch)');\n if (loaded) return;\n if (this.loadedSuccessfullyOnce) return;\n }\n const res = await this._requestFeatureFlagDefinitions();\n if (!res) return;\n switch(res.status){\n case 304:\n this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Flags not modified (304), using cached data'));\n this.flagsEtag = res.headers?.get('ETag') ?? this.flagsEtag;\n this.loadedSuccessfullyOnce = true;\n this.clearBackoff();\n return;\n case 401:\n this.beginBackoff();\n throw new ClientError(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 402:\n 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');\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.onMinimalFlagCalledEvents?.(false);\n return;\n case 403:\n this.beginBackoff();\n throw new ClientError(`Your secret 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 secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);\n case 429:\n this.beginBackoff();\n 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`);\n case 200:\n {\n const responseJson = await res.json() ?? {};\n if (!('flags' in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));\n this.flagsEtag = res.headers?.get('ETag') ?? void 0;\n const flagData = {\n flags: responseJson.flags ?? [],\n groupTypeMapping: responseJson.group_type_mapping || {},\n cohorts: responseJson.cohorts || {},\n minimalFlagCalledEvents: true === responseJson.minimal_flag_called_events\n };\n this.updateFlagState(flagData);\n this.flagDefinitionsLoadedAt = Date.now();\n this.clearBackoff();\n if (this.cacheProvider && shouldFetch) try {\n await this.cacheProvider.onFlagDefinitionsReceived(flagData);\n } catch (err) {\n this.onError?.(new Error(`Failed to store in cache: ${err}`));\n }\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(flagData.flags);\n break;\n }\n default:\n return;\n }\n } catch (err) {\n if (err instanceof ClientError) this.onError?.(err);\n } finally{\n if (!this.pollerStopped) this.poller = setTimeout(()=>this.loadFeatureFlags(true), this.getPollingInterval());\n }\n }\n getPersonalApiKeyRequestOptions(method = 'GET', etag) {\n const headers = {\n ...this.customHeaders,\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.personalApiKey}`\n };\n if (etag) headers['If-None-Match'] = etag;\n return {\n method,\n headers\n };\n }\n async _requestFeatureFlagDefinitions() {\n const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;\n const options = this.getPersonalApiKeyRequestOptions('GET', this.flagsEtag);\n let abortTimeout = null;\n if (this.timeout && 'number' == typeof this.timeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.timeout);\n options.signal = controller.signal;\n }\n const clearAbortTimeout = ()=>clearTimeout(abortTimeout);\n try {\n const fetch1 = this.fetch;\n const res = await fetch1(url, options);\n if (200 !== res.status) {\n clearAbortTimeout();\n return res;\n }\n return {\n status: res.status,\n headers: res.headers,\n body: res.body,\n text: async ()=>{\n try {\n return await res.text();\n } finally{\n clearAbortTimeout();\n }\n },\n json: async ()=>{\n try {\n return await res.json();\n } finally{\n clearAbortTimeout();\n }\n }\n };\n } catch (err) {\n clearAbortTimeout();\n throw err;\n }\n }\n async stopPoller(timeoutMs = 30000) {\n this.pollerStopped = true;\n clearTimeout(this.poller);\n this.poller = void 0;\n if (this.cacheProvider) try {\n const shutdownResult = this.cacheProvider.shutdown();\n if (shutdownResult instanceof Promise) await raceWithTimeout(shutdownResult, timeoutMs, ()=>{\n throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);\n });\n } catch (err) {\n this.onError?.(new Error(`Error during cache shutdown: ${err}`));\n }\n }\n}\nasync function _hash(key, bucketingValue, salt = '') {\n const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);\n return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;\n}\nfunction matchProperty(property, propertyValues, warnFunction) {\n const key = property.key;\n const value = property.value;\n const operator = property.operator || 'exact';\n if (key in propertyValues) {\n if ('is_not_set' === operator) return false;\n } else {\n if ('is_not_set' === operator) return true;\n throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);\n }\n const overrideValue = propertyValues[key];\n if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {\n if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);\n return false;\n }\n function computeExactMatch(value, overrideValue) {\n if (Array.isArray(value)) return value.map((val)=>String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());\n return String(value).toLowerCase() === String(overrideValue).toLowerCase();\n }\n function compare(lhs, rhs, operator) {\n if ('gt' === operator) return lhs > rhs;\n if ('gte' === operator) return lhs >= rhs;\n if ('lt' === operator) return lhs < rhs;\n if ('lte' === operator) return lhs <= rhs;\n throw new Error(`Invalid operator: ${operator}`);\n }\n switch(operator){\n case 'exact':\n return computeExactMatch(value, overrideValue);\n case 'is_not':\n return !computeExactMatch(value, overrideValue);\n case 'is_set':\n return key in propertyValues;\n case 'icontains':\n return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'not_icontains':\n return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'starts_with':\n return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());\n case 'not_starts_with':\n return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());\n case 'ends_with':\n return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());\n case 'not_ends_with':\n return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());\n case 'regex':\n return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));\n case 'not_regex':\n return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n {\n const parsedValue = 'number' == typeof value ? value : parseFloat(String(value));\n let parsedOverride;\n parsedOverride = 'number' == typeof overrideValue ? overrideValue : null != overrideValue ? parseFloat(String(overrideValue)) : NaN;\n if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride)) return compare(parsedOverride, parsedValue, operator);\n return compare(String(overrideValue), String(value), operator);\n }\n case 'is_date_after':\n case 'is_date_before':\n {\n if ('boolean' == typeof value) throw new InconclusiveMatchError(\"Date operations cannot be performed on boolean values\");\n let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));\n if (null == parsedDate) parsedDate = convertToDateTime(value);\n if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);\n const overrideDate = convertToDateTime(overrideValue);\n if ([\n 'is_date_before'\n ].includes(operator)) return overrideDate < parsedDate;\n return overrideDate > parsedDate;\n }\n case 'semver_eq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 === cmp;\n }\n case 'semver_neq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 !== cmp;\n }\n case 'semver_gt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp > 0;\n }\n case 'semver_gte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp >= 0;\n }\n case 'semver_lt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp < 0;\n }\n case 'semver_lte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp <= 0;\n }\n case 'semver_tilde':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeTildeBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_caret':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeCaretBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_wildcard':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeWildcardBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n default:\n throw new InconclusiveMatchError(`Unknown operator: ${operator}`);\n }\n}\nfunction checkCohortExists(cohortId, cohortProperties) {\n if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);\n}\nasync function matchCohort(property, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n const cohortId = String(property.value);\n checkCohortExists(cohortId, cohortProperties);\n const propertyGroup = cohortProperties[cohortId];\n return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n}\nasync function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n if (!propertyGroup) return true;\n const propertyGroupType = propertyGroup.type;\n const properties = propertyGroup.values;\n if (!properties || 0 === properties.length) return true;\n let errorMatchingLocally = false;\n if ('values' in properties[0]) {\n for (const prop of properties)try {\n const matches = await matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n if ('AND' === propertyGroupType) {\n if (!matches) return false;\n } else if (matches) return true;\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"Can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n }\n for (const prop of properties)try {\n let matches;\n if ('cohort' === prop.type) matches = await matchCohort(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n else if ('flag' === prop.type) {\n if (!flagDependencyEvaluator) throw new InconclusiveMatchError(`Flag dependency '${prop.key || 'unknown'}' cannot be evaluated without a flag dependency evaluator`);\n matches = await flagDependencyEvaluator(prop);\n } else matches = matchProperty(prop, propertyValues);\n const negation = prop.negation || false;\n if ('AND' === propertyGroupType) {\n if (!matches && !negation) return false;\n if (matches && negation) return false;\n } else {\n if (matches && !negation) return true;\n if (!matches && negation) return true;\n }\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n}\nfunction isValidRegex(regex) {\n try {\n new RegExp(regex);\n return true;\n } catch (err) {\n return false;\n }\n}\nfunction parseSemverNumericIdentifier(part, raw) {\n if (!/^\\d+$/.test(part)) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n if (part.length > 1 && '0' === part[0]) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n return parseInt(part, 10);\n}\nfunction parseSemver(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const baseVersion = text.split('-')[0].split('+')[0];\n if (!baseVersion || baseVersion.startsWith('.')) throw new InconclusiveMatchError(`Invalid semver: ${value}`);\n const parts = baseVersion.split('.');\n const parsePart = (part)=>{\n if (void 0 === part || '' === part) return 0;\n return parseSemverNumericIdentifier(part, value);\n };\n const major = parsePart(parts[0]);\n const minor = parsePart(parts[1]);\n const patch = parsePart(parts[2]);\n return [\n major,\n minor,\n patch\n ];\n}\nfunction compareSemverTuples(a, b) {\n for(let i = 0; i < 3; i++){\n if (a[i] < b[i]) return -1;\n if (a[i] > b[i]) return 1;\n }\n return 0;\n}\nfunction computeTildeBounds(value) {\n const parsed = parseSemver(value);\n const lower = [\n parsed[0],\n parsed[1],\n parsed[2]\n ];\n const upper = [\n parsed[0],\n parsed[1] + 1,\n 0\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeCaretBounds(value) {\n const parsed = parseSemver(value);\n const [major, minor, patch] = parsed;\n const lower = [\n major,\n minor,\n patch\n ];\n let upper;\n upper = major > 0 ? [\n major + 1,\n 0,\n 0\n ] : minor > 0 ? [\n 0,\n minor + 1,\n 0\n ] : [\n 0,\n 0,\n patch + 1\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeWildcardBounds(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const cleanedText = text.replace(/\\.\\*$/, '').replace(/\\*$/, '');\n if (!cleanedText) throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n const parts = cleanedText.split('.');\n const parseWildcardPart = (part)=>{\n try {\n return parseSemverNumericIdentifier(part, value);\n } catch {\n throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n }\n };\n const major = parseWildcardPart(parts[0]);\n let lower;\n let upper;\n if (1 === parts.length) {\n lower = [\n major,\n 0,\n 0\n ];\n upper = [\n major + 1,\n 0,\n 0\n ];\n } else {\n const minor = parseWildcardPart(parts[1]);\n lower = [\n major,\n minor,\n 0\n ];\n upper = [\n major,\n minor + 1,\n 0\n ];\n }\n return {\n lower,\n upper\n };\n}\nfunction convertToDateTime(value) {\n if (value instanceof Date) return value;\n if ('string' == typeof value || 'number' == typeof value) {\n const date = new Date(value);\n if (!isNaN(date.valueOf())) return date;\n throw new InconclusiveMatchError(`${value} is in an invalid date format`);\n }\n throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);\n}\nfunction relativeDateParseForFeatureFlagMatching(value) {\n const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;\n const match = value.match(regex);\n const parsedDt = new Date(new Date().toISOString());\n if (!match) return null;\n {\n if (!match.groups) return null;\n const number = parseInt(match.groups['number']);\n if (number >= 10000) return null;\n const interval = match.groups['interval'];\n if ('h' == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);\n else if ('d' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);\n else if ('w' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);\n else if ('m' == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);\n else {\n if ('y' != interval) return null;\n parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);\n }\n return parsedDt;\n }\n}\nexport { ClientError, FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation, matchProperty, parseSemver, relativeDateParseForFeatureFlagMatching };\n","const UNHANDLED_REJECTION_OPTION_NAMES = [\n '--unhandled-rejections',\n '--unhandled_rejections'\n];\nconst UNHANDLED_REJECTION_MODES = new Set([\n 'throw',\n 'strict',\n 'warn',\n 'warn-with-error-code',\n 'none'\n]);\nconst STARTUP_EXEC_ARGV = [\n ...globalThis.process?.execArgv ?? []\n];\nconst STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;\nfunction splitNodeOptions(nodeOptions) {\n const args = [];\n let current = '';\n let isInString = false;\n for(let index = 0; index < nodeOptions.length; index++){\n const character = nodeOptions[index];\n if ('\\\\' === character && isInString && index + 1 < nodeOptions.length) current += nodeOptions[++index];\n else if (' ' !== character || isInString) if ('\"' === character) isInString = !isInString;\n else current += character;\n else if (current) {\n args.push(current);\n current = '';\n }\n }\n if (current) args.push(current);\n return args;\n}\nfunction findUnhandledRejectionMode(args) {\n let mode;\n for(let index = 0; index < args.length; index++){\n const argument = args[index];\n const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name)=>argument === name || argument.startsWith(`${name}=`));\n if (!optionName) continue;\n const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);\n if (UNHANDLED_REJECTION_MODES.has(value)) mode = value;\n }\n return mode;\n}\nfunction getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {\n return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? '')) ?? 'throw';\n}\nconst STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();\nfunction captureUncaughtException(captureFn, error, origin) {\n captureFn(error, {\n mechanism: {\n type: 'unhandledRejection' === origin ? 'onunhandledrejection' : 'onuncaughtexception',\n handled: false\n }\n });\n}\nfunction makeUncaughtExceptionHandler(captureFn, onFatalFn) {\n let calledFatalError = false;\n return Object.assign((error, origin)=>{\n const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;\n captureUncaughtException(captureFn, error, origin);\n if (!calledFatalError && 0 === userProvidedListenersCount) {\n calledFatalError = true;\n onFatalFn(error);\n }\n }, {\n _posthogErrorHandler: true\n });\n}\nfunction addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {\n const process = globalThis.process;\n if (!process) return;\n if ('strict' === mode) return void process.on('uncaughtExceptionMonitor', (error, origin)=>captureUncaughtException(captureFn, error, origin));\n process.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));\n}\nfunction addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {\n const process = globalThis.process;\n if (!process || 'throw' === mode || 'strict' === mode || 'warn-with-error-code' === mode) return;\n process.on('unhandledRejection', (reason)=>{\n captureFn(reason, {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false\n }\n });\n });\n}\nexport { addUncaughtExceptionListener, addUnhandledRejectionListener, getUnhandledRejectionMode };\n","import { addUncaughtExceptionListener, addUnhandledRejectionListener } from \"./autocapture.mjs\";\nimport { BucketedRateLimiter, ErrorTracking, isObject, resolveExceptionRateLimiterConfig } from \"@posthog/core\";\nconst SHUTDOWN_TIMEOUT = 2000;\nclass error_tracking_ErrorTracking {\n constructor(client, options, _logger){\n this.client = client;\n this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;\n this._logger = _logger;\n this._rateLimiter = new BucketedRateLimiter({\n ...resolveExceptionRateLimiterConfig(options),\n refillInterval: 10000,\n _logger: this._logger\n });\n this.startAutocaptureIfEnabled();\n }\n static isPreviouslyCapturedError(x) {\n return isObject(x) && '__posthog_previously_captured_error' in x && true === x.__posthog_previously_captured_error;\n }\n static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {\n const properties = {\n ...additionalProperties\n };\n const exceptionProperties = builder.buildFromUnknown(error, hint);\n exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);\n const injectedReleaseId = ErrorTracking.getInjectedReleaseId();\n if (injectedReleaseId) properties.$release_id = injectedReleaseId;\n return {\n event: '$exception',\n distinctId: distinctId,\n properties: {\n ...exceptionProperties,\n ...properties\n },\n _originatedFromCaptureException: true\n };\n }\n startAutocaptureIfEnabled() {\n if (this.isEnabled()) {\n addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));\n addUnhandledRejectionListener(this.onException.bind(this));\n }\n }\n onException(exception, hint) {\n this.client.addPendingPromise((async ()=>{\n if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {\n const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);\n const exceptionProperties = eventMessage.properties;\n const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? 'Exception';\n const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);\n if (isRateLimited) return void this._logger.info('Skipping exception capture because of client rate limiting.', {\n exception: exceptionType\n });\n return this.client._capturePreparedEvent(eventMessage, false);\n }\n })());\n }\n async onFatalError(exception) {\n console.error(exception);\n await this.client.shutdown(SHUTDOWN_TIMEOUT);\n globalThis.process.exit(1);\n }\n isEnabled() {\n return !this.client.isDisabled && this._exceptionAutocaptureEnabled;\n }\n shutdown() {\n this._rateLimiter.stop();\n }\n}\nexport { error_tracking_ErrorTracking as default };\n","class PostHogMemoryStorage {\n getProperty(key) {\n return this._memoryStorage[key];\n }\n setProperty(key, value) {\n this._memoryStorage[key] = null !== value ? value : void 0;\n }\n constructor(){\n this._memoryStorage = {};\n }\n}\nexport { PostHogMemoryStorage };\n","function isCaptureMode(value) {\n return 'v0' === value || 'v1' === value;\n}\nfunction resolveCaptureMode() {\n const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;\n return isCaptureMode(envMode) ? envMode : 'v0';\n}\nexport { resolveCaptureMode };\n","const AI_EVENT_PREFIX = '$ai_';\nconst ANALYTICS_ROUTE = 'analytics';\nconst AI_ROUTE = 'ai';\nfunction isLegacyOnlyEvent(message) {\n return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);\n}\nexport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent };\n","class CaptureV1Error extends Error {\n constructor({ requestId, drops, retryExhausted, cause }){\n super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';\n this.requestId = requestId;\n this.drops = drops;\n this.retryExhausted = retryExhausted;\n this.cause = cause;\n }\n static buildMessage(requestId, drops, retryExhausted, cause) {\n let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;\n if (cause instanceof Error) message += ` (${cause.message})`;\n return message;\n }\n}\nexport { CaptureV1Error };\n","function coerceBool(value) {\n if ('boolean' == typeof value) return value;\n if ('number' == typeof value) return 0 !== value;\n if ('string' == typeof value) {\n const normalized = value.trim().toLowerCase();\n if ('true' === normalized || '1' === normalized) return true;\n if ('false' === normalized || '0' === normalized) return false;\n }\n}\nfunction coerceString(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst OPTION_SENTINELS = [\n {\n property: '$cookieless_mode',\n optionKey: 'cookieless_mode',\n coerce: coerceBool\n },\n {\n property: '$ignore_sent_at',\n optionKey: 'disable_skew_correction',\n coerce: coerceBool\n },\n {\n property: '$process_person_profile',\n optionKey: 'process_person_profile',\n coerce: coerceBool\n },\n {\n property: '$product_tour_id',\n optionKey: 'product_tour_id',\n coerce: coerceString\n }\n];\nconst TOPLEVEL_SENTINELS = [\n {\n property: '$session_id',\n field: 'session_id'\n },\n {\n property: '$window_id',\n field: 'window_id'\n }\n];\nfunction isRecord(value) {\n return 'object' == typeof value && null !== value && !Array.isArray(value);\n}\nfunction toRfc3339(timestamp) {\n if ('string' == typeof timestamp) {\n const asDate = new Date(timestamp);\n if (Number.isNaN(asDate.getTime())) return new Date().toISOString();\n const normalized = asDate.toISOString();\n const fractionalSeconds = timestamp.match(/\\.(\\d+)(?:Z|[+-]\\d{2}:?\\d{2})?$/i)?.[1];\n return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\\.\\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;\n }\n if (timestamp instanceof Date) return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();\n const asDate = null == timestamp ? new Date() : new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();\n}\nfunction relocateInto(properties, key, value) {\n if (void 0 !== value && !(key in properties)) properties[key] = value;\n}\nfunction buildV1Event(message) {\n const sourceProperties = isRecord(message.properties) ? message.properties : {};\n const properties = {\n ...sourceProperties\n };\n const options = {};\n for (const { property, optionKey, coerce } of OPTION_SENTINELS)if (property in properties) {\n const coerced = coerce(properties[property]);\n if (void 0 !== coerced) options[optionKey] = coerced;\n delete properties[property];\n }\n const topLevel = {};\n for (const { property, field } of TOPLEVEL_SENTINELS)if (property in properties) {\n const value = properties[property];\n if ('string' == typeof value) topLevel[field] = value;\n delete properties[property];\n }\n delete properties.$lib;\n delete properties.$lib_version;\n relocateInto(properties, '$set', message.$set);\n relocateInto(properties, '$set_once', message.$set_once);\n return {\n event: String(message.event ?? ''),\n uuid: String(message.uuid ?? ''),\n distinct_id: String(message.distinct_id ?? ''),\n timestamp: toRfc3339(message.timestamp),\n ...topLevel,\n options,\n properties\n };\n}\nfunction buildV1Batch(messages, { createdAt, historicalMigration }) {\n const batch = {\n created_at: createdAt,\n batch: messages.map(buildV1Event)\n };\n if (historicalMigration) batch.historical_migration = true;\n return batch;\n}\nexport { buildV1Batch, buildV1Event, coerceBool, coerceString };\n","import { gzipCompress, safeJsonStringify, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { CaptureV1Error } from \"./errors.mjs\";\nimport { buildV1Batch } from \"./transform.mjs\";\nconst V1_ANALYTICS_PATH = '/i/v1/analytics/events';\nconst DEFAULT_MAX_BACKOFF_MS = 30000;\nconst RETRYABLE_STATUSES = new Set([\n 408,\n 500,\n 502,\n 503,\n 504\n]);\nclass V1CaptureSender {\n constructor(config, hooks){\n this.config = config;\n this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;\n this.fetchFn = hooks.fetch;\n this.onError = hooks.onError;\n this.now = hooks.now ?? Date.now;\n this.sleep = hooks.sleep ?? ((ms)=>new Promise((resolve)=>safeSetTimeout(resolve, ms)));\n this.generateRequestId = hooks.generateRequestId ?? uuidv7;\n this.compress = hooks.compress ?? gzipCompress;\n }\n async sendV1Batch(messages) {\n if (0 === messages.length) return;\n const requestId = this.generateRequestId();\n const createdAt = new Date(this.now()).toISOString();\n const { batch } = buildV1Batch(messages, {\n createdAt,\n historicalMigration: this.config.historicalMigration\n });\n const url = `${this.config.host}${V1_ANALYTICS_PATH}`;\n const drops = [];\n let pending = batch;\n const maxAttempts = Math.max(1, this.config.maxAttempts);\n for(let attempt = 1; attempt <= maxAttempts; attempt++){\n const isLastAttempt = attempt === maxAttempts;\n const payload = safeJsonStringify({\n created_at: createdAt,\n ...this.config.historicalMigration ? {\n historical_migration: true\n } : {},\n batch: pending\n });\n let captureAttempt;\n let retryDelayMs;\n try {\n captureAttempt = await this.sendOnce(url, payload, attempt, requestId);\n const { response, signal } = captureAttempt;\n const { status } = response;\n if (status < 200 || status >= 300) if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {\n const retryAfterMs = this.parseRetryAfter(response);\n await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(()=>{});\n retryDelayMs = this.backoffDelay(attempt, retryAfterMs);\n } else {\n const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);\n return this.surfaceBatchFailure(requestId, drops, pending, httpError);\n }\n else {\n let parsed;\n try {\n parsed = await captureAttempt.waitFor(this.parseResponse(response));\n } catch (error) {\n if (signal.aborted) throw error;\n return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));\n }\n const retryable = this.classify(pending, parsed, drops);\n if (0 === retryable.length) return this.surfacePartialDrops(requestId, drops);\n if (isLastAttempt) return void this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: retryable.map((event)=>event.uuid)\n }));\n pending = retryable;\n const retryAfterMs = this.parseRetryAfter(response);\n retryDelayMs = this.backoffDelay(attempt, retryAfterMs);\n }\n } catch (transportError) {\n if (captureAttempt && !captureAttempt.signal.aborted) throw transportError;\n if (isLastAttempt) return this.surfaceBatchFailure(requestId, drops, pending, transportError);\n retryDelayMs = this.backoffDelay(attempt);\n } finally{\n captureAttempt?.cleanup();\n }\n if (void 0 !== retryDelayMs) await this.sleep(retryDelayMs);\n }\n }\n async sendOnce(url, payload, attempt, requestId) {\n const headers = this.buildHeaders(attempt, requestId);\n let body = payload;\n if (this.config.compressionEnabled) {\n const compressed = await this.compress(payload, this.config.isDebug);\n if (null !== compressed) {\n body = compressed;\n headers['Content-Encoding'] = 'gzip';\n }\n }\n const controller = new AbortController();\n let timeoutPhase = 'waiting for response headers';\n let timer;\n const deadline = new Promise((_resolve, reject)=>{\n timer = safeSetTimeout(()=>{\n const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);\n timeoutError.name = 'AbortError';\n reject(timeoutError);\n controller.abort(timeoutError);\n }, this.config.requestTimeoutMs);\n });\n try {\n const fetchPromise = this.fetchFn(url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal\n });\n let responseAccepted = false;\n fetchPromise.then((lateResponse)=>{\n if (controller.signal.aborted && !responseAccepted) this.cancelBody(lateResponse);\n }).catch(()=>{});\n const response = await Promise.race([\n fetchPromise,\n deadline\n ]);\n responseAccepted = true;\n timeoutPhase = 'while reading the response body';\n let cleanedUp = false;\n let cancellation;\n const cancelBody = ()=>cancellation ??= this.cancelBody(response);\n return {\n response,\n signal: controller.signal,\n waitFor: (operation)=>Promise.race([\n operation,\n deadline\n ]),\n cancelBody,\n cleanup: ()=>{\n if (cleanedUp) return;\n cleanedUp = true;\n clearTimeout(timer);\n if (controller.signal.aborted) cancelBody();\n }\n };\n } catch (error) {\n clearTimeout(timer);\n throw error;\n }\n }\n buildHeaders(attempt, requestId) {\n const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.config.apiKey}`,\n 'PostHog-Sdk-Info': sdkInfo,\n 'PostHog-Attempt': String(attempt),\n 'PostHog-Request-Id': requestId,\n 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()\n };\n if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;\n return headers;\n }\n classify(pending, parsed, drops) {\n const results = parsed.results ?? {};\n const retryable = [];\n for (const event of pending){\n const result = results[event.uuid];\n if (result) {\n if ('drop' === result.result) drops.push({\n uuid: event.uuid,\n details: result.details ?? void 0\n });\n else if ('retry' === result.result) retryable.push(event);\n }\n }\n return retryable;\n }\n backoffDelay(attempt, retryAfterMs) {\n const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);\n if (void 0 === retryAfterMs) return exponential;\n return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));\n }\n parseRetryAfter(response) {\n const raw = response.headers?.get('Retry-After');\n if (!raw) return;\n const trimmed = raw.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = parseInt(trimmed, 10);\n return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return;\n const delta = dateMs - this.now();\n return delta > 0 ? delta : void 0;\n }\n async parseResponse(response) {\n const text = await response.text();\n const parsed = JSON.parse(text);\n if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');\n const results = parsed.results;\n if (void 0 !== results && ('object' != typeof results || null === results || Array.isArray(results))) throw new Error('unexpected results shape');\n return {\n results: results ?? {}\n };\n }\n async buildHttpError(response, status, waitFor) {\n let bodyText = '';\n try {\n bodyText = (await waitFor(response.text())).slice(0, 512);\n } catch {}\n const suffix = bodyText ? `: ${bodyText}` : '';\n return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);\n }\n surfaceBatchFailure(requestId, drops, pending, cause) {\n this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: pending.map((event)=>event.uuid),\n cause\n }));\n }\n surfacePartialDrops(requestId, drops) {\n if (drops.length > 0) this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: []\n }));\n }\n async cancelBody(response) {\n try {\n await response.body?.cancel();\n } catch {}\n }\n}\nexport { V1CaptureSender };\n","const AI_CAPTURE_ROUTE = 'ai-capture';\nconst AI_CAPTURE_ENDPOINT_PATH = '/i/v0/ai/batch/';\nconst AI_MAX_EVENT_BYTES = 8388608;\nconst AI_BATCH_TARGET_BYTES = 5242880;\nexport { AI_BATCH_TARGET_BYTES, AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES };\n","import { safeJsonStringify } from \"@posthog/core\";\nimport { AI_BATCH_TARGET_BYTES, AI_MAX_EVENT_BYTES } from \"./routing.mjs\";\nconst encoder = new TextEncoder();\nfunction eventByteSize(message) {\n return encoder.encode(safeJsonStringify(message)).length;\n}\nfunction partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {\n const batches = [];\n const dropped = [];\n let current = [];\n let currentBytes = 0;\n for (const message of messages){\n if (void 0 === message) continue;\n const bytes = eventByteSize(message);\n if (bytes > maxEventBytes) {\n dropped.push({\n event: 'string' == typeof message.event ? message.event : 'unknown',\n bytes\n });\n continue;\n }\n if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {\n batches.push(current);\n current = [];\n currentBytes = 0;\n }\n current.push(message);\n currentBytes += bytes;\n }\n if (current.length > 0) batches.push(current);\n return {\n batches,\n dropped\n };\n}\nexport { eventByteSize, partitionAiBatch };\n","import { version } from \"./version.mjs\";\nimport { PostHogCoreStateless, PostHogMetrics, PostHogPersistedProperty, getEventUuid, isBlockedUA, isPlainObject, isPostHogFetchContentTooLargeError, minimizeFlagCalledEventProperties, raceWithTimeout, resolveMetricsConfig, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { FeatureFlagError } from \"./types.mjs\";\nimport { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from \"./extensions/feature-flags/feature-flags.mjs\";\nimport error_tracking from \"./extensions/error-tracking/index.mjs\";\nimport { PostHogMemoryStorage } from \"./storage-memory.mjs\";\nimport { resolveCaptureMode } from \"./capture-v1/config.mjs\";\nimport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from \"./capture-v1/routing.mjs\";\nimport { V1CaptureSender } from \"./capture-v1/sender.mjs\";\nimport { eventByteSize, partitionAiBatch } from \"./ai-capture/batching.mjs\";\nimport { AI_CAPTURE_ENDPOINT_PATH, AI_CAPTURE_ROUTE, AI_MAX_EVENT_BYTES } from \"./ai-capture/routing.mjs\";\nconst MINIMUM_POLLING_INTERVAL = 100;\nconst THIRTY_SECONDS = 30000;\nconst MAX_CACHE_SIZE = 50000;\nconst WAITUNTIL_DEBOUNCE_MS = 50;\nconst WAITUNTIL_MAX_WAIT_MS = 500;\nconst DEFAULT_NODE_HOST = 'https://us.i.posthog.com';\nconst _emittedDeprecations = new Set();\nfunction emitDeprecationWarningOnce(id, message) {\n if (_emittedDeprecations.has(id)) return;\n _emittedDeprecations.add(id);\n console.warn(`[PostHog] ${message}`);\n}\nfunction _resetDeprecationWarningsForTests() {\n _emittedDeprecations.clear();\n}\nfunction normalizeApiKey(value) {\n return 'string' == typeof value ? value.trim() : '';\n}\nfunction normalizePersonalApiKey(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || void 0;\n}\nfunction normalizeHost(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || DEFAULT_NODE_HOST;\n}\nfunction normalizeUnsetPersonProperties(value) {\n const propertyNames = Array.isArray(value) ? value : [\n value\n ];\n return propertyNames.filter((propertyName)=>'string' == typeof propertyName && propertyName.trim().length > 0);\n}\nfunction buildFlagEventProperties(flagValues) {\n if (!flagValues) return {};\n const additionalProperties = {};\n for (const [feature, variant] of Object.entries(flagValues))additionalProperties[`$feature/${feature}`] = variant;\n const activeFlags = Object.keys(flagValues).filter((flag)=>false !== flagValues[flag]).sort();\n if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;\n return additionalProperties;\n}\nclass PostHogBackendClient extends PostHogCoreStateless {\n constructor(apiKey, options = {}){\n const normalizedApiKey = normalizeApiKey(apiKey);\n const normalizedOptions = {\n ...options,\n maxQueueSize: options.maxQueueSize ?? 10000,\n flushInterval: options.flushInterval ?? 5000,\n host: normalizeHost(options.host),\n personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)\n };\n super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;\n this.options = normalizedOptions;\n this.captureMode = resolveCaptureMode();\n this.enableFullAiCapture = true === normalizedOptions.enableFullAiCapture;\n this.context = this.initializeContext();\n this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;\n if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);\n if ('number' == typeof normalizedOptions.waitUntilMaxWaitMs) this.options.waitUntilMaxWaitMs = Math.max(normalizedOptions.waitUntilMaxWaitMs, 0);\n if (!this.disabled && normalizedOptions.personalApiKey) {\n if (normalizedOptions.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.');\n const shouldEnableLocalEvaluation = false !== normalizedOptions.enableLocalEvaluation;\n if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({\n pollingInterval: this.options.featureFlagsPollingInterval,\n personalApiKey: normalizedOptions.personalApiKey,\n projectApiKey: normalizedApiKey,\n timeout: normalizedOptions.requestTimeout ?? 10000,\n host: this.host,\n fetch: normalizedOptions.fetch,\n onError: (err)=>{\n this._events.emit('error', err);\n },\n onLoad: (count)=>{\n this._events.emit('localEvaluationFlagsLoaded', count);\n },\n onMinimalFlagCalledEvents: (enabled)=>{\n this._minimalFlagCalledEvents = enabled;\n },\n customHeaders: this.getCustomHeaders(),\n cacheProvider: normalizedOptions.flagDefinitionCacheProvider,\n strictLocalEvaluation: normalizedOptions.strictLocalEvaluation\n });\n }\n this.errorTracking = new error_tracking(this, normalizedOptions, this._logger);\n this.distinctIdHasSentFlagCalls = {};\n this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;\n }\n enqueue(type, message, options, explicitRoute) {\n super.enqueue(type, message, options, explicitRoute);\n this.scheduleDebouncedFlush();\n }\n async flush() {\n const flushPromise = this.flushWithPendingPromises();\n const waitUntil = this.options.waitUntil;\n if (waitUntil && !this._waitUntilCycle) try {\n waitUntil(flushPromise.catch(()=>{}));\n } catch {}\n return flushPromise;\n }\n scheduleDebouncedFlush() {\n const waitUntil = this.options.waitUntil;\n if (!waitUntil) return;\n if (this.disabled || this.optedOut) return;\n if (!this._waitUntilCycle) {\n let resolve;\n const promise = new Promise((r)=>{\n resolve = r;\n });\n try {\n waitUntil(promise);\n } catch {\n return;\n }\n this._waitUntilCycle = {\n resolve: resolve,\n startedAt: Date.now(),\n timer: void 0\n };\n }\n const elapsed = Date.now() - this._waitUntilCycle.startedAt;\n const maxWaitMs = this.options.waitUntilMaxWaitMs ?? WAITUNTIL_MAX_WAIT_MS;\n const flushNow = elapsed >= maxWaitMs;\n if (void 0 !== this._waitUntilCycle.timer) clearTimeout(this._waitUntilCycle.timer);\n if (flushNow) return void this.resolveWaitUntilFlush();\n const debounceMs = this.options.waitUntilDebounceMs ?? WAITUNTIL_DEBOUNCE_MS;\n this._waitUntilCycle.timer = safeSetTimeout(()=>{\n this.resolveWaitUntilFlush();\n }, debounceMs);\n }\n _consumeWaitUntilCycle() {\n const cycle = this._waitUntilCycle;\n if (cycle) {\n clearTimeout(cycle.timer);\n this._waitUntilCycle = void 0;\n }\n return cycle?.resolve;\n }\n async resolveWaitUntilFlush() {\n const resolve = this._consumeWaitUntilCycle();\n try {\n await this.flushWithPendingPromises();\n } catch {} finally{\n resolve?.();\n }\n }\n getPersistedProperty(key) {\n return this._memoryStorage.getProperty(key);\n }\n setPersistedProperty(key, value) {\n return this._memoryStorage.setProperty(key, value);\n }\n fetch(url, options) {\n return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);\n }\n getQueueRouteKey(message) {\n return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;\n }\n persistedQueueKeyForRoute(route) {\n if (route === AI_CAPTURE_ROUTE) return PostHogPersistedProperty.AiCaptureQueue;\n return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n const routes = 'v1' === this.captureMode ? [\n ANALYTICS_ROUTE,\n AI_ROUTE\n ] : [\n ANALYTICS_ROUTE\n ];\n if (this._aiCaptureRouteActive) routes.push(AI_CAPTURE_ROUTE);\n return routes;\n }\n getBatchEndpointPath(route) {\n return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);\n }\n async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {\n if (route === AI_CAPTURE_ROUTE) return this.sendAiCaptureBatch(batchMessages, retryOptions);\n if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);\n const v1Events = batchMessages.filter((message)=>void 0 !== message);\n await this.getV1Sender().sendV1Batch(v1Events);\n }\n async sendAiCaptureBatch(batchMessages, retryOptions) {\n const { batches, dropped } = partitionAiBatch(batchMessages);\n for (const { event, bytes } of dropped){\n const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;\n this._logger.error(message);\n this._events.emit('error', new Error(message));\n }\n for (const batch of batches)await this.sendAiSubBatch(batch, retryOptions);\n }\n async sendAiSubBatch(batch, retryOptions) {\n try {\n await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);\n } catch (err) {\n if (!isPostHogFetchContentTooLargeError(err)) throw err;\n if (1 === batch.length) {\n const [event] = batch;\n const eventName = 'string' == typeof event.event ? event.event : 'unknown';\n const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;\n this._logger.error(message);\n this._events.emit('error', new Error(message));\n return;\n }\n const mid = Math.ceil(batch.length / 2);\n await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);\n await this.sendAiSubBatch(batch.slice(mid), retryOptions);\n }\n }\n getV1Sender() {\n if (!this._v1Sender) this._v1Sender = new V1CaptureSender({\n host: this.host,\n apiKey: this.apiKey,\n libraryId: this.getLibraryId(),\n libraryVersion: this.getLibraryVersion(),\n userAgent: this.getCustomUserAgent() || void 0,\n historicalMigration: this.historicalMigration,\n compressionEnabled: !this.disableCompression,\n requestTimeoutMs: this.requestTimeout,\n maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,\n initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,\n isDebug: this.isDebug\n }, {\n fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),\n onError: (error)=>this._events.emit('error', error),\n compress: (payload)=>this.compressPayload(payload)\n });\n return this._v1Sender;\n }\n getLibraryVersion() {\n return version;\n }\n get metrics() {\n if (!this._metrics) this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);\n return this._metrics;\n }\n getCustomUserAgent() {\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`;\n }\n getCommonEventProperties() {\n const commonProperties = super.getCommonEventProperties();\n if (this.options.isServer ?? true) commonProperties.$is_server = true;\n return commonProperties;\n }\n enable() {\n return super.optIn();\n }\n disable() {\n return super.optOut();\n }\n debug(enabled = true) {\n super.debug(enabled);\n this.featureFlagsPoller?.debug(enabled);\n }\n _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {\n if ('string' == typeof props) this._logger.warn(stringArgumentWarning);\n if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);\n }\n _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {\n return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{\n const captureOptions = {\n timestamp: options.timestamp,\n disableGeoip: options.disableGeoip,\n uuid: options.uuid\n };\n const message = {\n distinctId,\n event,\n properties: {\n ...properties,\n ...this.getCommonEventProperties()\n }\n };\n return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);\n }).catch((err)=>{\n if (err) console.error(err);\n }));\n }\n _capturePreparedEvent(props, immediate) {\n return this._sendPreparedEvent('capture', props, immediate);\n }\n capture(props) {\n this._warnIfInvalidCapture(props, 'Called capture() with a string as the first argument when an object was expected.', \"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this._capturePreparedEvent(props, false);\n }\n async captureImmediate(props) {\n this._warnIfInvalidCapture(props, 'Called captureImmediate() with a string as the first argument when an object was expected.', \"Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.\");\n return this._capturePreparedEvent(props, true);\n }\n captureAi(props) {\n if (this.disabled) return;\n const uuid = getEventUuid(props.uuid, uuidv7);\n this._sendPreparedAiEvent({\n ...props,\n uuid\n }, false);\n return uuid;\n }\n async captureAiImmediate(props) {\n if (this.disabled) return;\n const uuid = getEventUuid(props.uuid, uuidv7);\n await this._sendPreparedAiEvent({\n ...props,\n uuid\n }, true);\n return uuid;\n }\n _sendPreparedAiEvent(props, immediate) {\n if ('string' == typeof props?.event && !props.event.startsWith('$ai_')) this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);\n this._aiCaptureRouteActive = true;\n return this._sendPreparedEvent('capture', props, immediate, void 0, AI_CAPTURE_ROUTE);\n }\n identify({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n await this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {\n if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;\n const eventProperties = {};\n if (Object.keys(properties).length > 0) eventProperties.$set = properties;\n if (Object.keys(propertiesOnce).length > 0) eventProperties.$set_once = propertiesOnce;\n this.capture({\n distinctId,\n event: '$set',\n properties: eventProperties\n });\n }\n unsetPersonProperties({ distinctId, properties }) {\n const propertyNames = normalizeUnsetPersonProperties(properties);\n if (0 === propertyNames.length) return;\n this.capture({\n distinctId,\n event: '$set',\n properties: {\n $unset: propertyNames\n }\n });\n }\n alias(data) {\n this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async aliasImmediate(data) {\n await this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n isLocalEvaluationReady() {\n return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;\n }\n async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {\n if (this.isLocalEvaluationReady()) return true;\n if (void 0 === this.featureFlagsPoller) return false;\n return new Promise((resolve)=>{\n const timeout = setTimeout(()=>{\n cleanup();\n resolve(false);\n }, timeoutMs);\n const cleanup = this._events.on('localEvaluationFlagsLoaded', (count)=>{\n clearTimeout(timeout);\n cleanup();\n resolve(count > 0);\n });\n });\n }\n _resolveDistinctId(distinctIdOrOptions, options) {\n if ('string' == typeof distinctIdOrOptions) return {\n distinctId: distinctIdOrOptions,\n options\n };\n return {\n distinctId: this.context?.get()?.distinctId,\n options: distinctIdOrOptions\n };\n }\n async _getFeatureFlagResult(key, distinctId, options = {}, matchValue) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true;\n if (void 0 !== this._flagOverrides && key in this._flagOverrides) {\n const overrideValue = this._flagOverrides[key];\n if (void 0 === overrideValue) return;\n const overridePayload = this._payloadOverrides?.[key];\n return {\n key,\n enabled: false !== overrideValue,\n variant: 'string' == typeof overrideValue ? overrideValue : void 0,\n payload: overridePayload\n };\n }\n const { groups, disableGeoip } = options;\n let { onlyEvaluateLocally, personProperties, groupProperties } = options;\n const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n let result;\n let flagWasLocallyEvaluated = false;\n let requestId;\n let evaluatedAt;\n let featureFlagError;\n let flagId;\n let flagVersion;\n let flagReason;\n let flagHasExperiment;\n const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;\n if (localEvaluationEnabled) {\n await this.featureFlagsPoller?.loadFeatureFlags();\n const flag = this.featureFlagsPoller?.featureFlagsByKey[key];\n if (flag) try {\n const localResult = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, evaluationContext, {\n matchValue\n });\n if (localResult) {\n flagWasLocallyEvaluated = true;\n const value = localResult.value;\n flagId = flag.id;\n flagReason = 'Evaluated locally';\n flagHasExperiment = flag.has_experiment;\n result = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payload ?? void 0\n };\n }\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${key}: ${e.message}`);\n else throw e;\n }\n }\n if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {\n const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) featureFlagError = FeatureFlagError.UNKNOWN_ERROR;\n else {\n this._minimalFlagCalledEvents = true === flagsResponse.minimalFlagCalledEvents;\n requestId = flagsResponse.requestId;\n evaluatedAt = flagsResponse.evaluatedAt;\n const errors = [];\n if (flagsResponse.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (flagsResponse.quotaLimited?.includes('feature_flags')) errors.push(FeatureFlagError.QUOTA_LIMITED);\n const flagDetail = flagsResponse.flags[key];\n if (void 0 === flagDetail) errors.push(FeatureFlagError.FLAG_MISSING);\n else {\n flagId = flagDetail.metadata?.id;\n flagVersion = flagDetail.metadata?.version;\n flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;\n flagHasExperiment = flagDetail.metadata?.has_experiment;\n let parsedPayload;\n if (flagDetail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(flagDetail.metadata.payload);\n } catch {\n parsedPayload = flagDetail.metadata.payload;\n }\n result = {\n key,\n enabled: flagDetail.enabled,\n variant: flagDetail.variant ?? void 0,\n payload: parsedPayload\n };\n }\n if (errors.length > 0) featureFlagError = errors.join(',');\n }\n }\n if (sendFeatureFlagEvents) {\n const response = void 0 === result ? void 0 : false === result.enabled ? false : result.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flagId,\n $feature_flag_version: flagVersion,\n $feature_flag_reason: flagReason,\n locally_evaluated: flagWasLocallyEvaluated,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: requestId,\n $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt\n };\n if (void 0 !== flagHasExperiment) properties.$feature_flag_has_experiment = flagHasExperiment;\n if (flagWasLocallyEvaluated && this.featureFlagsPoller) {\n const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();\n if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;\n }\n if (featureFlagError) properties.$feature_flag_error = featureFlagError;\n this._captureFlagCalledEventIfNeeded({\n distinctId,\n key,\n response,\n groups,\n disableGeoip,\n properties\n });\n }\n if (void 0 !== result && void 0 !== this._payloadOverrides && key in this._payloadOverrides) result = {\n ...result,\n payload: this._payloadOverrides[key]\n };\n return result;\n }\n async getFeatureFlag(key, distinctId, options) {\n emitDeprecationWarningOnce('getFeatureFlag', \"`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n return result.variant ?? true;\n }\n async getFeatureFlagPayload(key, distinctId, matchValue, options) {\n emitDeprecationWarningOnce('getFeatureFlagPayload', \"`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n if (void 0 !== this._payloadOverrides && key in this._payloadOverrides) return this._payloadOverrides[key];\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: false\n }, matchValue);\n if (void 0 === result) return;\n return result.payload ?? null;\n }\n async getFeatureFlagResult(key, distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) return void this._logger.warn(\"[PostHog] distinctId is required \\u2014 pass it explicitly or use withContext()\");\n return this._getFeatureFlagResult(key, resolvedDistinctId, {\n ...resolvedOptions,\n sendFeatureFlagEvents: resolvedOptions?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n }\n async getRemoteConfigPayload(flagKey) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this.options.personalApiKey) throw new Error('Personal API key is required for remote config payload decryption');\n const response = await this._requestRemoteConfigPayload(flagKey);\n if (!response) return;\n const parsed = await response.json();\n if ('string' == typeof parsed) try {\n return JSON.parse(parsed);\n } catch (e) {}\n return parsed;\n }\n async isFeatureEnabled(key, distinctId, options) {\n emitDeprecationWarningOnce('isFeatureEnabled', \"`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n const feat = result.variant ?? true;\n return !!feat || false;\n }\n async getAllFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags \\u2014 pass it explicitly or use withContext()\");\n return {};\n }\n const response = await this.getAllFlagsAndPayloads(resolvedDistinctId, resolvedOptions);\n return response.featureFlags || {};\n }\n async getAllFlagsAndPayloads(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags and payloads \\u2014 pass it explicitly or use withContext()\");\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n let featureFlags = {};\n let featureFlagPayloads = {};\n let fallbackToFlags = true;\n if (localEvaluationResult) {\n featureFlags = localEvaluationResult.response;\n featureFlagPayloads = localEvaluationResult.payloads;\n fallbackToFlags = localEvaluationResult.fallbackToFlags;\n }\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n featureFlags = {\n ...featureFlags,\n ...remoteEvaluationResult.flags || {}\n };\n featureFlagPayloads = {\n ...featureFlagPayloads,\n ...remoteEvaluationResult.payloads || {}\n };\n }\n if (void 0 !== this._flagOverrides) featureFlags = {\n ...featureFlags,\n ...this._flagOverrides\n };\n if (void 0 !== this._payloadOverrides) featureFlagPayloads = {\n ...featureFlagPayloads,\n ...this._payloadOverrides\n };\n return {\n featureFlags,\n featureFlagPayloads\n };\n }\n async evaluateFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to evaluate feature flags \\u2014 pass it explicitly or use withContext()\");\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: '',\n flags: {}\n });\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n flags: {}\n });\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const requestedFlagKeys = flagKeys ? new Set(flagKeys) : void 0;\n const records = {};\n let requestId;\n let evaluatedAt;\n let errorsWhileComputing = false;\n let quotaLimited = false;\n const localResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n const locallyEvaluatedKeys = new Set();\n if (localResult) for (const [key, value] of Object.entries(localResult.response)){\n const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payloads[key],\n id: flagDef?.id,\n version: void 0,\n reason: 'Evaluated locally',\n locallyEvaluated: true,\n hasExperiment: flagDef?.has_experiment\n };\n locallyEvaluatedKeys.add(key);\n }\n const requestedFlagMissingLocally = void 0 !== requestedFlagKeys && Array.from(requestedFlagKeys).some((key)=>this.featureFlagsPoller?.featureFlagsByKey[key] === void 0);\n const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n if (details) {\n this._minimalFlagCalledEvents = true === details.minimalFlagCalledEvents;\n requestId = details.requestId;\n evaluatedAt = details.evaluatedAt;\n errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);\n quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');\n for (const [key, detail] of Object.entries(details.flags)){\n if (locallyEvaluatedKeys.has(key)) continue;\n let parsedPayload;\n if (detail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(detail.metadata.payload);\n } catch {\n parsedPayload = detail.metadata.payload;\n }\n records[key] = {\n key,\n enabled: detail.enabled,\n variant: detail.variant,\n payload: parsedPayload,\n id: detail.metadata?.id,\n version: detail.metadata?.version,\n reason: detail.reason?.description ?? detail.reason?.code,\n locallyEvaluated: false,\n hasExperiment: detail.metadata?.has_experiment\n };\n }\n }\n }\n if (void 0 !== this._flagOverrides) for (const [key, value] of Object.entries(this._flagOverrides)){\n if (void 0 === value) {\n delete records[key];\n continue;\n }\n const existing = records[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: existing?.payload,\n id: existing?.id,\n version: existing?.version,\n reason: existing?.reason,\n locallyEvaluated: existing?.locallyEvaluated ?? false,\n hasExperiment: existing?.hasExperiment\n };\n }\n if (void 0 !== this._payloadOverrides) for (const [key, payload] of Object.entries(this._payloadOverrides)){\n const existing = records[key];\n if (existing) records[key] = {\n ...existing,\n payload\n };\n }\n if (void 0 !== requestedFlagKeys) {\n for (const key of Object.keys(records))if (!requestedFlagKeys.has(key)) delete records[key];\n }\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n groups,\n disableGeoip,\n flags: records,\n requestId,\n evaluatedAt,\n flagDefinitionsLoadedAt: this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),\n errorsWhileComputing,\n quotaLimited\n });\n }\n _shouldSendMinimalFlagCalledEvent(event, properties) {\n return '$feature_flag_called' === event && this._minimalFlagCalledEvents && false === properties.$feature_flag_has_experiment;\n }\n _captureFlagCalledEventIfNeeded(params) {\n const { distinctId, key, response, groups, disableGeoip, properties } = params;\n const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0))}` : '';\n const featureFlagReportedKey = `${key}_${response}${groupSuffix}`;\n if (distinctId in this.distinctIdHasSentFlagCalls && this.distinctIdHasSentFlagCalls[distinctId].has(featureFlagReportedKey)) return;\n if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};\n if (this.distinctIdHasSentFlagCalls[distinctId] instanceof Set) this.distinctIdHasSentFlagCalls[distinctId].add(featureFlagReportedKey);\n else this.distinctIdHasSentFlagCalls[distinctId] = new Set([\n featureFlagReportedKey\n ]);\n this.capture({\n distinctId,\n event: '$feature_flag_called',\n properties,\n groups,\n disableGeoip\n });\n }\n _getFeatureFlagEvaluationsHost() {\n if (!this._featureFlagEvaluationsHost) this._featureFlagEvaluationsHost = {\n captureFlagCalledEventIfNeeded: (params)=>this._captureFlagCalledEventIfNeeded(params),\n logWarning: (message)=>{\n if (false !== this.options.featureFlagsLogWarnings) console.warn(`[PostHog] ${message}`);\n }\n };\n return this._featureFlagEvaluationsHost;\n }\n groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n await this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n async reloadFeatureFlags() {\n await this.featureFlagsPoller?.loadFeatureFlags(true);\n }\n overrideFeatureFlags(overrides) {\n const flagArrayToRecord = (flags)=>Object.fromEntries(flags.map((f)=>[\n f,\n true\n ]));\n if (false === overrides) {\n this._flagOverrides = void 0;\n this._payloadOverrides = void 0;\n return;\n }\n if (Array.isArray(overrides)) {\n this._flagOverrides = flagArrayToRecord(overrides);\n return;\n }\n if (this._isFeatureFlagOverrideOptions(overrides)) {\n if ('flags' in overrides) {\n if (false === overrides.flags) this._flagOverrides = void 0;\n else if (Array.isArray(overrides.flags)) this._flagOverrides = flagArrayToRecord(overrides.flags);\n else if (void 0 !== overrides.flags) this._flagOverrides = {\n ...overrides.flags\n };\n }\n if ('payloads' in overrides) {\n if (false === overrides.payloads) this._payloadOverrides = void 0;\n else if (void 0 !== overrides.payloads) this._payloadOverrides = {\n ...overrides.payloads\n };\n }\n return;\n }\n this._flagOverrides = {\n ...overrides\n };\n }\n _isFeatureFlagOverrideOptions(overrides) {\n if ('object' != typeof overrides || null === overrides || Array.isArray(overrides)) return false;\n const obj = overrides;\n if ('flags' in obj) {\n const flagsValue = obj['flags'];\n if (false === flagsValue || Array.isArray(flagsValue) || 'object' == typeof flagsValue && null !== flagsValue) return true;\n }\n if ('payloads' in obj) {\n const payloadsValue = obj['payloads'];\n if (false === payloadsValue || 'object' == typeof payloadsValue && null !== payloadsValue) return true;\n }\n return false;\n }\n withContext(data, fn, options) {\n if (!this.context) return fn();\n return this.context.run(data, fn, options);\n }\n getContext() {\n return this.context?.get();\n }\n enterContext(data, options) {\n this.context?.enter(data, options);\n }\n async _shutdown(shutdownTimeoutMs) {\n const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);\n const resolve = this._consumeWaitUntilCycle();\n await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);\n this.errorTracking.shutdown();\n if (this._metrics) {\n await raceWithTimeout(this._metrics.flush().catch(()=>{}), Math.max(0, shutdownDeadlineMs - Date.now()));\n this._metrics.reset();\n }\n try {\n return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));\n } finally{\n this.distinctIdHasSentFlagCalls = {};\n resolve?.();\n }\n }\n async _requestRemoteConfigPayload(flagKey) {\n if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;\n const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;\n const options = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.options.personalApiKey}`\n }\n };\n let abortTimeout = null;\n if (this.options.requestTimeout && 'number' == typeof this.options.requestTimeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.options.requestTimeout);\n options.signal = controller.signal;\n }\n try {\n return await this.fetch(url, options);\n } catch (error) {\n this._events.emit('error', error);\n return;\n } finally{\n if (abortTimeout) clearTimeout(abortTimeout);\n }\n }\n extractPropertiesFromEvent(eventProperties, groups) {\n if (!eventProperties) return {\n personProperties: {},\n groupProperties: {}\n };\n const personProperties = {};\n const groupProperties = {};\n for (const [key, value] of Object.entries(eventProperties))if (isPlainObject(value) && groups && key in groups) {\n const groupProps = {};\n for (const [groupKey, groupValue] of Object.entries(value))groupProps[String(groupKey)] = String(groupValue);\n groupProperties[String(key)] = groupProps;\n } else personProperties[String(key)] = String(value);\n return {\n personProperties,\n groupProperties\n };\n }\n async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {\n if (this.disabled || !this.apiKey) return void this._logger.warn('The client is disabled');\n const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};\n const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};\n const flagKeys = sendFeatureFlagsOptions?.flagKeys;\n const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? this.options.strictLocalEvaluation ?? false;\n if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};\n else {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;\n }\n addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {\n const allPersonProperties = {\n ...personProperties || {}\n };\n const allGroupProperties = {};\n if (groups) for (const groupName of Object.keys(groups))allGroupProperties[groupName] = {\n $group_key: groups[groupName],\n ...groupProperties?.[groupName] || {}\n };\n return {\n allPersonProperties,\n allGroupProperties\n };\n }\n personPropertiesForLocalEvaluation(distinctId, personProperties) {\n return {\n distinct_id: distinctId,\n ...personProperties || {}\n };\n }\n createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {\n return {\n distinctId,\n groups: groups || {},\n personProperties: personProperties || {},\n groupProperties: groupProperties || {},\n evaluationCache: {}\n };\n }\n captureException(error, distinctId, additionalProperties, uuid, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this._capturePreparedEvent({\n ...msg,\n uuid,\n flags\n }, false)));\n }\n }\n async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this.captureImmediate({\n ...msg,\n flags\n })));\n }\n }\n async prepareEventMessage(props) {\n return this._prepareEventMessage(props);\n }\n async _prepareEventMessage(props, options = {}) {\n const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;\n const contextData = this.context?.get();\n const includeContextProperties = options.includeContextProperties ?? true;\n let mergedDistinctId = distinctId || contextData?.distinctId;\n const mergedProperties = includeContextProperties ? {\n ...this.props,\n ...contextData?.properties || {},\n ...properties || {}\n } : {\n ...properties || {}\n };\n if (!mergedDistinctId) {\n mergedDistinctId = uuidv7();\n mergedProperties.$process_person_profile = false;\n }\n if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;\n const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;\n const eventMessage = this._runBeforeSend({\n distinctId: mergedDistinctId,\n event,\n properties: finalProperties,\n groups,\n flags,\n sendFeatureFlags,\n timestamp,\n disableGeoip,\n uuid\n });\n if (!eventMessage) return Promise.reject(null);\n const eventProperties = await Promise.resolve().then(async ()=>{\n if (flags) {\n if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');\n return flags._getEventProperties();\n }\n if (sendFeatureFlags) {\n emitDeprecationWarningOnce('sendFeatureFlags', \"`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.\");\n const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;\n const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);\n return buildFlagEventProperties(flagValues);\n }\n return {};\n }).catch(()=>({})).then((additionalProperties)=>{\n const resolvedGroups = eventMessage.groups || groups;\n return {\n ...additionalProperties,\n ...eventMessage.properties || {},\n ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {\n $groups: resolvedGroups\n } : {}\n };\n });\n if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {\n if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {\n eventMessage.event = '$bot_pageview';\n eventProperties.$browser_type = 'bot';\n }\n }\n return {\n distinctId: eventMessage.distinctId,\n event: eventMessage.event,\n properties: eventProperties,\n options: {\n timestamp: eventMessage.timestamp,\n disableGeoip: eventMessage.disableGeoip,\n uuid: eventMessage.uuid\n }\n };\n }\n _runBeforeSend(eventMessage) {\n const beforeSend = this.options.before_send;\n if (!beforeSend) return eventMessage;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = eventMessage;\n for (const fn of fns)try {\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);\n return null;\n }\n if (!result.properties || 0 === Object.keys(result.properties).length) {\n const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;\n this._logger.warn(message);\n }\n } catch (error) {\n this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);\n return null;\n }\n return result;\n }\n}\nexport { PostHogBackendClient, _resetDeprecationWarningsForTests };\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nclass PostHogContext {\n constructor(){\n this.storage = new AsyncLocalStorage();\n }\n get() {\n return this.storage.getStore();\n }\n run(context, fn, options) {\n return this.storage.run(this.resolve(context, options), fn);\n }\n enter(context, options) {\n this.storage.enterWith(this.resolve(context, options));\n }\n resolve(context, options) {\n if (options?.fresh === true) return context;\n const current = this.get() || {};\n return {\n distinctId: context.distinctId ?? current.distinctId,\n sessionId: context.sessionId ?? current.sessionId,\n properties: {\n ...current.properties || {},\n ...context.properties || {}\n }\n };\n }\n}\nexport { PostHogContext };\n","import { gzip } from \"node:zlib\";\nimport { promisify } from \"node:util\";\nconst gzipAsync = promisify(gzip);\nasync function gzipCompress(input, isDebug = true) {\n try {\n const compressed = await gzipAsync(input);\n return new Uint8Array(compressed);\n } catch (error) {\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress };\n","import { ErrorTracking } from \"@posthog/core\";\nconst NAME = 'posthog-node';\nfunction createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [\n 'error'\n], sendExceptionsToPostHog = true } = {}) {\n return (event)=>{\n const shouldProcessLevel = '*' === severityAllowList || severityAllowList.includes(event.level);\n if (!shouldProcessLevel) return event;\n if (!event.tags) event.tags = {};\n const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];\n if (void 0 === userId) return event;\n const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';\n const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();\n event.tags['PostHog Person URL'] = personUrl;\n const exceptions = event.exception?.values || [];\n const exceptionList = exceptions.map((exception)=>({\n ...exception,\n stacktrace: exception.stacktrace ? {\n ...exception.stacktrace,\n type: 'raw',\n frames: (exception.stacktrace.frames || []).map((frame)=>({\n ...frame,\n platform: \"node:javascript\"\n }))\n } : void 0\n }));\n const properties = {\n $exception_message: exceptions[0]?.value || event.message,\n $exception_type: exceptions[0]?.type,\n $exception_level: event.level,\n $exception_list: exceptionList,\n $sentry_event_id: event.event_id,\n $sentry_exception: event.exception,\n $sentry_exception_message: exceptions[0]?.value || event.message,\n $sentry_exception_type: exceptions[0]?.type,\n $sentry_tags: event.tags\n };\n const injectedReleaseId = ErrorTracking.getInjectedReleaseId();\n if (injectedReleaseId) properties.$release_id = injectedReleaseId;\n if (organization && projectId) properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;\n if (sendExceptionsToPostHog) _posthog.capture({\n event: '$exception',\n distinctId: userId,\n properties\n });\n return event;\n };\n}\nfunction sentryIntegration(_posthog, options) {\n const processor = createEventProcessor(_posthog, options);\n return {\n name: NAME,\n processEvent (event) {\n return processor(event);\n }\n };\n}\nclass PostHogSentryIntegration {\n static #_ = this.POSTHOG_ID_TAG = 'posthog_distinct_id';\n constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog){\n this.name = NAME;\n this.name = NAME;\n this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {\n const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;\n addGlobalEventProcessor(createEventProcessor(_posthog, {\n organization,\n projectId,\n prefix,\n severityAllowList,\n sendExceptionsToPostHog: sendExceptionsToPostHog ?? true\n }));\n };\n }\n}\nexport { PostHogSentryIntegration, createEventProcessor, sentryIntegration };\n","const TRACING_HEADER_MAX_LENGTH = 1000;\nconst TRACING_HEADER_CONTROL_CHARS_REGEX = /[\\x00-\\x1f\\x7f-\\x9f]/g;\nconst POSTHOG_TRACING_HEADERS = {\n sessionId: 'x-posthog-session-id',\n distinctId: 'x-posthog-distinct-id'\n};\nfunction addProperty(properties, key, value) {\n if (null != value && '' !== value) properties[key] = value;\n}\nfunction getFirstHeaderValue(value) {\n return Array.isArray(value) ? value[0] : value;\n}\nfunction sanitizeTracingHeaderValue(value) {\n if (Array.isArray(value)) {\n for (const item of value){\n const sanitized = sanitizeTracingHeaderValue(item);\n if (void 0 !== sanitized) return sanitized;\n }\n return;\n }\n if ('string' != typeof value) return;\n const sanitized = value.replace(TRACING_HEADER_CONTROL_CHARS_REGEX, '').trim();\n if (!sanitized) return;\n return sanitized.length > TRACING_HEADER_MAX_LENGTH ? sanitized.slice(0, TRACING_HEADER_MAX_LENGTH) : sanitized;\n}\nfunction getPostHogTracingHeaderValues(headers) {\n if (!headers) return {};\n const sessionId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.sessionId]);\n const distinctId = sanitizeTracingHeaderValue(headers[POSTHOG_TRACING_HEADERS.distinctId]);\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {}\n };\n}\nexport { POSTHOG_TRACING_HEADERS, addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues, sanitizeTracingHeaderValue };\n","import { stripUrlHash } from \"@posthog/core\";\nfunction normalizeRequestCurrentUrl(currentUrl, disableCaptureUrlHashes) {\n return disableCaptureUrlHashes ? stripUrlHash(currentUrl) : currentUrl;\n}\nfunction normalizeRequestPath(path, disableCaptureUrlHashes) {\n const pathWithoutSearch = stripUrlSearch(path);\n return disableCaptureUrlHashes ? stripUrlHash(pathWithoutSearch) : pathWithoutSearch;\n}\nfunction stripUrlSearch(url) {\n if (!url) return url;\n const searchIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n if (-1 === searchIndex || -1 !== hashIndex && hashIndex < searchIndex) return url;\n return `${url.slice(0, searchIndex)}${-1 === hashIndex ? '' : url.slice(hashIndex)}`;\n}\nexport { normalizeRequestCurrentUrl, normalizeRequestPath };\n","import error_tracking from \"./error-tracking/index.mjs\";\nimport { addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues } from \"./tracing-headers.mjs\";\nimport { normalizeRequestCurrentUrl, normalizeRequestPath } from \"./url-utils.mjs\";\nfunction getClientIp(req) {\n const forwarded = getFirstHeaderValue(req.headers['x-forwarded-for']);\n if (forwarded) {\n const ip = forwarded.split(',')[0].trim();\n if (ip) return ip;\n }\n return req.socket?.remoteAddress;\n}\nfunction buildRequestContextData(posthog, req) {\n const { sessionId, distinctId } = getPostHogTracingHeaderValues(req.headers);\n const properties = {};\n const disableCaptureUrlHashes = true === posthog.options.disable_capture_url_hashes;\n addProperty(properties, '$current_url', normalizeRequestCurrentUrl(req.originalUrl || req.url, disableCaptureUrlHashes));\n addProperty(properties, '$request_method', req.method);\n addProperty(properties, '$request_path', normalizeRequestPath(req.path, disableCaptureUrlHashes));\n addProperty(properties, '$user_agent', getFirstHeaderValue(req.headers['user-agent']));\n addProperty(properties, '$ip', getClientIp(req));\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {},\n properties\n };\n}\nfunction setupExpressRequestContext(_posthog, app) {\n app.use(posthogRequestContext(_posthog));\n}\nfunction posthogRequestContext(posthog) {\n return (req, _res, next)=>{\n posthog.withContext(buildRequestContextData(posthog, req), ()=>next());\n };\n}\nfunction setupExpressErrorHandler(_posthog, app) {\n app.use(posthogErrorHandler(_posthog));\n}\nfunction posthogErrorHandler(posthog) {\n return (error, req, res, next)=>{\n if (error_tracking.isPreviouslyCapturedError(error)) return void next(error);\n const contextData = buildRequestContextData(posthog, req);\n const syntheticException = new Error('Synthetic exception');\n const hint = {\n mechanism: {\n type: 'middleware',\n handled: false\n },\n syntheticException\n };\n const additionalProperties = {\n ...void 0 !== contextData.sessionId ? {\n $session_id: contextData.sessionId\n } : {},\n ...contextData.properties || {},\n $response_status_code: res.statusCode\n };\n posthog.addPendingPromise(error_tracking.buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, contextData.distinctId, additionalProperties).then((msg)=>posthog._capturePreparedEvent(msg, false)));\n next(error);\n };\n}\nexport { setupExpressErrorHandler, setupExpressRequestContext };\n","import { createModulerModifier } from \"../extensions/error-tracking/modifiers/module.node.mjs\";\nimport { addSourceContext } from \"../extensions/error-tracking/modifiers/context-lines.node.mjs\";\nimport { createRelativePathModifier } from \"../extensions/error-tracking/modifiers/relative-path.node.mjs\";\nimport { PostHogBackendClient } from \"../client.mjs\";\nimport { ErrorTracking } from \"@posthog/core\";\nimport { PostHogContext } from \"../extensions/context/context.mjs\";\nimport { gzipCompress } from \"../gzip.node.mjs\";\nexport * from \"../exports.mjs\";\nclass PostHog extends PostHogBackendClient {\n getLibraryId() {\n return 'posthog-node';\n }\n compressPayload(payload) {\n return gzipCompress(payload, this.isDebug);\n }\n initializeContext() {\n return new PostHogContext();\n }\n createErrorPropertiesBuilder() {\n return new ErrorTracking.ErrorPropertiesBuilder([\n new ErrorTracking.EventCoercer(),\n new ErrorTracking.ErrorCoercer(),\n new ErrorTracking.ObjectCoercer(),\n new ErrorTracking.StringCoercer(),\n new ErrorTracking.PrimitiveCoercer()\n ], ErrorTracking.createStackParser(\"node:javascript\", ErrorTracking.nodeStackLineParser), [\n createModulerModifier(),\n (frames)=>addSourceContext(frames, void 0, this._logger),\n createRelativePathModifier()\n ]);\n }\n}\nexport { PostHog };\n","type ShutdownHook = () => void | Promise<void>\n\nconst SIGNAL_SHUTDOWN_TIMEOUT_MS = 2_000\n\nconst hooks = new Set<ShutdownHook>()\nlet signalsBound = false\n\nconst runHooks = async() => {\n await Promise.all([...hooks].map(async(hook) => {\n try {\n await hook()\n } catch (error) {\n console.error(\"[rb/server] shutdown hook error\", error)\n }\n }))\n}\n\nexport const bindShutdownSignals = () => {\n if (signalsBound) return\n signalsBound = true\n\n // Handling a signal disables Node's default exit-on-signal behavior, so we\n // must re-raise it once the hooks are done; `once` keeps a second signal fatal\n const stop = (signal: NodeJS.Signals) => {\n const timeout = new Promise(resolve => setTimeout(resolve, SIGNAL_SHUTDOWN_TIMEOUT_MS).unref())\n void Promise.race([runHooks(), timeout]).finally(() => process.kill(process.pid, signal))\n }\n\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n}\n\nexport const onShutdown = (hook: ShutdownHook) => {\n hooks.add(hook)\n bindShutdownSignals()\n}\n","import type { Application } from \"express\"\nimport { PostHog, setupExpressErrorHandler } from \"posthog-node\"\n\nimport { onShutdown } from \"./shutdown\"\n\n\ntype ServerEnv = Record<string, string | undefined>\n\nlet client: PostHog | null | undefined\nlet shutdownHookBound = false\n\nexport const resolvePosthogApiKey = (env: ServerEnv) => env.RB_PUBLIC_POSTHOG_KEY\n\nexport const resolvePosthogHost = () => \"https://eu.i.posthog.com\"\n\nexport const getPosthogClient = (env: ServerEnv): PostHog | null => {\n if (client !== undefined) return client\n\n const apiKey = resolvePosthogApiKey(env)\n\n if (!apiKey) {\n client = null\n return client\n }\n\n client = new PostHog(apiKey, {\n host: resolvePosthogHost(),\n enableExceptionAutocapture: true,\n flushAt: 1,\n flushInterval: 1_000,\n })\n\n return client\n}\n\nexport const bindExpressErrorHandler = (app: Application, posthog: PostHog | null) => {\n if (!posthog) return\n setupExpressErrorHandler(posthog, app)\n}\n\nexport const captureServerException = (\n error: unknown,\n posthog?: PostHog | null,\n properties?: Record<string, unknown>,\n) => {\n const clientToUse = posthog ?? client ?? null\n\n if (!clientToUse || typeof clientToUse.captureException !== \"function\") return\n\n clientToUse.captureException(error as any, \"server\", properties)\n}\n\nconst shutdown = async() => {\n if (!client) return\n try {\n await client.shutdown()\n } catch (err) {\n console.error(\"posthog shutdown error\", err)\n }\n}\n\nexport const ensurePosthogShutdown = () => {\n if (shutdownHookBound || !client) return\n shutdownHookBound = true\n\n onShutdown(shutdown)\n process.on(\"beforeExit\", shutdown)\n}\n","import type {Application} from \"express\"\nimport httpProxy from \"http-proxy-3\"\n\n\nconst POSTHOG_INGEST_TARGET = \"https://eu.i.posthog.com\"\n\nconst getStatusCode = (errorCode: unknown): number => {\n if (typeof errorCode === \"string\" && /HPE_INVALID/.test(errorCode)) {\n return 502\n }\n\n switch (errorCode) {\n case \"ECONNRESET\":\n case \"ENOTFOUND\":\n case \"ECONNREFUSED\":\n case \"ETIMEDOUT\":\n return 504\n default:\n return 500\n }\n}\n\nconst proxy = httpProxy.createProxyServer({\n changeOrigin: true,\n})\n\nproxy.on(\"error\", (err: any, req: any, res: any) => {\n console.error(`Proxy error: ${err?.message ?? String(err)}`)\n\n if (!res || typeof res.writeHead !== \"function\") return\n if (res.headersSent) return\n\n const statusCode = getStatusCode(err?.code)\n res.writeHead(statusCode)\n\n const host = req?.headers?.host ?? \"\"\n const url = req?.url ?? \"\"\n res.end(`Error occurred while trying to proxy: ${host}${url}`)\n})\n\nexport const metricsIngestProxyMiddleware = (app: Application) => {\n app.use(\"/ingest\", (req, res) => {\n if (!req.url) {\n req.url = \"/\"\n }\n\n proxy.web(req, res, {target: POSTHOG_INGEST_TARGET})\n })\n}\n","import { MongoClient } from \"mongodb\"\n\n\ntype ServerEnv = { [key: string]: string | undefined }\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\nlet hasWarnedNoReplicationEnabled = false\n\nexport const checkInitReplicaSet = async (serverEnv: ServerEnv): Promise<void> => {\n const port = serverEnv.DB_PORT?.trim()\n if (!port) return\n\n const host = (serverEnv.DB_HOST ?? \"localhost\").trim()\n\n const replSetName = \"rs0\"\n const memberHost = `${host}:${port}`\n const maxAttempts = 10\n const serverSelectionTimeoutMs = 2000\n\n const uri = `mongodb://${host}:${port}/?directConnection=true`\n\n const waitForReplicaSetReady = async (admin: any): Promise<void> => {\n const maxWaitAttempts = 10\n\n for (let attempt = 1; attempt <= maxWaitAttempts; attempt++) {\n try {\n const status: any = await admin.command({ replSetGetStatus: 1 })\n const state = Number(status?.myState ?? 0)\n if (status?.ok && (state === 1 || state === 2)) return\n } catch {\n // ignore\n }\n\n await sleep(250 * attempt)\n }\n }\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n let client: MongoClient | null = null\n\n try {\n client = new MongoClient(uri, {\n family: 4,\n serverSelectionTimeoutMS: serverSelectionTimeoutMs,\n connectTimeoutMS: serverSelectionTimeoutMs,\n })\n\n await client.connect()\n\n const admin = client.db(\"admin\").admin()\n await admin.command({ ping: 1 })\n\n try {\n await admin.command({ replSetGetStatus: 1 })\n return\n } catch (error) {\n const codeName = (error as any)?.codeName\n\n if (codeName === \"NotYetInitialized\") {\n try {\n const res: any = await admin.command({\n replSetInitiate: {\n _id: replSetName,\n members: [{ _id: 0, host: memberHost }],\n },\n })\n\n if (res?.ok) {\n console.warn(`[rb/server] MongoDB replica set '${replSetName}' initiated (${memberHost}).`)\n } else {\n console.warn(`[rb/server] MongoDB replica set initiation returned ok=${String(res?.ok)}.`)\n }\n } catch (initError) {\n const initCodeName = (initError as any)?.codeName\n if (initCodeName !== \"AlreadyInitialized\") {\n const message = initError instanceof Error ? initError.message : String(initError)\n console.warn(`[rb/server] MongoDB replica set initiation failed: ${message}`)\n if (initCodeName === \"InvalidReplicaSetConfig\") {\n console.warn(\n \"[rb/server] Hint: the replica set member host must match the mongod address/port. \" +\n `If MongoDB runs in Docker with port mapping, ensure the container listens on ${port} (e.g. mongod --port ${port}) instead of the default 27017.`,\n )\n }\n }\n }\n\n await waitForReplicaSetReady(admin)\n return\n }\n\n if (codeName === \"NoReplicationEnabled\") {\n if (!hasWarnedNoReplicationEnabled) {\n hasWarnedNoReplicationEnabled = true\n console.warn(\n `[rb/server] MongoDB is not started with --replSet ${replSetName} (replication disabled). ` +\n \"Change streams require a replica set; start mongod with --replSet.\",\n )\n }\n return\n }\n\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set check failed: ${message}`)\n return\n }\n } catch (error) {\n if (attempt === maxAttempts) {\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set auto-init skipped (unable to connect to ${host}:${port}): ${message}`)\n return\n }\n\n await sleep(250 * attempt)\n } finally {\n try {\n await client?.close()\n } catch {\n // ignore\n }\n }\n }\n}\n","import fs from \"node:fs\"\nimport fsPromises from \"node:fs/promises\"\nimport inspector from \"node:inspector\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\n\nimport type { Application } from \"express\"\n\n\ntype CoverageRoots = {\n projectRoot: string\n workspaceRoot: string\n}\n\ntype NormalizedPath = {\n absolutePath: string\n relativePath: string\n}\n\ntype CoverageRun = {\n roots: CoverageRoots\n session: inspector.Session\n sourceCache: Map<string, Promise<string>>\n startedAt: number\n}\n\ntype ServerCoverageTarget = \"api\" | \"worker\" | \"ssr\"\n\nconst VITE_FS_PREFIX = \"/@fs/\"\n\nlet activeRun: CoverageRun | null = null\n\nconst post = async <T = any>(\n session: inspector.Session,\n method: string,\n params?: Record<string, unknown>,\n): Promise<T> => {\n return await new Promise<T>((resolve, reject) => {\n session.post(method, params, (error, result) => {\n if (error) {\n reject(error)\n return\n }\n resolve(result as T)\n })\n })\n}\n\nconst describeError = (error: unknown): string => {\n return error instanceof Error ? error.message : String(error)\n}\n\nconst findWorkspaceRoot = (projectRoot: string): string => {\n let dir = path.resolve(projectRoot)\n\n while (true) {\n const pkgPath = path.join(dir, \"package.json\")\n try {\n if (fs.existsSync(pkgPath)) {\n const parsed = JSON.parse(fs.readFileSync(pkgPath, \"utf8\")) as { workspaces?: unknown }\n if (parsed && typeof parsed === \"object\" && parsed.workspaces) {\n return dir\n }\n }\n } catch {\n //\n }\n\n const parent = path.dirname(dir)\n if (parent === dir) {\n return path.resolve(projectRoot)\n }\n dir = parent\n }\n}\n\nconst stripQuery = (url: string): string => {\n const queryIndex = url.indexOf(\"?\")\n const hashIndex = url.indexOf(\"#\")\n\n const endIndex = Math.min(\n queryIndex === -1 ? Number.POSITIVE_INFINITY : queryIndex,\n hashIndex === -1 ? Number.POSITIVE_INFINITY : hashIndex,\n )\n\n if (!Number.isFinite(endIndex)) {\n return url\n }\n\n return url.slice(0, endIndex)\n}\n\nconst resolveAbsoluteFromUrl = (rawUrl: string, roots: CoverageRoots): string | null => {\n const cleaned = stripQuery(rawUrl)\n\n try {\n if (cleaned.startsWith(\"file://\")) {\n return path.normalize(fileURLToPath(cleaned))\n }\n } catch {\n //\n }\n\n let pathname = cleaned\n\n try {\n const parsed = new URL(cleaned)\n pathname = parsed.pathname\n } catch {\n //\n }\n\n const decoded = decodeURIComponent(pathname)\n\n if (decoded.startsWith(VITE_FS_PREFIX)) {\n return path.normalize(decoded.slice(VITE_FS_PREFIX.length))\n }\n\n if (!path.isAbsolute(decoded)) {\n return null\n }\n\n if (fs.existsSync(decoded)) {\n return path.normalize(decoded)\n }\n\n const projectRoot = path.resolve(roots.projectRoot)\n const workspaceRoot = path.resolve(roots.workspaceRoot)\n\n if (decoded.startsWith(projectRoot + path.sep) || decoded.startsWith(workspaceRoot + path.sep)) {\n return path.normalize(decoded)\n }\n\n return path.resolve(projectRoot, `.${decoded}`)\n}\n\nconst normalizeScriptUrl = async (rawUrl: string, roots: CoverageRoots): Promise<NormalizedPath | null> => {\n if (!rawUrl || rawUrl.startsWith(\"node:\")) {\n return null\n }\n\n const absolute = resolveAbsoluteFromUrl(rawUrl, roots)\n if (!absolute) {\n return null\n }\n\n let realPath = absolute\n try {\n realPath = await fsPromises.realpath(absolute)\n } catch {\n //\n }\n\n const normalized = path.normalize(realPath)\n\n if (normalized.includes(`${path.sep}node_modules${path.sep}`)) {\n return null\n }\n\n const workspaceRoot = path.resolve(roots.workspaceRoot)\n const projectRoot = path.resolve(roots.projectRoot)\n\n if (normalized.startsWith(workspaceRoot + path.sep) || normalized === workspaceRoot) {\n return {\n absolutePath: normalized,\n relativePath: path.relative(workspaceRoot, normalized),\n }\n }\n\n if (normalized.startsWith(projectRoot + path.sep) || normalized === projectRoot) {\n return {\n absolutePath: normalized,\n relativePath: path.relative(projectRoot, normalized),\n }\n }\n\n return null\n}\n\nconst fetchScriptSource = async (session: inspector.Session, scriptId: string): Promise<string> => {\n try {\n const response = await post<{ scriptSource?: unknown }>(session, \"Debugger.getScriptSource\", { scriptId })\n return typeof response?.scriptSource === \"string\" ? response.scriptSource : \"\"\n } catch {\n return \"\"\n }\n}\n\nconst resolveScriptSource = async (\n session: inspector.Session,\n cache: Map<string, Promise<string>>,\n scriptId: string,\n): Promise<string> => {\n const cached = cache.get(scriptId)\n if (cached) {\n return await cached\n }\n\n const promise = fetchScriptSource(session, scriptId)\n cache.set(scriptId, promise)\n return await promise\n}\n\nconst shutdownSession = async (session: inspector.Session): Promise<void> => {\n await Promise.allSettled([\n post(session, \"Profiler.stopPreciseCoverage\").catch(() => undefined),\n post(session, \"Profiler.disable\").catch(() => undefined),\n post(session, \"Debugger.disable\").catch(() => undefined),\n ])\n\n try {\n session.disconnect()\n } catch {\n //\n }\n}\n\nconst toPosixPath = (input: string): string => input.split(path.sep).join(\"/\")\n\nconst isSubpath = (candidate: string, root: string): boolean => {\n const relative = path.relative(root, candidate)\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))\n}\n\nconst classifyServerTarget = (absolutePath: string, projectRoot: string): ServerCoverageTarget => {\n if (!isSubpath(absolutePath, projectRoot)) {\n return \"ssr\"\n }\n\n const relative = toPosixPath(path.relative(projectRoot, absolutePath))\n\n if (relative.startsWith(\"src/api/\") || relative.includes(\"/src/api/\")) {\n return \"api\"\n }\n if (relative.startsWith(\"src/worker/\") || relative.includes(\"/src/worker/\")) {\n return \"worker\"\n }\n if (relative.startsWith(\"src/server/\") || relative.includes(\"/src/server/\")) {\n return \"ssr\"\n }\n\n if (relative.startsWith(\"build/dist/api/\") || relative.includes(\"/build/dist/api/\")) {\n return \"api\"\n }\n if (relative.startsWith(\"build/dist/worker/\") || relative.includes(\"/build/dist/worker/\")) {\n return \"worker\"\n }\n if (relative.startsWith(\"build/dist/ssr/\") || relative.includes(\"/build/dist/ssr/\")) {\n return \"ssr\"\n }\n\n return \"ssr\"\n}\n\nexport function registerDevCoverageEndpoints(app: Application): void {\n app.post(\"/api/dev/coverage/start\", async (_req, res) => {\n if (process.env.NODE_ENV === \"production\") {\n res.status(404).json({ error: \"Not Found\" })\n return\n }\n\n if (activeRun) {\n res.json({ ok: true, status: \"already_started\", startedAt: activeRun.startedAt })\n return\n }\n\n const roots = {\n projectRoot: path.resolve(process.cwd()),\n workspaceRoot: findWorkspaceRoot(process.cwd()),\n }\n\n const session = new inspector.Session()\n session.connect()\n\n try {\n await post(session, \"Debugger.enable\")\n await post(session, \"Profiler.enable\")\n await post(session, \"Profiler.startPreciseCoverage\", { callCount: false, detailed: true })\n\n activeRun = {\n roots,\n session,\n sourceCache: new Map(),\n startedAt: Date.now(),\n }\n\n res.json({ ok: true, status: \"started\", startedAt: activeRun.startedAt })\n } catch (error) {\n await shutdownSession(session)\n activeRun = null\n res.status(500).json({ ok: false, error: describeError(error) })\n }\n })\n\n app.post(\"/api/dev/coverage/stop\", async (req, res) => {\n if (process.env.NODE_ENV === \"production\") {\n res.status(404).json({ error: \"Not Found\" })\n return\n }\n\n const run = activeRun\n if (!run) {\n res.status(409).json({ ok: false, error: \"coverage_not_started\" })\n return\n }\n\n activeRun = null\n\n const outputRoot = path.join(run.roots.projectRoot, \"build\", \"coverage\", \"server\")\n const outputFiles: Record<ServerCoverageTarget, string> = {\n api: path.join(outputRoot, \"api\", \"v8-coverage.json\"),\n worker: path.join(outputRoot, \"worker\", \"v8-coverage.json\"),\n ssr: path.join(outputRoot, \"ssr\", \"v8-coverage.json\"),\n }\n\n try {\n const taken = await post<{ result?: unknown }>(run.session, \"Profiler.takePreciseCoverage\")\n const result = Array.isArray(taken?.result) ? (taken.result as any[]) : []\n\n const scriptsByTarget: Record<ServerCoverageTarget, any[]> = {\n api: [],\n worker: [],\n ssr: [],\n }\n\n for (const entry of result) {\n const scriptId = typeof entry?.scriptId === \"string\" ? entry.scriptId : null\n const url = typeof entry?.url === \"string\" ? entry.url : null\n if (!scriptId || !url) {\n continue\n }\n\n const normalized = await normalizeScriptUrl(url, run.roots)\n if (!normalized) {\n continue\n }\n\n const source = await resolveScriptSource(run.session, run.sourceCache, scriptId)\n\n const script = {\n absolutePath: normalized.absolutePath,\n relativePath: normalized.relativePath,\n source,\n functions: Array.isArray(entry?.functions) ? entry.functions : [],\n url,\n }\n\n const target = classifyServerTarget(script.absolutePath, run.roots.projectRoot)\n scriptsByTarget[target].push(script)\n }\n\n await Promise.all(\n (Object.keys(outputFiles) as ServerCoverageTarget[]).map(async (target) => {\n const outputFile = outputFiles[target]\n const payload = {\n testId: `node-${target}`,\n scripts: scriptsByTarget[target],\n }\n\n await fsPromises.mkdir(path.dirname(outputFile), { recursive: true })\n await fsPromises.writeFile(outputFile, JSON.stringify(payload, null, 2), \"utf8\")\n }),\n )\n\n res.json({\n ok: true,\n status: \"stopped\",\n outputFiles,\n scriptCount: {\n api: scriptsByTarget.api.length,\n worker: scriptsByTarget.worker.length,\n ssr: scriptsByTarget.ssr.length,\n },\n })\n } catch (error) {\n res.status(500).json({ ok: false, error: describeError(error) })\n } finally {\n await shutdownSession(run.session)\n }\n })\n}\n","import path from \"node:path\"\n\nimport type {Request, RequestHandler} from \"express\"\n\n\nconst vitePathPrefixes = [\n \"/@fs\",\n \"/@id\",\n \"/@react-refresh\",\n \"/@vite\",\n \"/node_modules\",\n \"/src\",\n]\n\nconst assetDestinations = new Set([\n \"audio\",\n \"audioworklet\",\n \"embed\",\n \"font\",\n \"image\",\n \"manifest\",\n \"object\",\n \"paintworklet\",\n \"script\",\n \"serviceworker\",\n \"sharedworker\",\n \"style\",\n \"track\",\n \"video\",\n \"worker\",\n \"xslt\",\n])\n\nconst isPathAtOrBelow = (requestPath: string, prefix: string): boolean => {\n return requestPath === prefix || requestPath.startsWith(`${prefix}/`)\n}\n\nconst getHeader = (req: Request, name: string): string => {\n const value = req.headers[name]\n return Array.isArray(value) ? value[0] ?? \"\" : value ?? \"\"\n}\n\nexport const isDevelopmentAssetRequest = (req: Request): boolean => {\n if (req.method !== \"GET\" && req.method !== \"HEAD\") return false\n if (isPathAtOrBelow(req.path, \"/api\")) return false\n if (getHeader(req, \"accept\") === \"text/x-vite-ping\") return true\n if (vitePathPrefixes.some((prefix) => isPathAtOrBelow(req.path, prefix))) return true\n\n const destination = getHeader(req, \"sec-fetch-dest\").toLowerCase()\n return assetDestinations.has(destination) && path.posix.extname(req.path) !== \"\"\n}\n\nexport const developmentSessionMiddleware = (sessionMiddleware: RequestHandler): RequestHandler => {\n return (req, res, next) => {\n if (isDevelopmentAssetRequest(req)) {\n next()\n return\n }\n\n sessionMiddleware(req, res, next)\n }\n}\n","import type { Application, RequestHandler } from \"express\"\n\n\nexport const RPCBASE_SERVICE_WORKER_PATH = \"/rpcbase-service-worker.js\"\nexport const RPCBASE_SERVICE_WORKER_MESSAGE_SOURCE = \"@rpcbase/service-worker\"\n\nexport const rpcbaseServiceWorkerSource = `\nconst MESSAGE_SOURCE = ${JSON.stringify(RPCBASE_SERVICE_WORKER_MESSAGE_SOURCE)}\n\nconst getSameOriginWindowClients = async () => {\n const windowClients = await self.clients.matchAll({ type: \"window\", includeUncontrolled: true })\n return windowClients.filter((client) => {\n try {\n return new URL(client.url).origin === self.location.origin\n } catch {\n return false\n }\n })\n}\n\nconst normalizeMessage = (value) => {\n if (!value || typeof value !== \"object\") return null\n if (value.source !== MESSAGE_SOURCE || typeof value.type !== \"string\" || !value.type.trim()) return null\n return {\n source: MESSAGE_SOURCE,\n type: value.type.trim(),\n ...(value.payload === undefined ? {} : { payload: value.payload }),\n }\n}\n\nconst broadcastMessage = async (message, excludedClientId) => {\n const windowClients = await getSameOriginWindowClients()\n for (const client of windowClients) {\n if (client.id === excludedClientId) continue\n client.postMessage(message)\n }\n}\n\nconst showNotificationFromMessage = async (message) => {\n if (message.type !== \"notifications.show\") return false\n const payload = message.payload\n if (!payload || typeof payload !== \"object\") return false\n const title = typeof payload.title === \"string\" ? payload.title.trim() : \"\"\n if (!title) return false\n const options = payload.options && typeof payload.options === \"object\" ? payload.options : undefined\n await self.registration.showNotification(title, options)\n return true\n}\n\nconst fetchAssetWithNetworkRetry = async (request) => {\n try {\n const response = await fetch(request)\n if (response.status < 500) return response\n } catch {\n return fetch(request)\n }\n\n return fetch(request)\n}\n\nconst getTargetUrl = (link, linkMode, client) => {\n try {\n if (linkMode === \"merge_current_search\" && client) {\n const currentUrl = new URL(client.url)\n const actionUrl = new URL(link, currentUrl)\n actionUrl.searchParams.forEach((value, key) => currentUrl.searchParams.set(key, value))\n if (actionUrl.hash) currentUrl.hash = actionUrl.hash\n return currentUrl.origin === self.location.origin ? currentUrl.href : null\n }\n\n const targetUrl = new URL(link, self.location.origin)\n return targetUrl.origin === self.location.origin ? targetUrl.href : null\n } catch {\n return null\n }\n}\n\nself.addEventListener(\"install\", (event) => event.waitUntil(self.skipWaiting()))\n\nself.addEventListener(\"activate\", (event) => {\n event.waitUntil((async () => {\n await self.clients.claim()\n await broadcastMessage({ source: MESSAGE_SOURCE, type: \"worker.ready\" })\n })())\n})\n\nself.addEventListener(\"message\", (event) => {\n const message = normalizeMessage(event.data)\n if (!message) return\n\n event.waitUntil((async () => {\n if (await showNotificationFromMessage(message)) return\n const sourceClientId = event.source && typeof event.source.id === \"string\"\n ? event.source.id\n : undefined\n await broadcastMessage(message, sourceClientId)\n })())\n})\n\nself.addEventListener(\"fetch\", (event) => {\n const request = event.request\n if (request.method !== \"GET\") return\n if (request.destination !== \"script\" && request.destination !== \"style\") return\n if (new URL(request.url).origin !== self.location.origin) return\n event.respondWith(fetchAssetWithNetworkRetry(request))\n})\n\nself.addEventListener(\"push\", (event) => {\n let message = null\n try {\n message = normalizeMessage(event.data ? event.data.json() : null)\n } catch {\n return\n }\n if (!message || message.type !== \"notifications.show\") return\n event.waitUntil(showNotificationFromMessage(message))\n})\n\nself.addEventListener(\"notificationclick\", (event) => {\n event.notification.close()\n event.waitUntil((async () => {\n const data = event.notification.data && typeof event.notification.data === \"object\"\n ? event.notification.data\n : {}\n const link = typeof data.link === \"string\" ? data.link.trim() : \"\"\n const linkMode = data.linkMode === \"merge_current_search\" ? \"merge_current_search\" : \"navigate\"\n const windowClients = await getSameOriginWindowClients()\n const client = windowClients.find((candidate) => candidate.focused) ?? windowClients[0]\n\n if (!link) {\n if (client) await client.focus()\n return\n }\n\n const targetUrl = getTargetUrl(link, linkMode, client)\n if (!targetUrl) return\n\n if (client) {\n try {\n const navigatedClient = await client.navigate(targetUrl)\n await (navigatedClient ?? client).focus()\n return\n } catch {\n await self.clients.openWindow(targetUrl)\n return\n }\n }\n\n await self.clients.openWindow(targetUrl)\n })())\n})\n`.trimStart()\n\nexport const rpcbaseServiceWorkerRequestHandler: RequestHandler = (_req, res) => {\n res.set({\n \"Cache-Control\": \"no-cache\",\n \"Content-Type\": \"application/javascript; charset=utf-8\",\n \"Service-Worker-Allowed\": \"/\",\n \"X-Content-Type-Options\": \"nosniff\",\n })\n res.send(rpcbaseServiceWorkerSource)\n}\n\nexport const registerRpcbaseServiceWorkerRoute = (app: Application): void => {\n app.get(RPCBASE_SERVICE_WORKER_PATH, rpcbaseServiceWorkerRequestHandler)\n}\n","import type { Application, RequestHandler } from \"express\"\nimport session, { type CookieOptions, type SessionOptions } from \"express-session\"\nimport {RedisStore} from \"connect-redis\"\nimport MongoStore from \"connect-mongo\"\nimport {createClient} from \"redis\"\nimport requestIp from \"request-ip\"\nimport { MongoClient } from \"mongodb\"\nimport env from \"@rpcbase/env\"\nimport { initApiClient } from \"@rpcbase/client\"\nimport { getMongoDirectConnection, getMongoUrl } from \"@rpcbase/db/mongo\"\n\nimport { bindExpressErrorHandler, ensurePosthogShutdown, getPosthogClient } from \"./posthog\"\nimport { bindShutdownSignals } from \"./shutdown\"\nimport { getDerivedKey } from \"./getDerivedKey\"\nimport { metricsIngestProxyMiddleware } from \"./metricsIngestProxyMiddleware\"\nimport { checkInitReplicaSet } from \"./checkInitReplicaSet\"\nimport { registerDevCoverageEndpoints } from \"./dev/coverage\"\nimport { syncAuthenticatedSessionMiddleware } from \"./syncAuthenticatedSession\"\nimport { developmentSessionMiddleware } from \"./developmentSessionMiddleware\"\nimport { registerRpcbaseServiceWorkerRoute } from \"./serviceWorker\"\n\n// dotenv setup, merge process env with vite process.env file\nprocess.env = {\n ...env,\n ...__rb_env__,\n ...process.env,\n} as NodeJS.ProcessEnv\n\n\nconst isProduction = process.env.NODE_ENV === \"production\"\n\ntype ServerEnv = { [key: string]: string | undefined }\n\nexport type InitServerOptions = {\n sessions?: boolean\n}\n\nexport type InitServerResult = {\n sessionMiddleware: RequestHandler | undefined\n}\n\ntype InitServerWithSessionsOptions = InitServerOptions & {\n sessions?: true\n}\n\ntype InitServerWithoutSessionsOptions = InitServerOptions & {\n sessions: false\n}\n\nconst SESSION_MAX_AGE_S = 3600 * 24 * 60 // 60 days\n\nconst getMongoSessionUrl = (serverEnv: ServerEnv) => {\n const appName = serverEnv.APP_NAME?.trim()\n if (!appName) {\n throw new Error(\"Missing APP_NAME (required to build MongoDB session store DB name)\")\n }\n\n return getMongoUrl(serverEnv, { dbName: `${appName}-sessions` })\n}\n\nconst createMongoSessionStore = async (serverEnv: ServerEnv) => {\n const mongoUrl = getMongoSessionUrl(serverEnv)\n\n console.log(\"Using MongoDB session store\")\n\n const client = await MongoClient.connect(mongoUrl, {\n family: 4,\n serverSelectionTimeoutMS: 2000,\n connectTimeoutMS: 2000,\n directConnection: getMongoDirectConnection(serverEnv),\n })\n\n const store = MongoStore.create({\n client,\n collectionName: \"sessions\",\n ttl: SESSION_MAX_AGE_S,\n })\n\n await (store as any).collectionP\n return store\n}\n\nconst createRedisSessionStore = async (redisUrl: string) => {\n const reconnectStrategy = (retries: number) => {\n console.log(\"redis_client::rb/server reconnectStrategy::retrying with arg\", retries)\n if (retries < 5) {\n console.log(\"retry count:\", retries, \"retrying in 1s\")\n return 4000\n } else {\n return new Error(\"max retries expired\")\n }\n }\n\n const redisClient = createClient({\n url: redisUrl,\n socket: {\n reconnectStrategy,\n connectTimeout: 10000,\n keepAlive: false,\n },\n })\n\n redisClient.on(\"ready\", () => {\n console.log(\"session-storage::redis_client connected\")\n })\n\n redisClient.on(\"error\", (error) => {\n console.log(\"session-storage::redis_client ERROR\", error)\n })\n\n console.log(\"Using Redis session store\")\n\n await redisClient.connect()\n\n return new RedisStore({\n client: redisClient,\n ttl: SESSION_MAX_AGE_S,\n })\n}\n\n\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerWithoutSessionsOptions,\n): Promise<{ sessionMiddleware: undefined }>\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options?: InitServerWithSessionsOptions,\n): Promise<{ sessionMiddleware: RequestHandler }>\nexport function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerOptions,\n): Promise<InitServerResult>\nexport async function initServer(\n app: Application,\n serverEnv: ServerEnv,\n options: InitServerOptions = {},\n): Promise<InitServerResult> {\n bindShutdownSignals()\n\n await initApiClient({app})\n\n const replicaSetInitPromise = checkInitReplicaSet(serverEnv).catch((error) => {\n const message = error instanceof Error ? error.message : String(error)\n console.warn(`[rb/server] MongoDB replica set auto-init error: ${message}`)\n })\n\n app.disable(\"x-powered-by\")\n\n app.set(\"trust proxy\", true)\n\n app.use(requestIp.mw())\n\n // redirect www to non-www middleware\n app.use((req, res, next) => {\n if (req.headers.host?.startsWith(\"www.\")) {\n const newHost = req.headers.host.replace(\"www.\", \"\")\n return res.redirect(301, `${req.protocol}://${newHost}${req.originalUrl}`)\n }\n next()\n })\n\n registerRpcbaseServiceWorkerRoute(app)\n metricsIngestProxyMiddleware(app)\n\n const posthog = getPosthogClient(serverEnv)\n\n if (posthog) {\n app.locals.posthog = posthog\n bindExpressErrorHandler(app, posthog)\n ensurePosthogShutdown()\n }\n\n if (!isProduction) {\n registerDevCoverageEndpoints(app)\n }\n\n if (options.sessions === false) {\n return {\n sessionMiddleware: undefined,\n }\n }\n\n if (!serverEnv.MASTER_KEY) {\n throw new Error(\"MASTER_KEY must be defined to derive the session secret\")\n }\n if (!serverEnv.RB_PROXY_SHARED_SECRET?.trim()) {\n throw new Error(\"RB_PROXY_SHARED_SECRET must be defined\")\n }\n\n const sessionSecret = getDerivedKey(serverEnv.MASTER_KEY, \"express_session_key\")\n\n const redisUrl = serverEnv.REDIS_URL?.trim()\n\n let store: SessionOptions[\"store\"]\n if (redisUrl) {\n store = await createRedisSessionStore(redisUrl)\n } else {\n await replicaSetInitPromise\n store = await createMongoSessionStore(serverEnv)\n }\n\n const cookie: CookieOptions = {\n maxAge: SESSION_MAX_AGE_S * 1000\n }\n\n if (isProduction) {\n cookie.secure = \"auto\"\n // cookie.domain = \"\"\n }\n\n const sessionConfig: SessionOptions = {\n name: `${serverEnv.APP_NAME?.trim()}-session`,\n store,\n proxy: true,\n resave: false,\n saveUninitialized: false,\n secret: sessionSecret,\n cookie,\n }\n\n const sessionMiddleware = session(sessionConfig)\n\n app.use(isProduction ? sessionMiddleware : developmentSessionMiddleware(sessionMiddleware))\n app.use(syncAuthenticatedSessionMiddleware)\n\n return {\n sessionMiddleware\n }\n}\n","import { scrypt } from \"crypto\"\n\n\nexport async function hashPassword(password: string, salt: string): Promise<Buffer> {\n const keyLength = 64 // Length of the derived key\n const options = {\n N: 8192, // CPU/memory cost parameter\n r: 8, // Block size\n p: 1 // Parallelization factor\n }\n\n // Return a Promise-wrapped scrypt call\n const derivedKey = await new Promise<Buffer>((resolve, reject) => {\n scrypt(password, salt, keyLength, options, (err, derivedKey) => {\n if (err) {\n reject(err)\n } else {\n resolve(derivedKey)\n }\n })\n })\n\n return derivedKey\n}\n","import crypto from \"crypto\"\n\n\nconst PRODUCTION_SCRYPT_PARAMS = {\n N: 8192,\n r: 8,\n p: 4,\n keylen: 64,\n saltBytes: 16,\n maxmemBytes: 256 * 1024 * 1024,\n}\n\nconst DEVELOPMENT_SCRYPT_PARAMS = {\n N: 1024,\n r: 8,\n p: 1,\n keylen: 64,\n saltBytes: 16,\n maxmemBytes: 256 * 1024 * 1024,\n}\n\nconst MAX_SCRYPT_MAXMEM_BYTES = 1024 * 1024 * 1024\nconst MAX_SCRYPT_N = 1_048_576\nconst MAX_SCRYPT_R = 64\nconst MAX_SCRYPT_P = 16\nconst MAX_SCRYPT_KEYLEN = 128\nconst MAX_SCRYPT_SALT_BYTES = 64\n\nexport type HashPasswordForStorageOptions = Partial<{\n N: number\n r: number\n p: number\n keylen: number\n saltBytes: number\n maxmemBytes: number\n}>\n\ntype ScryptParams = {\n N: number\n r: number\n p: number\n keylen: number\n saltBytes: number\n maxmemBytes: number\n}\n\nconst parseEnvInt = (value: unknown): number | undefined => {\n if (typeof value !== \"string\") return undefined\n const trimmed = value.trim()\n if (!trimmed) return undefined\n const parsed = Number(trimmed)\n if (!Number.isSafeInteger(parsed)) return undefined\n return parsed\n}\n\nconst isPowerOfTwo = (value: number) => (value & (value - 1)) === 0\n\nconst estimateScryptMemoryBytes = ({ N, r, p }: Pick<ScryptParams, \"N\" | \"r\" | \"p\">) => {\n return 128 * r * (N + p)\n}\n\nconst isProductionRuntime = () => {\n return process.env.NODE_ENV === \"production\" || globalThis.__rb_env__?.MODE === \"production\"\n}\n\nconst getDefaultScryptParams = (): ScryptParams => {\n return isProductionRuntime() ? PRODUCTION_SCRYPT_PARAMS : DEVELOPMENT_SCRYPT_PARAMS\n}\n\nconst validateScryptParams = (params: ScryptParams): { ok: true } | { ok: false, error: string } => {\n const { N, r, p, keylen, saltBytes, maxmemBytes } = params\n\n if (!Number.isSafeInteger(N) || N < 2 || N > MAX_SCRYPT_N || !isPowerOfTwo(N)) {\n return { ok: false, error: \"invalid_scrypt_N\" }\n }\n\n if (!Number.isSafeInteger(r) || r < 1 || r > MAX_SCRYPT_R) {\n return { ok: false, error: \"invalid_scrypt_r\" }\n }\n\n if (!Number.isSafeInteger(p) || p < 1 || p > MAX_SCRYPT_P) {\n return { ok: false, error: \"invalid_scrypt_p\" }\n }\n\n if (!Number.isSafeInteger(keylen) || keylen < 16 || keylen > MAX_SCRYPT_KEYLEN) {\n return { ok: false, error: \"invalid_scrypt_keylen\" }\n }\n\n if (!Number.isSafeInteger(saltBytes) || saltBytes < 8 || saltBytes > MAX_SCRYPT_SALT_BYTES) {\n return { ok: false, error: \"invalid_scrypt_salt_bytes\" }\n }\n\n if (!Number.isSafeInteger(maxmemBytes) || maxmemBytes < 16 * 1024 * 1024 || maxmemBytes > MAX_SCRYPT_MAXMEM_BYTES) {\n return { ok: false, error: \"invalid_scrypt_maxmem\" }\n }\n\n const estimatedMem = estimateScryptMemoryBytes({ N, r, p })\n if (estimatedMem > maxmemBytes) {\n return { ok: false, error: \"scrypt_params_exceed_maxmem\" }\n }\n\n return { ok: true }\n}\n\nconst getCurrentMaxmemBytes = (opts?: HashPasswordForStorageOptions): number => {\n const envMaxmemBytes = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_MAXMEM_BYTES)\n const maxmemBytes = opts?.maxmemBytes ?? envMaxmemBytes ?? getDefaultScryptParams().maxmemBytes\n\n if (\n !Number.isSafeInteger(maxmemBytes)\n || maxmemBytes < 16 * 1024 * 1024\n || maxmemBytes > MAX_SCRYPT_MAXMEM_BYTES\n ) {\n throw new Error(\"invalid_scrypt_maxmem\")\n }\n\n return maxmemBytes\n}\n\nconst getCurrentScryptParams = (opts?: HashPasswordForStorageOptions): ScryptParams => {\n const envN = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_N)\n const envR = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_R)\n const envP = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_P)\n const envKeylen = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_KEYLEN)\n const envSaltBytes = parseEnvInt(process.env.RB_PASSWORD_SCRYPT_SALT_BYTES)\n const defaults = getDefaultScryptParams()\n\n const params: ScryptParams = {\n N: opts?.N ?? envN ?? defaults.N,\n r: opts?.r ?? envR ?? defaults.r,\n p: opts?.p ?? envP ?? defaults.p,\n keylen: opts?.keylen ?? envKeylen ?? defaults.keylen,\n saltBytes: opts?.saltBytes ?? envSaltBytes ?? defaults.saltBytes,\n maxmemBytes: getCurrentMaxmemBytes(opts),\n }\n\n const validated = validateScryptParams(params)\n if (!validated.ok) {\n throw new Error(validated.error)\n }\n\n return params\n}\n\nconst scryptAsync = async (\n password: string,\n salt: Buffer,\n params: Pick<ScryptParams, \"N\" | \"r\" | \"p\" | \"keylen\" | \"maxmemBytes\">,\n): Promise<Buffer> => {\n const { N, r, p, keylen, maxmemBytes } = params\n\n return await new Promise<Buffer>((resolve, reject) => {\n crypto.scrypt(password, salt, keylen, { N, r, p, maxmem: maxmemBytes }, (err, derivedKey) => {\n if (err) {\n reject(err)\n return\n }\n resolve(derivedKey)\n })\n })\n}\n\nconst base64Regex = /^[A-Za-z0-9+/]+={0,2}$/\n\nconst parseB64 = (value: string): Buffer | null => {\n if (!value) return null\n if (!base64Regex.test(value)) return null\n if (value.length % 4 !== 0) return null\n\n const buf = Buffer.from(value, \"base64\")\n if (buf.length === 0) return null\n if (buf.toString(\"base64\") !== value) return null\n return buf\n}\n\ntype ParsedStoredScryptHash = {\n N: number\n r: number\n p: number\n keylen: number\n salt: Buffer\n dk: Buffer\n}\n\nconst MAX_STORED_PASSWORD_LENGTH = 1024\nconst MAX_STORED_PASSWORD_SECTION_LENGTH = 256\n\nconst parseStoredScryptHash = (stored: string): ParsedStoredScryptHash | null => {\n if (stored.length > MAX_STORED_PASSWORD_LENGTH) return null\n\n const parts = stored.split(\"$\")\n if (parts.length !== 5) return null\n if (parts[0] !== \"\" || parts[1] !== \"scrypt\") return null\n\n const paramsStr = parts[2]\n const saltB64 = parts[3]\n const dkB64 = parts[4]\n\n if (paramsStr.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n if (saltB64.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n if (dkB64.length > MAX_STORED_PASSWORD_SECTION_LENGTH) return null\n\n const kvPairs = paramsStr.split(\",\").filter(Boolean)\n if (kvPairs.length === 0) return null\n\n const params = new Map<string, number>()\n for (const pair of kvPairs) {\n const idx = pair.indexOf(\"=\")\n if (idx <= 0 || idx === pair.length - 1) return null\n const key = pair.slice(0, idx)\n const valueRaw = pair.slice(idx + 1)\n if (!/^[a-zA-Z0-9]+$/.test(key)) return null\n if (params.has(key)) return null\n const value = Number(valueRaw)\n if (!Number.isSafeInteger(value)) return null\n params.set(key, value)\n }\n\n const N = params.get(\"N\")\n const r = params.get(\"r\")\n const p = params.get(\"p\")\n const keylen = params.get(\"keylen\")\n\n if (N === undefined || r === undefined || p === undefined || keylen === undefined) return null\n if (params.size !== 4) return null\n\n const salt = parseB64(saltB64)\n const dk = parseB64(dkB64)\n if (!salt || !dk) return null\n\n if (dk.length !== keylen) return null\n if (salt.length < 8 || salt.length > MAX_SCRYPT_SALT_BYTES) return null\n if (dk.length < 16 || dk.length > MAX_SCRYPT_KEYLEN) return null\n\n const currentMaxmemBytes = getCurrentMaxmemBytes()\n const validated = validateScryptParams({\n N,\n r,\n p,\n keylen,\n saltBytes: salt.length,\n maxmemBytes: currentMaxmemBytes,\n })\n if (!validated.ok) return null\n\n return { N, r, p, keylen, salt, dk }\n}\n\nexport async function hashPasswordForStorage(password: string, opts?: HashPasswordForStorageOptions): Promise<string> {\n const { N, r, p, keylen, saltBytes, maxmemBytes } = getCurrentScryptParams(opts)\n\n const salt = crypto.randomBytes(saltBytes)\n const dk = await scryptAsync(password, salt, { N, r, p, keylen, maxmemBytes })\n\n const saltB64 = salt.toString(\"base64\")\n const dkB64 = dk.toString(\"base64\")\n\n return `$scrypt$N=${N},r=${r},p=${p},keylen=${keylen}$${saltB64}$${dkB64}`\n}\n\nexport async function verifyPasswordFromStorage(password: string, stored: string): Promise<boolean> {\n const parsed = parseStoredScryptHash(stored)\n if (!parsed) return false\n\n const { N, r, p, keylen, salt, dk } = parsed\n const maxmemBytes = getCurrentMaxmemBytes()\n\n let derivedKey: Buffer\n try {\n derivedKey = await scryptAsync(password, salt, { N, r, p, keylen, maxmemBytes })\n } catch {\n return false\n }\n\n if (derivedKey.length !== dk.length) return false\n\n return crypto.timingSafeEqual(dk, derivedKey)\n}\n","/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { Request as ExpressRequest, Response as ExpressResponse } from \"express\"\nimport {\n StaticHandlerContext,\n matchRoutes,\n createPath,\n Location,\n parsePath,\n To,\n} from \"@rpcbase/router\"\n\n\nfunction createKey() {\n return Math.random().toString(36).substring(2, 10)\n}\n\nfunction createLocation(\n current: string | Location,\n to: To,\n state: any = null,\n key?: string,\n): Readonly<Location> {\n const location: Readonly<Location> = {\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\",\n ...(typeof to === \"string\" ? parsePath(to) : to),\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: (to && (to as Location).key) || key || createKey(),\n }\n return location\n}\n\nfunction getShortCircuitMatches(routes: any[]): {\n matches: any[];\n route: any;\n} {\n // Prefer a root layout route if present, otherwise shim in a route object\n const route =\n routes.length === 1\n ? routes[0]\n : routes.find((r) => r.index || !r.path || r.path === \"/\") || {\n id: \"__shim-error-route__\",\n }\n\n return {\n matches: [\n {\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route,\n },\n ],\n route,\n }\n}\n\nconst NOT_FOUND_STATUS = 404\nconst LOADER_TIMEOUT_MS = 10_000\nconst IMMUTABLE_LAZY_ROUTE_KEYS = new Set([\n \"lazy\",\n \"caseSensitive\",\n \"path\",\n \"id\",\n \"index\",\n \"children\",\n])\n\nconst getErrorStatus = (error: any): number | undefined => {\n if (!error) return undefined\n\n const candidate = error?.reason ?? error\n\n if (typeof candidate?.status === \"number\") return candidate.status\n if (typeof candidate?.statusCode === \"number\") return candidate.statusCode\n if (typeof candidate?.response?.status === \"number\") return candidate.response.status\n\n return undefined\n}\n\nconst isResponseLike = (value: unknown): value is Response => {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n typeof (value as any).status === \"number\" &&\n (value as any).headers &&\n typeof (value as any).headers.get === \"function\",\n )\n}\n\nconst isRedirectResponse = (value: unknown): value is Response => {\n if (!isResponseLike(value)) return false\n return (\n value.status >= 300 &&\n value.status < 400 &&\n Boolean(value.headers.get(\"Location\"))\n )\n}\n\nconst getRouteHandleStatusCode = (route: any): number | undefined => {\n if (!route) return undefined\n const handle = route.handle\n if (!handle) return undefined\n\n const candidate = handle.statusCode ?? handle.status ?? handle.httpStatus\n if (typeof candidate === \"number\") return candidate\n return undefined\n}\n\nconst isNotFoundFallbackRoute = (route: any): boolean => {\n if (!route) return false\n if (route.path !== \"*\") return false\n if (route.loader) return false\n if (route.action) return false\n if (route.children?.length) return false\n return true\n}\n\nexport type RouterContextWithRedirect = StaticHandlerContext & {\n redirectResponse?: Response\n redirectRouteId?: string | null\n redirectRoutePath?: string | null\n}\n\nexport async function applyRouteLoaders(\n req: ExpressRequest,\n res: ExpressResponse,\n dataRoutes: any[],\n): Promise<RouterContextWithRedirect> {\n\n const baseUrl = `${req.protocol}://${req.get(\"host\")}`\n const url = new URL(req.originalUrl, baseUrl)\n\n const method = req.method\n const location = createLocation(\"\", createPath(url), null, \"default\")\n\n const baseContext = {\n basename: \"\",\n location,\n loaderHeaders: {},\n actionHeaders: {},\n }\n\n const resolveLazyRoute = async (route: any) => {\n if (!route || typeof route !== \"object\") return\n\n const lazy = route.lazy\n if (typeof lazy !== \"function\") return\n\n const lazyModule = await lazy()\n if (!lazyModule || typeof lazyModule !== \"object\") {\n route.lazy = undefined\n return\n }\n\n for (const [key, value] of Object.entries(lazyModule as Record<string, unknown>)) {\n if (IMMUTABLE_LAZY_ROUTE_KEYS.has(key)) continue\n if (route[key] !== undefined) continue\n route[key] = value\n }\n\n route.lazy = undefined\n }\n\n // Match routes to the current location\n const matches = matchRoutes(dataRoutes, location)\n\n // Handle 404 (no matches)\n if (!matches || matches.length === 0) {\n const error = {\n status: 404,\n statusText: \"Not Found\",\n internal: true,\n data: {\n message: `No route matches URL: ${req.originalUrl}`,\n },\n }\n const { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes)\n\n return {\n ...baseContext,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: { [route.id]: error },\n statusCode: 404,\n }\n }\n\n // Skip if anything but GET\n if (method !== \"GET\") {\n return {\n ...baseContext,\n matches,\n loaderData: {},\n actionData: null,\n errors: null,\n statusCode: 200,\n }\n }\n\n const runLoaderWithTimeout = async (route: any, params: any) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n const err: any = new Error(`Loader timeout after ${LOADER_TIMEOUT_MS}ms`)\n err.status = 504\n console.error(\"[rpcbase timeout][server loader]\", {\n routeId: route.id,\n ms: LOADER_TIMEOUT_MS,\n url: req.originalUrl,\n })\n reject({id: route.id, path: route.path, reason: err})\n }, LOADER_TIMEOUT_MS)\n })\n\n const loaderPromise = (async () => {\n try {\n await resolveLazyRoute(route)\n if (!route.loader) return null\n\n const data = await route.loader({\n params,\n ctx: {req, res},\n })\n return {id: route.id, path: route.path, data}\n } catch (error) {\n throw {id: route.id, path: route.path, reason: error}\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n }\n })()\n\n return Promise.race([loaderPromise, timeoutPromise])\n }\n\n // Collect loader data and errors\n const loaderPromisesResults = await Promise.allSettled(\n matches.map((match) => runLoaderWithTimeout(match.route, match.params)),\n )\n\n const loaderData: Record<string, any> = {}\n // TODO: add i18n error handling\n let errors: Record<string, any> | null = null\n let hasNotFoundError = false\n let hasNonNotFoundError = false\n\n let redirectResponse: Response | null = null\n let redirectRouteId: string | null = null\n let redirectRoutePath: string | null = null\n\n for (const result of loaderPromisesResults) {\n if (result.status === \"fulfilled\") {\n if (result.value) {\n if (isRedirectResponse(result.value.data)) {\n redirectResponse = result.value.data\n redirectRouteId = result.value.id\n redirectRoutePath = result.value.path ?? null\n } else {\n loaderData[result.value.id] = result.value.data\n }\n }\n } else if (result.status === \"rejected\") {\n const id = (result as any).reason?.id\n if (!id) {\n throw new Error(\n `missing route ID in error: ${(result as any).reason}`,\n )\n }\n\n const reasonCandidate =\n (result as any).reason?.reason ?? (result as any).reason\n if (isRedirectResponse(reasonCandidate)) {\n redirectResponse = reasonCandidate\n redirectRouteId = id\n redirectRoutePath = (result as any).reason?.path ?? null\n continue\n }\n if (!errors) {\n errors = {}\n }\n const status = getErrorStatus((result as any).reason)\n if (status === NOT_FOUND_STATUS) {\n hasNotFoundError = true\n } else {\n hasNonNotFoundError = true\n }\n errors[id] = (result as any).reason\n }\n }\n\n if (redirectResponse) {\n return {\n ...baseContext,\n matches,\n loaderData,\n actionData: null,\n errors: null,\n statusCode: redirectResponse.status,\n redirectResponse,\n redirectRouteId,\n redirectRoutePath,\n }\n }\n\n let statusCode = 200\n if (errors) {\n if (hasNonNotFoundError) {\n statusCode = 500\n } else if (hasNotFoundError) {\n statusCode = NOT_FOUND_STATUS\n } else {\n statusCode = 500\n }\n }\n\n if (!errors && statusCode === 200) {\n const leafRoute = matches.at(-1)?.route\n\n const handleStatusCode = getRouteHandleStatusCode(leafRoute)\n if (typeof handleStatusCode === \"number\") {\n statusCode = handleStatusCode\n } else if (isNotFoundFallbackRoute(leafRoute)) {\n statusCode = NOT_FOUND_STATUS\n }\n }\n\n return {\n ...baseContext,\n matches,\n loaderData,\n actionData: null,\n errors,\n statusCode,\n }\n}\n","import type { Request } from \"express\"\nimport {\n STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY,\n type RtsSsrCountRegistration,\n type RtsSsrHydrationCountData,\n type RtsSsrHydrationQueryData,\n type RtsSsrQueryRegistration,\n type RtsSsrRuntime,\n type StaticRpcbaseRtsHydrationData,\n} from \"@rpcbase/client\"\n\nimport {\n buildRtsAbilityFromRequest,\n isRtsRequestAuthorized,\n normalizeRtsQueryOptions,\n resolveRtsRequestTenantId,\n runRtsCount,\n runRtsQuery,\n} from \"./queryExecutor\"\nimport { RTS_QUERY_WINDOW_MAX_COUNT } from \"./queryWindow\"\n\n\nconst DEFAULT_MAX_QUERIES = 32\nconst DEFAULT_MAX_DOCS_PER_QUERY = 500\nconst DEFAULT_MAX_SERIALIZED_BYTES = 200 * 1024\n\nconst makeRegistrationKey = (modelName: string, queryKey: string): string => `${modelName}.${queryKey}`\n\nconst hasSessionUser = (req: Request): boolean => {\n const id = (req.session?.user as { id?: unknown } | undefined)?.id\n return typeof id === \"string\" && id.trim().length > 0\n}\n\nconst escapeForInlineScript = (value: string): string => {\n return value\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\")\n}\n\nconst toSerializedHydrationPayload = (\n payload: StaticRpcbaseRtsHydrationData,\n): StaticRpcbaseRtsHydrationData | null => {\n try {\n return JSON.parse(JSON.stringify(payload)) as StaticRpcbaseRtsHydrationData\n } catch {\n return null\n }\n}\n\nexport type RtsSsrCollector = {\n runtime: RtsSsrRuntime\n hasRegistrations: () => boolean\n resolve: () => Promise<StaticRpcbaseRtsHydrationData | null>\n}\n\nexport const createRtsSsrCollector = (\n req: Request,\n opts?: {\n maxQueries?: number\n maxDocsPerQuery?: number\n maxSerializedBytes?: number\n },\n): RtsSsrCollector => {\n const maxQueries = typeof opts?.maxQueries === \"number\" && opts.maxQueries > 0\n ? Math.floor(opts.maxQueries)\n : DEFAULT_MAX_QUERIES\n const maxDocsPerQuery = typeof opts?.maxDocsPerQuery === \"number\" && opts.maxDocsPerQuery > 0\n ? Math.floor(opts.maxDocsPerQuery)\n : DEFAULT_MAX_DOCS_PER_QUERY\n const maxSerializedBytes = typeof opts?.maxSerializedBytes === \"number\" && opts.maxSerializedBytes > 0\n ? Math.floor(opts.maxSerializedBytes)\n : DEFAULT_MAX_SERIALIZED_BYTES\n\n const registrations = new Map<string, RtsSsrQueryRegistration>()\n const countRegistrations = new Map<string, RtsSsrCountRegistration>()\n const resolved = new Map<string, unknown[]>()\n const resolvedPageInfo = new Map<string, RtsSsrHydrationQueryData[\"pageInfo\"]>()\n const resolvedTotalCount = new Map<string, RtsSsrHydrationQueryData[\"totalCount\"]>()\n const resolvedCounts = new Map<string, RtsSsrHydrationCountData[\"count\"]>()\n\n const runtime: RtsSsrRuntime = {\n registerQuery(query: RtsSsrQueryRegistration) {\n const modelName = typeof query.modelName === \"string\" ? query.modelName.trim() : \"\"\n const queryKey = typeof query.queryKey === \"string\" ? query.queryKey.trim() : \"\"\n if (!modelName || !queryKey) return\n\n const key = makeRegistrationKey(modelName, queryKey)\n if (registrations.has(key)) return\n if (registrations.size + countRegistrations.size >= maxQueries) return\n\n registrations.set(key, {\n modelName: modelName as RtsSsrQueryRegistration[\"modelName\"],\n queryKey,\n query: query.query ?? {},\n options: query.options ?? {},\n })\n },\n registerCount(query: RtsSsrCountRegistration) {\n const modelName = typeof query.modelName === \"string\" ? query.modelName.trim() : \"\"\n const queryKey = typeof query.queryKey === \"string\" ? query.queryKey.trim() : \"\"\n if (!modelName || !queryKey) return\n\n const key = makeRegistrationKey(modelName, queryKey)\n if (countRegistrations.has(key)) return\n if (registrations.size + countRegistrations.size >= maxQueries) return\n\n countRegistrations.set(key, {\n modelName: modelName as RtsSsrCountRegistration[\"modelName\"],\n queryKey,\n query: query.query ?? {},\n options: query.options ?? {},\n })\n },\n getQueryData(modelName: string, queryKey: string) {\n return resolved.get(makeRegistrationKey(modelName, queryKey))\n },\n getQueryPageInfo(modelName: string, queryKey: string) {\n return resolvedPageInfo.get(makeRegistrationKey(modelName, queryKey))\n },\n getQueryTotalCount(modelName: string, queryKey: string) {\n return resolvedTotalCount.get(makeRegistrationKey(modelName, queryKey))\n },\n getCount(modelName: string, queryKey: string) {\n return resolvedCounts.get(makeRegistrationKey(modelName, queryKey))\n },\n }\n\n const resolve = async (): Promise<StaticRpcbaseRtsHydrationData | null> => {\n if (!registrations.size && !countRegistrations.size) return null\n\n const tenantId = resolveRtsRequestTenantId(req)\n if (!tenantId) return null\n\n if (hasSessionUser(req) && !isRtsRequestAuthorized(req, tenantId)) {\n return null\n }\n\n const { ability, userId } = await buildRtsAbilityFromRequest(req, tenantId)\n const queryEntries: RtsSsrHydrationQueryData[] = []\n const countEntries: RtsSsrHydrationCountData[] = []\n\n for (const registration of registrations.values()) {\n const options = normalizeRtsQueryOptions(registration.options)\n\n try {\n const result = await runRtsQuery({\n tenantId,\n ability,\n modelName: registration.modelName,\n query: registration.query,\n options,\n ...(options.pagination\n ? {\n paginationMaxLimit: RTS_QUERY_WINDOW_MAX_COUNT,\n includePaginationCursors: false,\n }\n : {}),\n })\n\n const boundedData = maxDocsPerQuery > 0 ? result.data.slice(0, maxDocsPerQuery) : result.data\n queryEntries.push({\n modelName: registration.modelName,\n queryKey: registration.queryKey,\n data: boundedData,\n ...(result.pageInfo ? { pageInfo: result.pageInfo } : {}),\n ...(typeof result.totalCount === \"number\" ? { totalCount: result.totalCount } : {}),\n })\n } catch {\n continue\n }\n }\n\n for (const registration of countRegistrations.values()) {\n try {\n const count = await runRtsCount({\n tenantId,\n ability,\n modelName: registration.modelName,\n query: registration.query,\n })\n\n countEntries.push({\n modelName: registration.modelName,\n queryKey: registration.queryKey,\n count,\n })\n } catch {\n continue\n }\n }\n\n if (!queryEntries.length && !countEntries.length) return null\n\n const payload: StaticRpcbaseRtsHydrationData = {\n v: 1,\n tenantId,\n uid: userId,\n queries: [],\n counts: [],\n }\n\n for (const entry of queryEntries) {\n payload.queries.push(entry)\n const bytes = Buffer.byteLength(JSON.stringify(payload), \"utf8\")\n if (bytes > maxSerializedBytes) {\n payload.queries.pop()\n break\n }\n }\n\n for (const entry of countEntries) {\n payload.counts.push(entry)\n const bytes = Buffer.byteLength(JSON.stringify(payload), \"utf8\")\n if (bytes > maxSerializedBytes) {\n payload.counts.pop()\n break\n }\n }\n\n const serializedPayload = toSerializedHydrationPayload(payload)\n if (!serializedPayload || (!serializedPayload.queries.length && !serializedPayload.counts.length)) return null\n\n resolved.clear()\n resolvedPageInfo.clear()\n resolvedTotalCount.clear()\n resolvedCounts.clear()\n for (const entry of serializedPayload.queries) {\n resolved.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.data)\n resolvedPageInfo.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.pageInfo)\n resolvedTotalCount.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.totalCount)\n }\n for (const entry of serializedPayload.counts) {\n resolvedCounts.set(makeRegistrationKey(entry.modelName, entry.queryKey), entry.count)\n }\n\n return serializedPayload\n }\n\n const hasRegistrations = (): boolean => registrations.size > 0 || countRegistrations.size > 0\n\n return { runtime, hasRegistrations, resolve }\n}\n\nexport const renderRtsHydrationScript = (\n data: StaticRpcbaseRtsHydrationData | null | undefined,\n): string => {\n if (!data) return \"\"\n const serialized = escapeForInlineScript(JSON.stringify(data))\n return `<script>window.${STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY}=${serialized};</script>`\n}\n","import { Writable } from \"node:stream\"\n\nimport * as express from \"express\"\nimport { ReactNode, StrictMode } from \"react\"\nimport { renderToPipeableStream } from \"react-dom/server\"\nimport {\n createStaticRouter,\n StaticRouterProvider,\n StaticHandler,\n} from \"@rpcbase/router\"\nimport {\n RtsSsrRuntimeProvider,\n type RtsSsrRuntime,\n type StaticRpcbaseRtsHydrationData,\n} from \"@rpcbase/client\"\n\n\nimport { applyRouteLoaders } from \"./applyRouteLoaders\"\nimport { createRtsSsrCollector } from \"./rts/ssrHydration\"\nimport { resolveRtsRequestTenantId } from \"./rts/queryExecutor\"\n\n\nconst RTS_SSR_PREPASS_TIMEOUT_MS = 4000\nconst SSR_IDENTIFIER_PREFIX = \"rb-\"\n\nexport const runRtsPrepass = async (element: ReactNode): Promise<boolean> => {\n return await new Promise<boolean>((resolve) => {\n let isDone = false\n let timeoutId: ReturnType<typeof setTimeout> | null = null\n\n const finish = (ok: boolean) => {\n if (isDone) return\n isDone = true\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n resolve(ok)\n }\n\n const sink = new Writable({\n write(_chunk, _encoding, callback) {\n callback()\n },\n })\n\n sink.on(\"finish\", () => {\n finish(true)\n })\n sink.on(\"error\", () => {\n finish(false)\n })\n\n const { pipe, abort } = renderToPipeableStream(element, {\n identifierPrefix: SSR_IDENTIFIER_PREFIX,\n onAllReady() {\n if (isDone) return\n pipe(sink)\n },\n onShellError() {\n finish(false)\n },\n onError() {\n //\n },\n })\n\n timeoutId = setTimeout(() => {\n finish(false)\n abort()\n }, RTS_SSR_PREPASS_TIMEOUT_MS)\n })\n}\n\n\n// https://api.reactrouter.com/v7/functions/react_router.StaticRouter.html\nexport async function renderSSR(\n req: express.Request,\n res: express.Response,\n dataRoutes: StaticHandler[\"dataRoutes\"],\n): Promise<{\n element: ReactNode | null\n isMatched: boolean\n statusCode: number\n rtsHydrationData?: StaticRpcbaseRtsHydrationData | null\n redirectResponse?: Response\n redirectRouteId?: string | null\n redirectRoutePath?: string | null\n}> {\n\n const routerContext = await applyRouteLoaders(req, res, dataRoutes)\n const isMatched = routerContext.matches.length > 0\n\n if (routerContext.redirectResponse) {\n return {\n element: null,\n isMatched,\n statusCode:\n routerContext.statusCode ?? routerContext.redirectResponse.status ?? 302,\n redirectResponse: routerContext.redirectResponse,\n redirectRouteId: routerContext.redirectRouteId,\n redirectRoutePath: routerContext.redirectRoutePath,\n rtsHydrationData: null,\n }\n }\n\n if (routerContext.errors) {\n if (routerContext.statusCode === 404) {\n if (req.method === \"GET\" || req.method === \"HEAD\") {\n console.warn(`SSR 404 ${req.method} ${req.originalUrl}`)\n } else {\n console.warn(`SSR 404 ${req.method} ${req.originalUrl}`, {\n errors: routerContext.errors,\n })\n }\n } else {\n const matchesSummary = routerContext.matches?.map((m) => ({\n routeId: m.route.id,\n routePath: m.route.path,\n pathname: m.pathname,\n pathnameBase: m.pathnameBase,\n }))\n console.error(\n `SSR ${routerContext.statusCode || 500} ${req.method} ${req.originalUrl}`,\n {\n errors: routerContext.errors,\n matches: matchesSummary,\n },\n )\n\n const errorEntries = Object.entries(routerContext.errors || {})\n const firstErrorEntry: any = errorEntries[0]?.[1]\n const firstReason = firstErrorEntry?.reason ?? firstErrorEntry\n if (errorEntries.length === 1 && firstReason instanceof Error) {\n ;(firstReason as any).details = routerContext.errors\n throw firstReason\n }\n\n const extra = firstErrorEntry?.id\n ? ` (route ${firstErrorEntry.id}${firstErrorEntry?.path ? ` ${firstErrorEntry.path}` : \"\"})`\n : \"\"\n const error = new Error(`SSR loader error${extra}`)\n ;(error as any).details = routerContext.errors\n throw error\n }\n }\n\n const buildElement = (runtime: RtsSsrRuntime | null) => {\n const router = createStaticRouter(dataRoutes, routerContext)\n const app = (\n <StaticRouterProvider\n router={router}\n context={routerContext}\n // TODO: setup CSP and use correct nonce\n // nonce=\"the-nonce\"\n />\n )\n\n return (\n <StrictMode>\n {runtime ? (\n <RtsSsrRuntimeProvider value={runtime}>\n {app}\n </RtsSsrRuntimeProvider>\n ) : app}\n </StrictMode>\n )\n }\n\n const tenantId = resolveRtsRequestTenantId(req)\n let rtsHydrationData: StaticRpcbaseRtsHydrationData | null = null\n let runtime: RtsSsrRuntime | null = null\n\n if (tenantId) {\n const collector = createRtsSsrCollector(req)\n // RTS hooks are synchronous and cannot await during render. We do a first\n // discovery pass to collect registrations, resolve them async, then render\n // again so the final SSR markup includes RTS data.\n const prepassOk = await runRtsPrepass(buildElement(collector.runtime))\n if (prepassOk && collector.hasRegistrations()) {\n rtsHydrationData = await collector.resolve()\n }\n runtime = collector.runtime\n }\n\n const element = buildElement(runtime)\n\n return {\n element,\n isMatched,\n statusCode: routerContext.statusCode ?? (routerContext.errors ? 500 : 200),\n rtsHydrationData,\n }\n}\n","const LEGACY_APP_HTML_PLACEHOLDER = \"<!--app-html-->\"\nconst TEMPLATE_ELEMENT_PATTERN = /<template\\b((?:\"[^\"]*\"|'[^']*'|[^'\">])*)>([\\s\\S]*?)<\\/template\\s*>/gi\nconst RPCBASE_OUTLET_ATTRIBUTE_PATTERN = /(?:^|\\s)data-rpcbase-outlet\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))(?=\\s|$)/gi\n\n\nexport type HtmlOutlets = {\n head?: string\n htmlAttributes?: {\n lang?: string\n dir?: \"ltr\" | \"rtl\" | \"auto\"\n }\n}\n\nexport type CompiledHtmlTemplate = {\n isLegacy: boolean\n render: (outlets?: HtmlOutlets) => {\n htmlStart: string\n htmlEnd: string\n }\n}\n\ntype OutletMatch = {\n name: string\n start: number\n end: number\n content: string\n}\n\ntype HtmlTagMatch = {\n start: number\n end: number\n}\n\nconst HTML_DIRECTIONS = new Set([\"ltr\", \"rtl\", \"auto\"])\nconst RAW_TEXT_ELEMENTS = new Set([\"script\", \"style\", \"textarea\", \"title\"])\n\nconst findTagEnd = (template: string, start: number) => {\n let quote: \"\\\"\" | \"'\" | null = null\n\n for (let index = start; index < template.length; index += 1) {\n const character = template[index]\n\n if (quote) {\n if (character === quote) quote = null\n continue\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character\n } else if (character === \">\") {\n return index + 1\n }\n }\n\n return template.length\n}\n\nconst findHtmlStartTags = (template: string): HtmlTagMatch[] => {\n const tags: HtmlTagMatch[] = []\n const lowerTemplate = template.toLowerCase()\n let index = 0\n\n while (index < template.length) {\n const start = template.indexOf(\"<\", index)\n if (start === -1) break\n\n if (template.startsWith(\"<!--\", start)) {\n const commentEnd = template.indexOf(\"-->\", start + 4)\n index = commentEnd === -1 ? template.length : commentEnd + 3\n continue\n }\n\n const firstCharacter = template[start + 1]\n if (firstCharacter === \"!\" || firstCharacter === \"?\" || firstCharacter === \"/\") {\n index = findTagEnd(template, start + 2)\n continue\n }\n\n const nameMatch = /^[A-Za-z][A-Za-z0-9:-]*/.exec(template.slice(start + 1))\n if (!nameMatch) {\n index = start + 1\n continue\n }\n\n const name = nameMatch[0].toLowerCase()\n const end = findTagEnd(template, start + 1 + nameMatch[0].length)\n\n if (name === \"html\") {\n tags.push({ start, end })\n }\n\n if (RAW_TEXT_ELEMENTS.has(name) && !template.slice(start, end).trimEnd().endsWith(\"/>\")) {\n const closingTagStart = lowerTemplate.indexOf(`</${name}`, end)\n index = closingTagStart === -1\n ? template.length\n : findTagEnd(template, closingTagStart + name.length + 2)\n } else {\n index = end\n }\n }\n\n return tags\n}\n\nconst escapeHtmlAttribute = (value: string) => value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"\\\"\", \"&quot;\")\n .replaceAll(\"'\", \"&#39;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n\nconst setHtmlTagAttributes = (\n tag: string,\n attributes: NonNullable<HtmlOutlets[\"htmlAttributes\"]>,\n) => {\n const values = new Map<string, string>()\n\n if (attributes.lang !== undefined) {\n if (typeof attributes.lang !== \"string\") {\n throw new Error(\"HTML attribute \\\"lang\\\" must be a string\")\n }\n values.set(\"lang\", attributes.lang)\n }\n\n if (attributes.dir !== undefined) {\n if (!HTML_DIRECTIONS.has(attributes.dir)) {\n throw new Error(\"HTML attribute \\\"dir\\\" must be one of \\\"ltr\\\", \\\"rtl\\\", or \\\"auto\\\"\")\n }\n values.set(\"dir\", attributes.dir)\n }\n\n if (values.size === 0) return tag\n\n const replacements: Array<{ start: number, end: number, value: string }> = []\n const replacedAttributes = new Set<string>()\n let index = 5\n\n while (index < tag.length - 1) {\n const whitespaceStart = index\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n if (tag[index] === \"/\" || tag[index] === \">\" || index >= tag.length - 1) break\n\n const attributeStart = index\n while (index < tag.length && !/[\\s=/>]/.test(tag[index])) index += 1\n const attributeName = tag.slice(attributeStart, index).toLowerCase()\n const attributeNameEnd = index\n\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n if (tag[index] === \"=\") {\n index += 1\n while (/\\s/.test(tag[index] ?? \"\")) index += 1\n\n const quote = tag[index]\n if (quote === \"\\\"\" || quote === \"'\") {\n index += 1\n while (index < tag.length && tag[index] !== quote) index += 1\n if (tag[index] === quote) index += 1\n } else {\n while (index < tag.length && !/[\\s>]/.test(tag[index])) index += 1\n }\n } else {\n index = attributeNameEnd\n }\n\n if (!values.has(attributeName)) continue\n\n replacements.push({\n start: replacedAttributes.has(attributeName) ? whitespaceStart : attributeStart,\n end: index,\n value: replacedAttributes.has(attributeName)\n ? \"\"\n : `${attributeName}=\"${escapeHtmlAttribute(values.get(attributeName)!)}\"`,\n })\n replacedAttributes.add(attributeName)\n }\n\n let renderedTag = tag\n for (const replacement of replacements.reverse()) {\n renderedTag = `${renderedTag.slice(0, replacement.start)}${replacement.value}${renderedTag.slice(replacement.end)}`\n }\n\n const missingAttributes = [...values]\n .filter(([name]) => !replacedAttributes.has(name))\n .map(([name, value]) => `${name}=\"${escapeHtmlAttribute(value)}\"`)\n\n if (missingAttributes.length === 0) return renderedTag\n\n return renderedTag.replace(/\\s*\\/?>$/, (ending) => {\n const suffix = ending.trimStart()\n return ` ${missingAttributes.join(\" \")}${suffix}`\n })\n}\n\nconst renderHtmlAttributes = (\n rendered: { htmlStart: string, htmlEnd: string },\n htmlAttributes: HtmlOutlets[\"htmlAttributes\"],\n) => {\n if (!htmlAttributes || (htmlAttributes.lang === undefined && htmlAttributes.dir === undefined)) {\n return rendered\n }\n\n const startTags = findHtmlStartTags(rendered.htmlStart)\n const endTags = findHtmlStartTags(rendered.htmlEnd)\n const htmlTagCount = startTags.length + endTags.length\n\n if (htmlTagCount === 0) {\n throw new Error(\"HTML template missing <html> element required by htmlAttributes\")\n }\n if (htmlTagCount > 1) {\n throw new Error(\"HTML template has multiple <html> elements\")\n }\n\n const target = startTags.length > 0 ? \"htmlStart\" : \"htmlEnd\"\n const match = startTags[0] ?? endTags[0]\n const value = rendered[target]\n\n return {\n ...rendered,\n [target]: `${value.slice(0, match.start)}${setHtmlTagAttributes(\n value.slice(match.start, match.end),\n htmlAttributes,\n )}${value.slice(match.end)}`,\n }\n}\n\nconst countOccurrences = (value: string, search: string) => {\n let count = 0\n let index = value.indexOf(search)\n\n while (index !== -1) {\n count += 1\n index = value.indexOf(search, index + search.length)\n }\n\n return count\n}\n\nconst getRpcbaseOutlets = (template: string): OutletMatch[] => {\n const outlets: OutletMatch[] = []\n\n for (const match of template.matchAll(TEMPLATE_ELEMENT_PATTERN)) {\n const outletAttributes = [...match[1].matchAll(RPCBASE_OUTLET_ATTRIBUTE_PATTERN)]\n if (outletAttributes.length === 0) continue\n if (outletAttributes.length > 1) {\n throw new Error(\"HTML template element has multiple data-rpcbase-outlet attributes\")\n }\n\n const outletAttribute = outletAttributes[0]\n outlets.push({\n name: outletAttribute[1] ?? outletAttribute[2] ?? outletAttribute[3],\n start: match.index,\n end: match.index + match[0].length,\n content: match[2],\n })\n }\n\n return outlets\n}\n\nexport const compileHtmlTemplate = (template: string): CompiledHtmlTemplate => {\n const legacyAppOutletCount = countOccurrences(template, LEGACY_APP_HTML_PLACEHOLDER)\n const rpcbaseOutlets = getRpcbaseOutlets(template)\n\n if (legacyAppOutletCount > 0 && rpcbaseOutlets.length > 0) {\n throw new Error(\"HTML template cannot mix rpcbase outlets with the legacy <!--app-html--> placeholder\")\n }\n\n if (rpcbaseOutlets.length === 0) {\n if (legacyAppOutletCount === 0) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"app\\\"></template> outlet\")\n }\n if (legacyAppOutletCount > 1) {\n throw new Error(\"HTML template has multiple legacy <!--app-html--> placeholders\")\n }\n\n const appOutletStart = template.indexOf(LEGACY_APP_HTML_PLACEHOLDER)\n\n return {\n isLegacy: true,\n render: (outlets = {}) => {\n if (outlets.head) {\n throw new Error(\"Cannot render the \\\"head\\\" outlet in a legacy HTML template\")\n }\n\n return renderHtmlAttributes({\n htmlStart: template.slice(0, appOutletStart),\n htmlEnd: template.slice(appOutletStart + LEGACY_APP_HTML_PLACEHOLDER.length),\n }, outlets.htmlAttributes)\n },\n }\n }\n\n const outletsByName = new Map<string, OutletMatch>()\n\n for (const outlet of rpcbaseOutlets) {\n if (outlet.name !== \"head\" && outlet.name !== \"app\") {\n throw new Error(`HTML template has unknown rpcbase outlet \"${outlet.name}\"`)\n }\n if (outletsByName.has(outlet.name)) {\n throw new Error(`HTML template has multiple rpcbase outlets named \"${outlet.name}\"`)\n }\n if (outlet.content.trim()) {\n throw new Error(`HTML template rpcbase outlet \"${outlet.name}\" must be empty`)\n }\n\n outletsByName.set(outlet.name, outlet)\n }\n\n const headOutlet = outletsByName.get(\"head\")\n const appOutlet = outletsByName.get(\"app\")\n\n if (!appOutlet) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"app\\\"></template> outlet\")\n }\n if (headOutlet && headOutlet.start > appOutlet.start) {\n throw new Error(\"HTML template rpcbase outlet \\\"head\\\" must appear before \\\"app\\\"\")\n }\n\n return {\n isLegacy: false,\n render: (outlets = {}) => {\n if (!headOutlet) {\n if (outlets.head) {\n throw new Error(\"HTML template missing <template data-rpcbase-outlet=\\\"head\\\"></template> outlet\")\n }\n\n return renderHtmlAttributes({\n htmlStart: template.slice(0, appOutlet.start),\n htmlEnd: template.slice(appOutlet.end),\n }, outlets.htmlAttributes)\n }\n\n return renderHtmlAttributes({\n htmlStart: `${template.slice(0, headOutlet.start)}${outlets.head ?? \"\"}${template.slice(headOutlet.end, appOutlet.start)}`,\n htmlEnd: template.slice(appOutlet.end),\n }, outlets.htmlAttributes)\n },\n }\n}\n","import fs from \"node:fs/promises\"\nimport { readFileSync } from \"node:fs\"\nimport { Transform } from \"node:stream\"\n\nimport env from \"@rpcbase/env\"\nimport { SSR_ERROR_STATE_GLOBAL_KEY, SsrErrorFallback, serializeSsrErrorState, type SsrErrorStatePayload } from \"@rpcbase/client\"\nimport { StaticHandler } from \"@rpcbase/router\"\nimport { createElement, StrictMode, type ComponentType } from \"react\"\nimport { renderToPipeableStream, renderToStaticMarkup } from \"react-dom/server\"\nimport { NextFunction, Request, Response } from \"express\"\nimport type { PostHog } from \"posthog-node\"\n\nimport { renderSSR } from \"./renderSSR\"\nimport { captureServerException } from \"./posthog\"\nimport { renderRtsHydrationScript } from \"./rts/ssrHydration\"\nimport { compileHtmlTemplate, type HtmlOutlets } from \"./htmlTemplate\"\n\n\ntype ViteDevServer = {\n transformIndexHtml: (url: string, html: string) => Promise<string>\n ssrFixStacktrace: (error: Error) => void\n}\n\n\nconst ABORT_DELAY_MS = 10_000\nconst SSR_IDENTIFIER_PREFIX = \"rb-\"\nconst DEFAULT_SERVER_ERROR_MESSAGE = \"We couldn't render this page on the server. Please refresh and try again.\"\nconst 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>*{box-sizing:border-box}body{margin:0;background:#fff;color:#111827;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,\\\"Segoe UI\\\",sans-serif}#root,#root>div{min-height:100vh;background:#fff}main{display:flex;min-height:100vh;max-width:42rem;margin:0 auto;padding:3rem 1.5rem;flex-direction:column;align-items:center;justify-content:center;text-align:center}p{margin:0}main>p:first-child{font-size:1rem;line-height:1.5rem;font-weight:600;color:#e11d48}h1{margin:1rem 0 0;color:#111827;font-size:2.25rem;line-height:1.1;font-weight:600;letter-spacing:0;text-wrap:pretty}h1+p{margin-top:1.5rem;color:#4b5563;font-size:1.125rem;line-height:1.75rem}[class~=\\\"bg-gray-900/95\\\"]{width:100%;margin-top:2.5rem;border-radius:1rem;background:rgba(17,24,39,.96);padding:1.25rem;text-align:left;box-shadow:0 25px 50px -12px rgba(0,0,0,.25)}[class~=\\\"bg-gray-900/95\\\"] p{color:#9ca3af;font-size:.875rem;line-height:1.25rem;font-weight:600;letter-spacing:.025em;text-transform:uppercase}pre{max-height:16rem;overflow:auto;margin:.75rem 0 0;white-space:pre-wrap;color:#f3f4f6;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,\\\"Liberation Mono\\\",\\\"Courier New\\\",monospace;font-size:.875rem;line-height:1.25rem}main>div[class~=\\\"flex\\\"]{display:flex;margin-top:2.5rem;flex-direction:column;gap:1rem;align-items:center;justify-content:center}a{color:#111827;text-decoration:none}main>div[class~=\\\"flex\\\"] a:first-child{display:inline-flex;height:2.25rem;align-items:center;justify-content:center;border-radius:.375rem;background:#111827;padding:0 1rem;color:#f8fafc;font-size:.875rem;font-weight:500;box-shadow:0 1px 2px rgba(15,23,42,.08)}main>div[class~=\\\"flex\\\"] a:first-child:hover{background:#1f2937}main>div[class~=\\\"flex\\\"] a:not(:first-child){color:#111827;font-size:.875rem;font-weight:500;text-underline-offset:4px}main>div[class~=\\\"flex\\\"] a:not(:first-child):hover{text-decoration:underline}@media (min-width:640px){main{padding-top:6rem;padding-bottom:6rem}h1{font-size:3rem}h1+p{font-size:1.25rem;line-height:1.625}main>div[class~=\\\"flex\\\"]{flex-direction:row}}</style></head><body><div id=\\\"root\\\">\"\nconst FALLBACK_ERROR_TEMPLATE_END = \"</div></body></html>\"\n\nconst isProduction = env.NODE_ENV === \"production\"\n\n\n// Cached production assets\nconst templateHtml = isProduction\n ? readFileSync(\"./build/dist/client/src/client/index.html\", \"utf-8\")\n : \"\"\nconst compiledTemplate = isProduction\n ? compileHtmlTemplate(templateHtml)\n : null\n\nconst handleRedirectionResponse = (\n res: Response,\n redirectResponse: globalThis.Response,\n location?: string | null,\n) => {\n res.status(redirectResponse.status || 302)\n\n try {\n const headers = redirectResponse.headers as Headers & {\n getSetCookie?: () => string[]\n }\n // `Set-Cookie` is special: redirects commonly set multiple cookies (auth/session). Express\n // `setHeader` overwrites duplicates, and `Headers#get(\"set-cookie\")` joins values with commas\n // (unsafe for cookies), so we forward it once as an array via `getSetCookie()` when available.\n const setCookies = headers.getSetCookie?.()\n const fallbackSetCookies: string[] = []\n\n for (const [key, value] of headers) {\n if (key.toLowerCase() === \"set-cookie\") {\n if (!setCookies?.length) {\n fallbackSetCookies.push(value)\n }\n continue\n }\n res.setHeader(key, value)\n }\n\n if (setCookies?.length) {\n res.setHeader(\"Set-Cookie\", setCookies)\n } else if (fallbackSetCookies.length === 1) {\n res.setHeader(\"Set-Cookie\", fallbackSetCookies[0])\n } else if (fallbackSetCookies.length > 1) {\n res.setHeader(\"Set-Cookie\", fallbackSetCookies)\n }\n } catch {\n //\n }\n\n if (location) res.setHeader(\"Location\", location)\n res.end()\n}\n\nconst formatErrorDetails = (error: unknown): string | undefined => {\n if (isProduction) return undefined\n if (!error) return undefined\n if (error instanceof Error) {\n return error.stack || error.message\n }\n if (typeof error === \"string\") {\n return error\n }\n try {\n return JSON.stringify(error, null, 2)\n } catch {\n return undefined\n }\n}\n\nconst sendErrorResponse = ({\n res,\n htmlStart,\n htmlEnd,\n error,\n status = 500,\n title = \"Server rendering error\",\n message = DEFAULT_SERVER_ERROR_MESSAGE,\n errorExtraComponent,\n}: {\n res: Response\n htmlStart: string | null\n htmlEnd: string | null\n error?: unknown\n status?: number\n title?: string\n message?: string\n errorExtraComponent?: ComponentType<{ state?: SsrErrorStatePayload }>\n}) => {\n if (res.headersSent) return\n\n const start = htmlStart ?? FALLBACK_ERROR_TEMPLATE_START\n const end = htmlEnd ?? FALLBACK_ERROR_TEMPLATE_END\n\n res.status(status)\n res.set({ \"Content-Type\": \"text/html\" })\n\n const details = formatErrorDetails(error)\n const state = {\n statusCode: status,\n title,\n message,\n details,\n }\n\n const markup = renderToStaticMarkup(\n createElement(\n StrictMode,\n null,\n createElement(SsrErrorFallback, {\n state,\n renderErrorExtra: errorExtraComponent\n ? (payload) => createElement(errorExtraComponent, { state: payload })\n : undefined,\n }),\n ),\n )\n\n const serializedState = `<script>window.${SSR_ERROR_STATE_GLOBAL_KEY}=${serializeSsrErrorState({\n ...state,\n details: isProduction ? undefined : details,\n })};</script>`\n\n res.end(`${start}${markup}${serializedState}${end}`)\n}\n\nexport const ssrMiddleware = ({\n viteInstance,\n dataRoutes,\n errorExtraComponent,\n getHtmlOutlets,\n renderTemplateStart,\n posthog,\n}: {\n viteInstance: ViteDevServer,\n dataRoutes: StaticHandler[\"dataRoutes\"],\n errorExtraComponent?: ComponentType<{ state?: SsrErrorStatePayload }>,\n getHtmlOutlets?: (req: Request) => HtmlOutlets | Promise<HtmlOutlets>,\n renderTemplateStart?: (req: Request, templateStart: string) => Promise<string>,\n posthog?: PostHog | null,\n}) => async(req: Request, res: Response, next: NextFunction) => {\n let template: string\n let htmlStart: string | null = null\n let htmlEnd: string | null = null\n let responseCommitted = false\n\n const posthogClient = posthog ?? (req.app?.locals?.posthog as PostHog | undefined) ?? null\n\n const captureException = (error: unknown, extra?: Record<string, unknown>) => {\n if (!error) return\n captureServerException(error, posthogClient, {\n path: req.originalUrl,\n method: req.method,\n source: \"ssrMiddleware\",\n ...extra,\n })\n }\n\n const finalizeWithErrorPage = (error?: unknown, status = 500, message = DEFAULT_SERVER_ERROR_MESSAGE) => {\n if (responseCommitted) return\n sendErrorResponse({\n res,\n htmlStart,\n htmlEnd,\n error,\n status,\n message,\n errorExtraComponent,\n })\n responseCommitted = true\n\n if (error) {\n captureException(error, { phase: \"finalizeWithErrorPage\" })\n }\n }\n\n try {\n const base = \"/\"\n const url = req.originalUrl.replace(base, \"\")\n\n let requestTemplate = compiledTemplate\n\n if (!isProduction) {\n template = await fs.readFile(\"./src/client/index.html\", \"utf-8\")\n template = await viteInstance.transformIndexHtml(url, template)\n requestTemplate = compileHtmlTemplate(template)\n }\n\n if (!requestTemplate) {\n throw new Error(\"HTML template was not compiled\")\n }\n\n const outlets = await getHtmlOutlets?.(req)\n const renderedTemplate = requestTemplate.render(outlets)\n const templateStart = renderedTemplate.htmlStart\n if (renderTemplateStart && !requestTemplate.isLegacy) {\n throw new Error(\"renderTemplateStart can only be used with the legacy <!--app-html--> placeholder\")\n }\n if (renderTemplateStart) {\n htmlStart = await renderTemplateStart(req, templateStart)\n } else {\n htmlStart = templateStart\n }\n htmlEnd = renderedTemplate.htmlEnd\n\n const {\n element,\n isMatched,\n statusCode,\n rtsHydrationData,\n redirectResponse,\n redirectRouteId,\n redirectRoutePath,\n } = await renderSSR(req, res, dataRoutes)\n\n if (redirectResponse) {\n if (!responseCommitted) {\n const location = redirectResponse.headers?.get?.(\"Location\")\n\n if (!isProduction) {\n console.info(\"SSR redirect\", {\n method: req.method,\n url: req.originalUrl,\n status: redirectResponse.status,\n location,\n routeId: redirectRouteId ?? undefined,\n routePath: redirectRoutePath ?? undefined,\n })\n }\n\n responseCommitted = true\n handleRedirectionResponse(res, redirectResponse, location)\n }\n return\n }\n\n // TODO we should do this before the renderTemplateStart, so we have the isMatched handling?\n if (!isMatched) {\n next()\n return\n }\n\n let didError = false\n\n const {pipe, abort} = renderToPipeableStream(\n element,\n {\n identifierPrefix: SSR_IDENTIFIER_PREFIX,\n onShellError(error) {\n if (error instanceof Error) {\n viteInstance?.ssrFixStacktrace(error)\n }\n console.error(\"SSR shell error\", error)\n captureException(error, { phase: \"shell\" })\n finalizeWithErrorPage(error)\n },\n onError(error) {\n didError = true\n if (error instanceof Error) {\n viteInstance?.ssrFixStacktrace(error)\n }\n console.error(\"SSR rendering error\", error)\n captureException(error, { phase: \"render\" })\n },\n onShellReady() {\n if (responseCommitted) {\n return\n }\n\n if (!htmlStart || !htmlEnd) {\n finalizeWithErrorPage()\n return\n }\n\n responseCommitted = true\n const responseStatus = didError ? 500 : statusCode || 200\n res.status(responseStatus)\n res.set({ \"Content-Type\": \"text/html\" })\n\n const transformStream = new Transform({\n transform(chunk, encoding, callback) {\n res.write(chunk, encoding)\n callback()\n },\n })\n\n const start = htmlStart\n const end = htmlEnd\n const rtsHydrationScript = renderRtsHydrationScript(rtsHydrationData)\n\n res.write(start)\n\n transformStream.on(\"finish\", () => {\n res.end(`${rtsHydrationScript}${end}`)\n })\n\n pipe(transformStream)\n },\n },\n )\n\n setTimeout(() => {\n abort()\n }, ABORT_DELAY_MS)\n } catch (err: unknown) {\n if (err instanceof Error) {\n viteInstance?.ssrFixStacktrace(err)\n console.error(\"SSR middleware error:\", err.message)\n console.error(err.stack)\n } else {\n console.error(\"Unknown SSR middleware error\", err)\n }\n\n captureException(err, { phase: \"catch\" })\n\n finalizeWithErrorPage(err)\n }\n}\n","import { GridFSBucket, ObjectId, type Collection, type Db } from \"mongodb\"\nimport {\n getTenantFilesystemDb,\n models,\n type IRBUploadChunk,\n type IRBUploadSession,\n} from \"@rpcbase/db\"\nimport type { Connection, Model } from \"mongoose\"\n\nimport {\n deleteUploadFileReference,\n type UploadFileReference,\n} from \"./uploads/api/file-uploads/fileReferences\"\nimport {\n getBucketName,\n getFileReferencesCollectionName,\n resolveStoredUploadAccessScope,\n} from \"./uploads/api/file-uploads/shared\"\n\n\ntype UploadSessionDocument = Pick<IRBUploadSession, \"_id\">\ntype UploadChunkDocument = Omit<IRBUploadChunk, \"data\"> & { data: Buffer }\n\ntype GridFsFileDocument = {\n _id: ObjectId\n metadata?: Record<string, unknown>\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst getNativeDb = (connection: Connection): Db => {\n if (!connection.db) {\n throw new Error(`Mongo database '${connection.name}' is unavailable.`)\n }\n return connection.db\n}\n\nconst deleteGridFsFile = async (\n db: Db,\n bucket: GridFSBucket,\n bucketName: string,\n fileId: ObjectId,\n): Promise<void> => {\n const variants = await db.collection<GridFsFileDocument>(`${bucketName}.files`)\n .find(\n { \"metadata.variantOf\": fileId.toHexString() },\n { projection: { _id: 1 } },\n )\n .toArray()\n\n await bucket.delete(fileId)\n for (const variant of variants) {\n if (variant._id instanceof ObjectId) await bucket.delete(variant._id)\n }\n}\n\nconst removeUserFromSharedFile = async (\n files: Collection<GridFsFileDocument>,\n fileId: ObjectId,\n): Promise<void> => {\n await files.updateMany(\n {\n $or: [\n { _id: fileId },\n { \"metadata.variantOf\": fileId.toHexString() },\n ],\n },\n { $unset: { \"metadata.userId\": \"\" } },\n )\n}\n\nexport const deleteRpcbaseUserUploads = async (\n tenantId: string,\n userId: string,\n): Promise<void> => {\n const modelCtx = { tenantId }\n const [UploadSession, UploadChunk] = await Promise.all([\n models.getUnsafe(\"RBUploadSession\", modelCtx) as Promise<Model<IRBUploadSession>>,\n models.getUnsafe(\"RBUploadChunk\", modelCtx) as Promise<Model<UploadChunkDocument>>,\n ])\n const uploadSessions = await UploadSession.find(\n { userId },\n { _id: 1 },\n ).lean() as UploadSessionDocument[]\n const uploadIds = uploadSessions.map((session) => session._id)\n\n const filesystemConnection = await getTenantFilesystemDb(tenantId)\n const filesystemDb = getNativeDb(filesystemConnection)\n const bucketName = getBucketName()\n const references = filesystemDb.collection<UploadFileReference>(\n getFileReferencesCollectionName(bucketName),\n )\n const userReferences = await references.find({ userId }).toArray()\n\n for (const reference of userReferences) {\n if (resolveStoredUploadAccessScope(reference as unknown as Record<string, unknown>) === \"owner\") {\n await deleteUploadFileReference({\n tenantId,\n bucketName,\n referenceId: reference._id,\n })\n continue\n }\n\n await references.updateOne(\n { _id: reference._id },\n { $unset: { userId: \"\" } },\n )\n }\n\n const files = filesystemDb.collection<GridFsFileDocument>(`${bucketName}.files`)\n const userFiles = await files.find({ \"metadata.userId\": userId }).toArray()\n const bucket = userFiles.length > 0\n ? new GridFSBucket(filesystemDb, { bucketName })\n : null\n\n for (const file of userFiles) {\n if (!(file._id instanceof ObjectId) || !bucket) continue\n\n const metadata = file.metadata ?? {}\n const deduplication = metadata.deduplication\n const isDeduplicated = Boolean(\n deduplication\n && typeof deduplication === \"object\"\n && toTrimmedString((deduplication as Record<string, unknown>).key),\n )\n const accessScope = resolveStoredUploadAccessScope(metadata)\n\n if (accessScope === \"owner\" && !isDeduplicated) {\n await deleteGridFsFile(filesystemDb, bucket, bucketName, file._id)\n continue\n }\n\n await removeUserFromSharedFile(files, file._id)\n }\n\n await Promise.all([\n uploadIds.length > 0\n ? UploadChunk.deleteMany({ uploadId: { $in: uploadIds } })\n : Promise.resolve(),\n UploadSession.deleteMany({ userId }),\n ])\n}\n","import { type Collection, type Db } from \"mongodb\"\nimport { getTenantFilesystemDb, models } from \"@rpcbase/db\"\nimport type { ClientSession, Connection } from \"mongoose\"\n\nimport { deleteRpcbaseUserUploads } from \"./accountDeletionUploads\"\n\n\ntype UserAccountDocument = {\n _id?: unknown\n tenants?: unknown\n tenantRoles?: unknown\n}\n\nexport type DeleteRpcbaseTenantUserDataScope = {\n tenantId: string\n userId: string\n}\n\nexport type DeleteRpcbaseUserAccountOptions = {\n userId: string\n deleteTenantUserData?: (scope: DeleteRpcbaseTenantUserDataScope) => Promise<void>\n}\n\nexport type DeleteRpcbaseUserAccountResult = {\n tenantIds: string[]\n deletedTenantIds: string[]\n failedTenantDatabaseIds: string[]\n}\n\nexport class RpcbaseUserAccountNotFoundError extends Error {\n constructor(userId: string) {\n super(`RPCBase user account '${userId}' was not found.`)\n this.name = \"RpcbaseUserAccountNotFoundError\"\n }\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst normalizeRequiredId = (value: string, label: string): string => {\n const normalized = value.trim()\n if (!normalized) throw new Error(`${label} is required.`)\n return normalized\n}\n\nconst toStringArray = (value: unknown): string[] => {\n if (!Array.isArray(value)) return []\n return value.map(toTrimmedString).filter(Boolean)\n}\n\nconst getTenantRoleIds = (value: unknown): string[] => {\n if (value instanceof Map) {\n return Array.from(value.keys()).map(toTrimmedString).filter(Boolean)\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return []\n return Object.keys(value).map(toTrimmedString).filter(Boolean)\n}\n\nconst getAccountTenantIds = (\n user: Pick<UserAccountDocument, \"tenants\" | \"tenantRoles\">,\n): string[] => Array.from(new Set([\n ...toStringArray(user.tenants),\n ...getTenantRoleIds(user.tenantRoles),\n]))\n\nconst getNativeDb = (connection: Connection): Db => {\n if (!connection.db) {\n throw new Error(`Mongo database '${connection.name}' is unavailable.`)\n }\n return connection.db\n}\n\nconst listCollectionNames = async (connection: Connection): Promise<string[]> => {\n const collections = await getNativeDb(connection)\n .listCollections({}, { nameOnly: true })\n .toArray()\n\n return collections\n .map((collection) => toTrimmedString(collection.name))\n .filter((collectionName) => collectionName && !collectionName.startsWith(\"system.\"))\n}\n\nconst buildTenantMembershipFilter = (tenantId: string): Record<string, unknown> => {\n const clauses: Array<Record<string, unknown>> = [{ tenants: tenantId }]\n if (!tenantId.includes(\".\") && !tenantId.startsWith(\"$\")) {\n clauses.push({ [`tenantRoles.${tenantId}`]: { $exists: true } })\n }\n return { $or: clauses }\n}\n\nconst deleteRpcbaseTenantUserData = async (\n tenantId: string,\n userId: string,\n): Promise<void> => {\n const modelCtx = { tenantId }\n const [Notification, NotificationDelivery, NotificationSettings] = await Promise.all([\n models.getUnsafe(\"RBNotification\", modelCtx),\n models.getUnsafe(\"RBNotificationDelivery\", modelCtx),\n models.getUnsafe(\"RBNotificationSettings\", modelCtx),\n ])\n\n await Promise.all([\n Notification.deleteMany({ userId }),\n NotificationDelivery.deleteMany({ userId }),\n NotificationSettings.deleteMany({ userId }),\n deleteRpcbaseUserUploads(tenantId, userId),\n ])\n}\n\nconst deleteTenantGlobalData = async (\n connection: Connection,\n collectionNames: string[],\n userCollectionName: string,\n tenantId: string,\n session: ClientSession,\n): Promise<void> => {\n for (const collectionName of collectionNames) {\n if (collectionName === userCollectionName) continue\n\n const collection = connection.collection(collectionName)\n const hasTenantData = await collection.findOne(\n { tenantId },\n { projection: { _id: 1 }, session },\n )\n if (hasTenantData) {\n await collection.deleteMany({ tenantId }, { session })\n }\n }\n}\n\nconst deleteGlobalUserAccount = async ({\n connection,\n users,\n userDocumentId,\n}: {\n connection: Connection\n users: Collection<UserAccountDocument>\n userDocumentId: unknown\n}): Promise<{ tenantIds: string[]; deletedTenantIds: string[] }> => {\n const collectionNames = await listCollectionNames(connection)\n const session = await connection.startSession()\n let result = { tenantIds: [] as string[], deletedTenantIds: [] as string[] }\n\n try {\n await session.withTransaction(async () => {\n const user = await users.findOne(\n { _id: userDocumentId } as Record<string, unknown>,\n {\n projection: { _id: 1, tenants: 1, tenantRoles: 1 },\n session,\n },\n )\n if (!user) throw new RpcbaseUserAccountNotFoundError(String(userDocumentId))\n\n const tenantIds = getAccountTenantIds(user)\n const deletedTenantIds: string[] = []\n\n for (const tenantId of tenantIds) {\n const otherUser = await users.findOne(\n {\n _id: { $ne: userDocumentId },\n ...buildTenantMembershipFilter(tenantId),\n } as Record<string, unknown>,\n { projection: { _id: 1 }, session },\n )\n if (!otherUser) deletedTenantIds.push(tenantId)\n }\n\n for (const tenantId of deletedTenantIds) {\n await deleteTenantGlobalData(\n connection,\n collectionNames,\n users.collectionName,\n tenantId,\n session,\n )\n }\n\n const deletedUser = await users.deleteOne(\n { _id: userDocumentId } as Record<string, unknown>,\n { session },\n )\n if (deletedUser.deletedCount !== 1) {\n throw new Error(\"RPCBase user account was not deleted.\")\n }\n\n result = { tenantIds, deletedTenantIds }\n })\n\n return result\n } finally {\n await session.endSession()\n }\n}\n\nconst dropTenantDatabases = async (tenantId: string): Promise<boolean> => {\n const tenantModel = await models.getUnsafe(\"RBNotification\", { tenantId })\n const filesystemConnection = await getTenantFilesystemDb(tenantId)\n const results = await Promise.allSettled([\n tenantModel.db.dropDatabase(),\n filesystemConnection.dropDatabase(),\n ])\n return results.every((result) => result.status === \"fulfilled\")\n}\n\nexport const deleteRpcbaseUserAccount = async ({\n userId: rawUserId,\n deleteTenantUserData,\n}: DeleteRpcbaseUserAccountOptions): Promise<DeleteRpcbaseUserAccountResult> => {\n const userId = normalizeRequiredId(rawUserId, \"User ID\")\n const User = await models.getGlobal(\"RBUser\", { req: { session: null } })\n const account = await User.findById(\n userId,\n { _id: 1, tenants: 1, tenantRoles: 1 },\n ).lean() as UserAccountDocument | null\n\n if (!account?._id) throw new RpcbaseUserAccountNotFoundError(userId)\n\n const initialTenantIds = getAccountTenantIds(account)\n for (const tenantId of initialTenantIds) {\n await deleteTenantUserData?.({ tenantId, userId })\n await deleteRpcbaseTenantUserData(tenantId, userId)\n }\n\n const users = User.collection as unknown as Collection<UserAccountDocument>\n const globalDeletion = await deleteGlobalUserAccount({\n connection: User.db,\n users,\n userDocumentId: account._id,\n })\n const failedTenantDatabaseIds: string[] = []\n\n for (const tenantId of globalDeletion.deletedTenantIds) {\n if (!await dropTenantDatabases(tenantId)) {\n failedTenantDatabaseIds.push(tenantId)\n }\n }\n\n return {\n ...globalDeletion,\n failedTenantDatabaseIds,\n }\n}\n","type StoredSession = {\n id?: unknown\n user?: {\n id?: unknown\n }\n}\n\ntype SessionStoreLike = {\n all?: (\n callback: (\n error: unknown,\n sessions?: StoredSession[] | Record<string, StoredSession> | null,\n ) => void,\n ) => unknown\n destroy: (sessionId: string, callback?: (error?: unknown) => void) => unknown\n}\n\ntype CurrentSessionLike = {\n user?: unknown\n destroy: (callback: (error?: unknown) => void) => unknown\n}\n\nexport type DestroyRpcbaseUserSessionsInput = {\n request: {\n sessionID?: unknown\n sessionStore?: unknown\n session?: unknown\n }\n userId: string\n}\n\nexport type DestroyRpcbaseUserSessionsResult = {\n destroyedSessionCount: number\n}\n\nconst toTrimmedString = (value: unknown): string => (\n typeof value === \"string\" ? value.trim() : \"\"\n)\n\nconst getSessionStore = (value: unknown): SessionStoreLike | null => {\n if (!value || typeof value !== \"object\") return null\n const candidate = value as Partial<SessionStoreLike>\n return typeof candidate.destroy === \"function\"\n ? candidate as SessionStoreLike\n : null\n}\n\nconst getCurrentSession = (value: unknown): CurrentSessionLike | null => {\n if (!value || typeof value !== \"object\") return null\n const candidate = value as Partial<CurrentSessionLike>\n return typeof candidate.destroy === \"function\"\n ? candidate as CurrentSessionLike\n : null\n}\n\nconst destroyStoredSession = async (\n store: SessionStoreLike,\n sessionId: string,\n): Promise<void> => {\n await new Promise<void>((resolve, reject) => {\n store.destroy(sessionId, (error) => {\n if (error) {\n reject(error)\n return\n }\n resolve()\n })\n })\n}\n\nconst loadStoredSessions = async (\n store: SessionStoreLike,\n): Promise<StoredSession[] | Record<string, StoredSession> | null> => {\n if (!store.all) return null\n\n return await new Promise((resolve, reject) => {\n store.all?.((error, sessions) => {\n if (error) {\n reject(error)\n return\n }\n resolve(sessions ?? null)\n })\n })\n}\n\nconst destroyOtherUserSessions = async (\n request: DestroyRpcbaseUserSessionsInput[\"request\"],\n userId: string,\n): Promise<number> => {\n const store = getSessionStore(request.sessionStore)\n if (!store?.all) return 0\n\n const storedSessions = await loadStoredSessions(store)\n if (!storedSessions) return 0\n\n const currentSessionId = toTrimmedString(request.sessionID)\n const entries = Array.isArray(storedSessions)\n ? storedSessions.map((session) => [toTrimmedString(session.id), session] as const)\n : Object.entries(storedSessions)\n const sessionIds = entries\n .filter(([, session]) => toTrimmedString(session.user?.id) === userId)\n .map(([sessionId]) => sessionId)\n .filter((sessionId) => sessionId && sessionId !== currentSessionId)\n\n await Promise.all(sessionIds.map((sessionId) => destroyStoredSession(store, sessionId)))\n return sessionIds.length\n}\n\nconst destroyCurrentSession = async (\n request: DestroyRpcbaseUserSessionsInput[\"request\"],\n): Promise<number> => {\n const session = getCurrentSession(request.session)\n if (!session) return 0\n\n session.user = undefined\n await new Promise<void>((resolve, reject) => {\n session.destroy((error) => {\n if (error) {\n reject(error)\n return\n }\n resolve()\n })\n })\n return 1\n}\n\nexport const destroyRpcbaseUserSessions = async ({\n request,\n userId: rawUserId,\n}: DestroyRpcbaseUserSessionsInput): Promise<DestroyRpcbaseUserSessionsResult> => {\n const userId = rawUserId.trim()\n if (!userId) throw new Error(\"User ID is required.\")\n\n const errors: unknown[] = []\n let destroyedSessionCount = 0\n\n try {\n destroyedSessionCount += await destroyOtherUserSessions(request, userId)\n } catch (error) {\n errors.push(error)\n }\n\n try {\n destroyedSessionCount += await destroyCurrentSession(request)\n } catch (error) {\n errors.push(error)\n }\n\n if (errors.length === 1) throw errors[0]\n if (errors.length > 1) {\n throw new AggregateError(errors, \"Could not destroy every RPCBase user session.\")\n }\n\n return { destroyedSessionCount }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65],"mappings":";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