@heycatch/sdk 0.7.0-dev.714 → 0.7.0-dev.974
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/README.md +57 -0
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +26 -2
- package/dist/index.d.ts +26 -2
- package/dist/index.js +2 -2
- package/dist/react-native.cjs +1 -1
- package/dist/react-native.d.cts +20 -2
- package/dist/react-native.d.ts +20 -2
- package/dist/react-native.js +1 -1
- package/dist/server.cjs +2 -2
- package/dist/server.d.cts +30 -3
- package/dist/server.d.ts +30 -3
- package/dist/server.js +2 -2
- package/dist/{shared-X3O5yyhh.d.cts → shared-CaIZ-Tgs.d.cts} +72 -1
- package/dist/{shared-X3O5yyhh.d.ts → shared-CaIZ-Tgs.d.ts} +72 -1
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var $t=Object.defineProperty;var mi=Object.getOwnPropertyDescriptor;var _i=Object.getOwnPropertyNames;var yi=Object.prototype.hasOwnProperty;var pr=(r,e)=>{for(var t in e)$t(r,t,{get:e[t],enumerable:!0})},vi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _i(e))!yi.call(r,i)&&i!==t&&$t(r,i,{get:()=>e[i],enumerable:!(n=mi(e,i))||n.enumerable});return r};var bi=r=>vi($t({},"__esModule",{value:!0}),r);var ra={};pr(ra,{KNOWN_FRAMEWORKS:()=>Nr,KNOWN_INSTALL_AGENTS:()=>Lr,SDK_VERSION:()=>ve,STAGE:()=>ye,UNKNOWN_INSTALL_VALUE:()=>H,analytics:()=>ta});module.exports=bi(ra);var Ze="project",xi="[a-z0-9]",ia=new RegExp(`^${xi}$`);var fr;function E(r,e,t){function n(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(r))return;a._zod.traits.add(r),e(a,u);let c=s.prototype,l=Object.keys(c);for(let p=0;p<l.length;p++){let f=l[p];f in a||(a[f]=c[f].bind(a))}}let i=t?.Parent??Object;class o extends i{}Object.defineProperty(o,"name",{value:r});function s(a){var u;let c=t?.Parent?new o:this;n(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(r)}),Object.defineProperty(s,"name",{value:r}),s}var Z=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(fr=globalThis).__zod_globalConfig??(fr.__zod_globalConfig={});var Ft=globalThis.__zod_globalConfig;function X(r){return r&&Object.assign(Ft,r),Ft}function hr(r,e){return typeof e=="bigint"?e.toString():e}function gr(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}var dr=Symbol("evaluating");function Q(r,e,t){let n;Object.defineProperty(r,e,{get(){if(n!==dr)return n===void 0&&(n=dr,n=t()),n},set(i){Object.defineProperty(r,e,{value:i})},configurable:!0})}var It="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Ue(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function mr(r){if(Ue(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Ue(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function zt(r){return mr(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}function At(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function J(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function _r(r){return Object.keys(r).filter(e=>r[e]._zod.optin==="optional"&&r[e]._zod.optout==="optional")}var sa={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function de(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function yr(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue===!1)return!0;return!1}function Ct(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function De(r){return typeof r=="string"?r:r?.message}function Y(r,e,t){let n=r.message?r.message:De(r.inst?._zod.def?.error?.(r))??De(e?.error?.(r))??De(t.customError?.(r))??De(t.localeError?.(r))??"Invalid input",{inst:i,continue:o,input:s,...a}=r;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}var vr=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),r.message=JSON.stringify(e,hr,2),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},br=E("$ZodError",vr),ge=E("$ZodError",vr,{Parent:Error});var Pi=r=>(e,t,n,i)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise)throw new Z;if(s.issues.length){let a=new(i?.Err??r)(s.issues.map(u=>Y(u,o,X())));throw It(a,i?.callee),a}return s.value},je=Pi(ge),Ei=r=>async(e,t,n,i)=>{let o=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(i?.Err??r)(s.issues.map(u=>Y(u,o,X())));throw It(a,i?.callee),a}return s.value},Be=Ei(ge),$i=r=>(e,t,n)=>{let i=n?{...n,async:!1}:{async:!1},o=e._zod.run({value:t,issues:[]},i);if(o instanceof Promise)throw new Z;return o.issues.length?{success:!1,error:new(r??br)(o.issues.map(s=>Y(s,i,X())))}:{success:!0,data:o.value}},me=$i(ge),Fi=r=>async(e,t,n)=>{let i=n?{...n,async:!0}:{async:!0},o=e._zod.run({value:t,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new r(o.issues.map(s=>Y(s,i,X())))}:{success:!0,data:o.value}},_e=Fi(ge);var Si="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Ii=new RegExp(`^${Si}$`);var xr=r=>{let e=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var kt=E("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])});var zi=E("$ZodCheckStringFormat",(r,e)=>{var t,n;kt.init(r,e),r._zod.onattach.push(i=>{let o=i._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(t=r._zod).check??(t.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),Pr=E("$ZodCheckRegex",(r,e)=>{zi.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}});var Er={major:4,minor:4,patch:3};var ee=E("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=Er;let n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(let i of n)for(let o of i._zod.onattach)o(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let i=(s,a,u)=>{let c=de(s),l;for(let p of a){if(p._zod.def.when){if(yr(s)||!p._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,d=p._zod.check(s);if(d instanceof Promise&&u?.async===!1)throw new Z;if(l||d instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await d,s.issues.length!==f&&(c||(c=de(s,f)))});else{if(s.issues.length===f)continue;c||(c=de(s,f))}}return l?l.then(()=>s):s},o=(s,a,u)=>{if(de(s))return s.aborted=!0,s;let c=i(a,n,u);if(c instanceof Promise){if(u.async===!1)throw new Z;return c.then(l=>r._zod.parse(l,u))}return r._zod.parse(c,u)};r._zod.run=(s,a)=>{if(a.skipChecks)return r._zod.parse(s,a);if(a.direction==="backward"){let c=r._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(l=>o(l,s,a)):o(c,s,a)}let u=r._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new Z;return u.then(c=>i(c,n,a))}return i(u,n,a)}}Q(r,"~standard",()=>({validate:i=>{try{let o=me(r,i);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return _e(r,i).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Sr=E("$ZodString",(r,e)=>{ee.init(r,e),r._zod.pattern=[...r?._zod.bag?.patterns??[]].pop()??xr(r._zod.bag),r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}});function $r(r,e,t){r.issues.length&&e.issues.push(...Ct(t,r.issues)),e.value[t]=r.value}var Ir=E("$ZodArray",(r,e)=>{ee.init(r,e),r._zod.parse=(t,n)=>{let i=t.value;if(!Array.isArray(i))return t.issues.push({expected:"array",code:"invalid_type",input:i,inst:r}),t;t.value=Array(i.length);let o=[];for(let s=0;s<i.length;s++){let a=i[s],u=e.element._zod.run({value:a,issues:[]},n);u instanceof Promise?o.push(u.then(c=>$r(c,t,s))):$r(u,t,s)}return o.length?Promise.all(o).then(()=>t):t}});function He(r,e,t,n,i,o){let s=t in n;if(r.issues.length){if(i&&o&&!s)return;e.issues.push(...Ct(t,r.issues))}if(!s&&!i){r.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}r.value===void 0?s&&(e.value[t]=void 0):e.value[t]=r.value}function ki(r){let e=Object.keys(r.shape);for(let n of e)if(!r.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let t=_r(r.shape);return{...r,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function Ri(r,e,t,n,i,o){let s=[],a=i.keySet,u=i.catchall._zod,c=u.def.type,l=u.optin==="optional",p=u.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let d=u.run({value:e[f],issues:[]},n);d instanceof Promise?r.push(d.then(h=>He(h,t,f,e,l,p))):He(d,t,f,e,l,p)}return s.length&&t.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),r.length?Promise.all(r).then(()=>t):t}var zr=E("$ZodObject",(r,e)=>{if(ee.init(r,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let u={...a};return Object.defineProperty(e,"shape",{value:u}),u}})}let n=gr(()=>ki(e));Q(r._zod,"propValues",()=>{let a=e.shape,u={};for(let c in a){let l=a[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(let p of l.values)u[c].add(p)}}return u});let i=Ue,o=e.catchall,s;r._zod.parse=(a,u)=>{s??(s=n.value);let c=a.value;if(!i(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:r}),a;a.value={};let l=[],p=s.shape;for(let f of s.keys){let d=p[f],h=d._zod.optin==="optional",y=d._zod.optout==="optional",P=d._zod.run({value:c[f],issues:[]},u);P instanceof Promise?l.push(P.then(_=>He(_,a,f,c,h,y))):He(P,a,f,c,h,y)}return o?Ri(l,c,a,u,n.value,r):l.length?Promise.all(l).then(()=>a):a}});var Ar=E("$ZodDefault",(r,e)=>{ee.init(r,e),r._zod.optin="optional",Q(r._zod,"values",()=>e.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);if(t.value===void 0)return t.value=e.defaultValue,t;let i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(o=>Fr(o,e)):Fr(i,e)}});function Fr(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}function Cr(r,e){return new r({type:"string",...J(e)})}function Rt(r,e){return new Pr({check:"string_format",format:"regex",...J(e),pattern:r})}var Ge=E("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(r,e),r.def=e,r.type=e.type,r.parse=(t,n)=>je(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>me(r,t,n),r.parseAsync=async(t,n)=>Be(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>_e(r,t,n),r.check=(...t)=>r.clone({...e,checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),r.with=r.check,r.clone=(t,n)=>At(r,t,n),r.brand=()=>r,r.register=((t,n)=>(t.add(r,n),r)),r.apply=t=>t(r)}),Oi=E("ZodMiniString",(r,e)=>{Sr.init(r,e),Ge.init(r,e)});function te(r){return Cr(Oi,r)}var Mi=E("ZodMiniArray",(r,e)=>{Ir.init(r,e),Ge.init(r,e)});function kr(r,e){return new Mi({type:"array",element:r,...J(e)})}var Ni=E("ZodMiniObject",(r,e)=>{zr.init(r,e),Ge.init(r,e),Q(r,"shape",()=>e.shape)});function Tt(r,e){let t={type:"object",shape:r??{},...J(e)};return new Ni(t)}var Li=E("ZodMiniDefault",(r,e)=>{Ar.init(r,e),Ge.init(r,e)});function re(r,e){return new Li({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():zt(e)}})}var Rr="https://in.dev.heycatch.ai",ye="dev",ve="0.7.0-dev.714",Tr="phc_CqKdgm7xbFBs3mSdtqzrHNTfzTRKrwRmCrEB9aftENY9";function ne(){return typeof globalThis.window<"u"}function Or(r=ye){return r!=="dev"?null:`[HeyCatch] WARNING: this is an internal development build (v${ve}). Events are being sent to the HeyCatch development environment and will NEVER appear in your dashboard. Reinstall the latest stable version - resolve it with \`npm view @heycatch/sdk version\` - or re-run the install guide: https://heycatch.ai/agents.md`}var H="unknown",Mr=Tt({projectKey:te({error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'}).check(Rt(/^hck_pk_/,{error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'})),tracingHosts:re(kr(te()),[]),install:re(Tt({framework:re(te(),H),frameworkVersion:re(te(),H),agent:re(te(),H)}),{framework:H,frameworkVersion:H,agent:H})}),Nr=["nextjs","vite-react","react","vue","svelte","astro","angular","react-native","web"],Lr=["lovable","bolt","v0","replit","cursor","claude-code","codex","windsurf","other"];var ie=require("path");function Dr(){let r=Ui();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function Ui(r=process.argv[1]?(0,ie.dirname)(process.argv[1]):process.cwd(),e=ie.sep==="\\"){let t=e?Zr(r):r;return n=>{if(!n)return;let i=e?Zr(n):n,{dir:o,base:s,ext:a}=ie.posix.parse(i);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);o||(o=".");let c=o.lastIndexOf("/node_modules");if(c>-1)return`${o.slice(c+14).replace(/\//g,".")}:${u}`;if(o.startsWith(t)){let l=o.slice(t.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function Zr(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Ot=r=>{if("flags"in r){let e=Ur(r.flags),t=jr(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([i,o])=>[i,Ke(o)])),n=Object.fromEntries(Object.entries(e).map(([i,o])=>[i,ji(i,o,t[i])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function ji(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var Ur=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,be(t)]).filter(([,e])=>e!==void 0)),jr=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?Ke(n):void 0]}))},be=r=>r===void 0?void 0:r.variant??r.enabled,Ke=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var Bi=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],xe=(r,e=[])=>{let t={},n=i=>{r[i]!==void 0&&(t[i]=r[i])};return Bi.forEach(n),e.forEach(n),t};var C=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function Mt(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var Gi="NativeGzipValidationError",Ki=31,qi=139,Wi=8,Vi=r=>r.length>=2&&r[0]===Ki&&r[1]===qi;var we,Xi=()=>{if(we)return we;we=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;we[r]=e>>>0}return we},Qi=r=>{let e=Xi(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},qe=r=>{let e=new Error(`Native gzip produced invalid output: ${r}`);throw e.name=Gi,e},Ji=async(r,e)=>{r.size<18&&qe("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!Vi(t)||t[2]!==Wi)&&qe("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==Qi(e)&&qe("invalid-crc");let i=e.length>>>0;n.getUint32(4,!0)!==i&&qe("invalid-size")};async function K(r,e=!0,t){try{let n=new TextEncoder().encode(r),i=new globalThis.CompressionStream("gzip"),o=i.writable.getWriter(),s=o.write(n).then(()=>o.close()).catch(async c=>{try{await o.abort(c)}catch{}throw c}),a=new Response(i.readable).blob(),[u]=await Promise.all([a,s]);return await Ji(u,n),u}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var Yi=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Br=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return Yi.concat(e).some(n=>{let i=n.toLowerCase();return t.indexOf(i)!==-1})};function oe(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var to=Array.isArray,Hr=Object.prototype,wp=Hr.hasOwnProperty,We=Hr.toString,M=to||function(r){return We.call(r)==="[object Array]"};var Pe=r=>r===Object(r)&&!M(r);var q=r=>r===void 0,D=r=>We.call(r)=="[object String]",Gr=r=>D(r)&&r.trim().length===0,Kr=r=>r===null;var Ee=r=>We.call(r)=="[object Number]"&&r===r;var qr=r=>We.call(r)==="[object Boolean]";var Wr=r=>r instanceof Error;function Ve(r){return r===null||typeof r!="object"}function W(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function Vr(r){return W(r,"ErrorEvent")}function se(r){return typeof Event<"u"&&ro(r,Event)}function Xr(r){return W(r,"Object")}function ro(r,e){try{return r instanceof e}catch{return!1}}function $e(r,e,t,n,i){return e>t&&(n.warn("min cannot be greater than max."),e=t),Ee(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+i),$e(i||t,e,t,n))}var no=864e5,io=1,oo=10;function Qr(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??io,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??oo}}var Xe=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=$e(e.bucketSize,0,100,e._logger),this._refillRate=$e(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=$e(e.refillInterval,0,no,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,i=Math.floor(n/this._refillInterval);if(i>0){let o=i*this._refillRate;e.tokens=Math.min(e.tokens+o,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),i=this._buckets[n];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=i),i.tokens===0?!0:(i.tokens--,i.tokens===0&&this._onBucketRateLimited?.(e),i.tokens===0)}stop(){this._buckets={}}};var Qe="0123456789abcdef",Je=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(i)||e<0||t<0||n<0||i<0||e>0xffffffffffff||t>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");let o=new Uint8Array(16);return o[0]=e/2**40,o[1]=e/2**32,o[2]=e/2**24,o[3]=e/2**16,o[4]=e/256,o[5]=e,o[6]=112|t>>>8,o[7]=t,o[8]=128|n>>>24,o[9]=n>>>16,o[10]=n>>>8,o[11]=n,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new r(o)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let i=0;i<16;i+=4){let o=parseInt(t.substring(2*i,2*i+8),16);n[i+0]=o>>>24,n[i+1]=o>>>16,n[i+2]=o>>>8,n[i+3]=o}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Qe.charAt(this.bytes[t]>>>4),e+=Qe.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=Qe.charAt(this.bytes[t]>>>4),e+=Qe.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},Nt=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??so()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Je.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,Je.ofInner(e)}},so=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),Jr,k=()=>ao().toString(),ao=()=>(Jr||(Jr=new Nt)).generate();var Ye=class{add(e){let t=k(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(i=>i.id<=t&&!n.has(i.promise)).map(i=>i.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function co(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Yr=(r,e,t)=>{function n(o,...s){e(()=>{let a=t[o];a(r,...s)})}return{debug:(...o)=>{n("debug",...o)},info:(...o)=>{n("log",...o)},warn:(...o)=>{n("warn",...o)},error:(...o)=>{n("error",...o)},critical:(...o)=>{t.error(r,...o)},createLogger:o=>Yr(`${r} ${o}`,e,t)}},uo=r=>r();function en(r,e=uo){return Yr(r,e,co())}var ce="Mobile",tt="iOS",ae="Android",sn="Tablet",Tp=ae+" "+sn;var po="Apple",Op=po+" Watch",an="Safari",rt="BlackBerry",cn="Samsung",fo=cn+"Browser",ho=cn+" Internet",nt="Chrome",go=nt+" OS",mo=nt+" "+tt,un="Internet Explorer",_o=un+" "+ce,Zt="Opera",Mp=Zt+" Mini",ln="Edge",yo="Microsoft "+ln,Dt="Firefox",vo=Dt+" "+tt,Ut="Nintendo",jt="PlayStation",et="Xbox",bo=ae+" "+ce,xo=ce+" "+an,Fe="Windows",wo=Fe+" Phone";var pn="Generic",Np=pn+" "+ce.toLowerCase(),Lp=pn+" "+sn.toLowerCase(),Po="Konqueror",Eo="Oculus Browser",tn="Vivaldi",$o="Yandex",rn="Whale",Fo="DuckDuckGo",So="Pale Moon",nn="Waterfox",on="Brave",Io="Google Search App",w="(\\d+(\\.\\d+)?)",Lt=new RegExp("Version/"+w);var Zp=new RegExp(et,"i"),Dp=new RegExp(jt+" \\w+","i"),Up=new RegExp(Ut+" \\w+","i"),zo=new RegExp(rt+"|PlayBook|BB10","i"),Ao={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var jp={[_o]:[new RegExp("rv:"+w)],[yo]:[new RegExp(ln+"?\\/"+w)],[nt]:[new RegExp("("+nt+"|CrMo)\\/"+w)],[mo]:[new RegExp("CriOS\\/"+w)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+w)],[an]:[Lt],[xo]:[Lt],[Zt]:[new RegExp("("+Zt+"|OPR)\\/"+w)],[Dt]:[new RegExp(Dt+"\\/"+w)],[vo]:[new RegExp("FxiOS\\/"+w)],[Po]:[new RegExp("Konqueror[:/]?"+w,"i")],[rt]:[new RegExp(rt+" "+w),Lt],[bo]:[new RegExp("android\\s"+w,"i")],[ho]:[new RegExp(fo+"\\/"+w)],[Eo]:[new RegExp("OculusBrowser\\/"+w)],[tn]:[new RegExp(tn+"\\/"+w)],[$o]:[new RegExp("YaBrowser\\/"+w)],[rn]:[new RegExp(rn+"\\/"+w)],[on]:[new RegExp(on+"\\/"+w)],[Fo]:[new RegExp("(DuckDuckGo|Ddg)\\/"+w)],[So]:[new RegExp("PaleMoon\\/"+w)],[nn]:[new RegExp(nn+"\\/"+w)],[Io]:[new RegExp("GSA\\/"+w)],[un]:[new RegExp("(rv:|MSIE )"+w)],Mozilla:[new RegExp("rv:"+w)]};var Bp=[[new RegExp(et+"; "+et+" (.*?)[);]","i"),r=>[et,r&&r[1]||""]],[new RegExp(Ut,"i"),[Ut,""]],[new RegExp(jt,"i"),[jt,""]],[zo,[rt,""]],[new RegExp(Fe,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[wo,""];if(new RegExp(ce).test(e)&&!/IEMobile\b/.test(e))return[Fe+" "+ce,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],i=Ao[n]||"";return/arm/i.test(e)&&(i="RT"),[Fe,i]}return[Fe,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[tt,e.join(".")]}return[tt,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=q(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+ae+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ae+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[ae,e.join(".")]}return[ae,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[go,""]],[/Linux|debian/i,["Linux",""]]];var fn="utf8",Co=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ko(r){return typeof r=="string"&&Co.test(r)}function it(r,e){return ko(r)?r:e()}function dn(r){return r?.replace(/\/+$/,"")}async function hn(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(i=>setTimeout(i,e.retryDelay));try{return await r()}catch(i){if(t=i,!e.retryCheck(i))throw i}}throw t}function Bt(){return new Date().toISOString()}function I(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}var gn=r=>r instanceof Error;function Ht(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var To={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},tf=To.info;function Gt(r){if(qr(r))return{boolValue:r};if(typeof r=="number")return Number.isFinite(r)?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:{stringValue:String(r)};if(typeof r=="string")return{stringValue:r};if(M(r))return{arrayValue:{values:r.map(e=>Gt(e))}};try{return{stringValue:JSON.stringify(r)}}catch{return{stringValue:String(r)}}}function Se(r){let e=[];for(let t in r){let n=r[t];Kr(n)||q(n)||e.push({key:t,value:Gt(n)})}return e}var Ie=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Kt(r){return String(r)+"000000"}function qt(r,e,t,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${r}\0${e}\0${t??""}\0${i}`}function mn(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function Wt(r,e,t){return{...r.resourceAttributes,"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}function Vt(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Se(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function ot(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var _n=1,ze=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,i;try{n=t.attributes?{...t.attributes}:void 0,i=qt(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let o=this._series.get(i);if(!o){if(!this._admitNewSeries())return;o={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(i,o)}let s=this._typeByName.get(t.name);s===void 0?this._typeByName.set(t.name,t.type):s!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(o,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Ie.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[mn(t,Ie)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=M(t)?t:[t],i=e;for(let o of n)try{let s=o(i);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;i=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return i}_armFlushTimer(){this._flushTimer||(this._flushTimer=I(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return Vt(this._buildMetrics(e),Wt(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Kt(Date.now()),n=new Map;for(let i of e.values()){let o=qt(i.type,i.name,i.unit,void 0),s=n.get(o);s||(s={name:i.name,...i.unit&&{unit:i.unit}},i.type==="count"?s.sum={aggregationTemporality:_n,isMonotonic:!0,dataPoints:[]}:i.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:_n,dataPoints:[]},n.set(o,s));let a=Se(i.attributes??{}),u=Kt(i.windowStartMs);if(i.type==="count"){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(c)}else if(i.type==="gauge"){let c={attributes:a,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(c)}else if(i.hist){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:Ie};s.histogram.dataPoints.push(c)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let i=this._series.get(t);if(!i){this._admitNewSeries()&&this._series.set(t,n);continue}switch(i.windowStartMs=Math.min(i.windowStartMs,n.windowStartMs),i.type){case"count":i.total=(i.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(i.hist){i.hist.count+=n.hist.count,i.hist.sum+=n.hist.sum,i.hist.min=Math.min(i.hist.min,n.hist.min),i.hist.max=Math.max(i.hist.max,n.hist.max);for(let o=0;o<i.hist.bucketCounts.length;o++)i.hist.bucketCounts[o]+=n.hist.bucketCounts[o]}else i.hist=n.hist;break}}}};var st=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};var A={};pr(A,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>pt,DOMExceptionCoercer:()=>Yt,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Oe,ErrorCoercer:()=>Ce,ErrorEventCoercer:()=>er,ErrorPropertiesBuilder:()=>Ae,EventCoercer:()=>tr,ExceptionStepsBuffer:()=>or,ObjectCoercer:()=>Re,PrimitiveCoercer:()=>Te,PromiseRejectionEventCoercer:()=>rr,ReduceableCache:()=>nr,StringCoercer:()=>ke,chromeStackLineParser:()=>Xt,createDefaultStackParser:()=>Jt,createStackParser:()=>In,geckoStackLineParser:()=>Qt,getUtf8ByteLength:()=>An,nodeStackLineParser:()=>En,opera10StackLineParser:()=>xn,opera11StackLineParser:()=>wn,resolveExceptionStepsConfig:()=>ir,reverseAndStripFrames:()=>Sn,stripReservedExceptionStepFields:()=>rs,winjsStackLineParser:()=>bn});var at,yn,ct;function vn(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return ct&&t.length===yn||(yn=t.length,ct=t.reduce((n,i)=>{at||(at={});let o=at[i];if(o)n[o[0]]=o[1];else{let s=r(i);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=e[i];if(c&&l){n[c]=l,at[i]=[c,l];break}}}return n},{})),ct}var Lo=4,Ae=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),a=this.buildParsingContext(t),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,i),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&M(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let i;return e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:i}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let i=[n];return e.cause!=null&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:vn(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let i=(s,a)=>{if(a<=Lo){let u=this.buildCoercingContext(e,t,a);return this.applyCoercers(s,u)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>i(s,n),next:s=>i(s,n+1)}}};var F="?";function N(r,e,t,n,i){let o={platform:r,filename:e,function:t==="<anonymous>"?F:t,in_app:!0};return q(n)||(o.lineno=n),q(i)||(o.colno=i),o}var ut=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:F,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var Zo=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Do=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Uo=/\((\S*)(?::(\d+))(?::(\d+))\)/,Xt=(r,e)=>{let t=Zo.exec(r);if(t){let[,i,o,s]=t;return N(e,i,F,+o,+s)}let n=Do.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=Uo.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[o,s]=ut(n[1]||F,n[2]);return N(e,s,o,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var jo=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Bo=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Qt=(r,e)=>{let t=jo.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let s=Bo.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let i=t[3],o=t[1]||F;return[o,i]=ut(o,i),N(e,i,o,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var Ho=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,bn=(r,e)=>{let t=Ho.exec(r);return t?N(e,t[2],t[1]||F,+t[3],t[4]?+t[4]:void 0):void 0};var Go=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,xn=(r,e)=>{let t=Go.exec(r);return t?N(e,t[2],t[3]||F,+t[1]):void 0},Ko=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,wn=(r,e)=>{let t=Ko.exec(r);return t?N(e,t[5],t[3]||t[4]||F,+t[1],+t[2]):void 0};var qo=/^\s*[-]{4,}$/,Wo=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Vo=/^Promise\.(?:all|any)$/,Xo=/^index \d+$/,Qo="node:internal/promise",En=(r,e)=>{let t=r.match(Wo);if(t){let n,i,o,s,a;if(t[1]){o=t[1];let l=o.lastIndexOf(".");if(o[l-1]==="."&&l--,l>0){n=o.slice(0,l),i=o.slice(l+1);let p=n.indexOf(".Module");p>0&&(o=o.slice(p+1),n=n.slice(0,p))}s=void 0}i&&(s=n,a=i),i==="<anonymous>"&&(a=void 0,o=void 0),o===void 0&&(a=a||F,o=s?`${s}.${a}`:a);let u=t[2]?.startsWith("file://")?t[2].slice(7):t[2],c=t[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&t[5]&&!c&&(u=t[5]),Vo.test(o)&&Xo.test(u||"")&&(u=Qo),{filename:u?decodeURI(u):void 0,module:void 0,function:o,lineno:Pn(t[3]),colno:Pn(t[4]),in_app:Jo(u||"",c),platform:e}}if(r.match(qo))return{filename:r,platform:e}};function Jo(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Pn(r){return parseInt(r||"",10)||void 0}var $n=/\(error: (.*)\)/,Fn=50;function Sn(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Fn).map(t=>({...t,filename:t.filename||Yo(e).filename,function:t.function||F}))}function Yo(r){return r[r.length-1]||{}}function Jt(){return In("web:javascript",Xt,Qt)}function In(r,...e){return(t,n=0)=>{let i=[],o=t.split(`
|
|
2
|
-
`);for(let s=n;s<o.length;s++){let a=o[s];if(a.length>1024)continue;let u=$n.test(a)?a.replace($n,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of e){let l=c(u,r);if(l){i.push(l);break}}if(i.length>=Fn)break}}return Sn(i)}}var Yt=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=D(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return W(e,"DOMException")}isDOMError(e){return W(e,"DOMError")}};var Ce=class{match(e){return Wr(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};var er=class{constructor(){}match(e){return Vr(e)&&e.error!=null}coerce(e,t){let n=t.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}};var es=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,ke=class{match(e){return typeof e=="string"}coerce(e,t){let[n,i]=this.getInfos(e);return{type:n??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,i=e.match(es);return i&&(t=i[1],n=i[2]),[t,n]}};var zn=["fatal","error","warning","log","info","debug"];function lt(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let i=t.slice(0,n).join(", ");if(!(i.length>e))return n===t.length||i.length<=e?i:`${i.slice(0,e)}...`}return""}var Re=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return se(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let i=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(i+=` with message: '${e.message}'`),i}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=lt(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return D(e)&&!Gr(e)&&zn.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(gn(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var tr=class{match(e){return se(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${lt(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Te=class{match(e){return Ve(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var rr=class{match(e){return W(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!se(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Ve(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var nr=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Oe={MESSAGE:"$message",TIMESTAMP:"$timestamp"},ts=new Set([Oe.MESSAGE,Oe.TIMESTAMP]),pt={enabled:!0,max_bytes:32768};function ir(r){return r?{enabled:r.enabled??pt.enabled,max_bytes:ns(r.max_bytes,pt.max_bytes)}:{...pt}}function rs(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,i)=>ts.has(i)?(e.push(i),n):(n[i]=r[i],n),{}),droppedKeys:e}}var or=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=ir(e)}setConfig(e){this._config=ir(e),this._trimToMaxBytes()}add(e){let t=is(e);if(!t)return;let n=An(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function ns(r,e){if(!Ee(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function is(r){let e;try{e=oe(r)}catch{return}try{let t=JSON.parse(e);if(!Pe(t))return;let n=t,i=n[Oe.MESSAGE],o=n[Oe.TIMESTAMP];return!D(i)||i.trim().length===0||!D(o)&&!Ee(o)?void 0:{step:n,json:e}}catch{return}}function An(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}var U=class extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},G=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var Rn=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function Cn(r){if(r instanceof U){let e="";try{e=await r.text}catch{}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function os(r){return typeof r=="object"&&(r instanceof U||Tn(r))}function Tn(r){return r instanceof G}function ss(r){if(r instanceof U)return r.status===502||r.status===504;if(!(r instanceof G))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}function ue(r){return typeof r=="object"&&r instanceof U&&r.status===413}function Me(r){return r instanceof U?r.status===408||r.status===429||r.status>=500:Tn(r)}function kn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var sr="default",Ne=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Ae([new Ce,new Re,new ke,new Te],Jt())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new Ye,this._events=new st,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",i=typeof t.host=="string"?t.host.trim():"",o=!n;this._logger=en("[PostHog]",this.logMsgIfDebug.bind(this)),o&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=dn(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:Me},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||o,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Mt()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(C.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(C.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(C.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,i)=>this._logger.info(n,i));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return Rn(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=xe(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,n)})}async identifyStatelessImmediate(e,t,n){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,n)}captureStateless(e,t,n,i){this.wrap(()=>{let o=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",o,i)})}async captureStatelessImmediate(e,t,n,i){let o=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",o,i)}aliasStateless(e,t,n,i){this.wrap(()=>{let o=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",o,i)})}async aliasStatelessImmediate(e,t,n,i){let o=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",o,i)}groupIdentifyStateless(e,t,n,i,o,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});this.enqueue("capture",a,i)})}async groupIdentifyStatelessImmediate(e,t,n,i,o,s){let a=this.buildPayload({distinct_id:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(i=>i.json()).catch(i=>{this._logger.error("Remote config could not be loaded",i),this._events.emit("error",i)})}async getFlags(e,t={},n={},i={},o={},s=!1){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:i,...o};n.$device_id&&(c.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:ss},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:Ot(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof U)return{type:"api_error",statusCode:e.status};if(e instanceof G){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,i,o,s);if(a===void 0)return{response:void 0,requestId:void 0};let u=be(a.response);return u===void 0&&(u=!1),{response:u,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,i,o,s,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},i={},o={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,i,o,s,[e]);if(!a)return;let u=a[e];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(e,t={},n={},i={},o,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,i,o,s)).payloads}async getFeatureFlagsStateless(e,t={},n={},i={},o,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,i,o,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},i={},o,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,i,o,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},i={},o,s){await this._initPromise;let a={geoip_disable:o??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(e,t,n,i,a);if(!u.success)return;let c=u.response;return c.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"),c.quotaLimited?.includes("feature_flags")?(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"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},i=(await this.fetchWithRetry(e,t).then(o=>{if(o.status!==200||!o.json){let s=`Surveys API could not be loaded: ${o.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return o.json()}).catch(o=>{this._logger.error("Surveys API could not be loaded",o),this._events.emit("error",o)}))?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(C.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(C.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(C.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return sr}persistedQueueKeyForRoute(e){return C.Queue}getActiveQueueRoutes(){return[sr]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i===null)return;i=this.normalizeMessage(i);let o=this.persistedQueueKeyForRoute(this.getQueueRouteKey(i)),s=this.getPersistedProperty(o)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),s.push({message:i}),this.setPersistedProperty(o,s),this._events.emit(e,i),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=I(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let i=this.prepareMessage(t,n);if(i=this.processBeforeEnqueue(i),i!==null){i=this.normalizeMessage(i);try{await this.sendBatch([i],void 0,this.getQueueRouteKey(i))}catch(o){this._events.emit("error",o)}}}normalizeMessage(e){let{type:t,library:n,library_version:i,...o}=e,s=kn(o.properties)?o.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),i!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:i}),s&&(o.properties=s),o.uuid=it(o.uuid,k),o}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:Bt(),uuid:it(t?.uuid,k)};return(t?.disableGeoip??this.disableGeoip)&&(kn(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await Cn(e)})}async waitForPendingPromises(e,t=[]){let n=t.filter(o=>!!o),i=0;for(;;){let o=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(o.length===0)return;i>0&&this._logger.debug(`flush() re-checking ${o.length} pending promise(s) before flushing`),await Promise.all(o.map(s=>s.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,i])}).then(()=>Ht([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),Ht([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}async sendBatch(e,t,n=sr){let i={api_key:this.apiKey,batch:e,sent_at:Bt()};this.historicalMigration&&(i.historical_migration=!0);let o=oe(i),s=`${this.host}/batch/`,a=this.disableCompression?null:await K(o,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||o};await(await this.fetchWithRetry(s,u,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(i=>this.getRouteQueue(i).length>0))return;let t=[],n;for(let i of e)try{await this._flushRoute(i,t)}catch(o){n===void 0&&(n=o)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(n)||[];if(!i.length)return;let o=i.length,s=0;for(;i.length>0&&s<o;){let a=i.slice(0,this.maxBatchSize),u=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),c=async()=>{let f=(this.getPersistedProperty(n)||[]).slice(a.length);this.setPersistedProperty(n,f),i=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:p=>ue(p)?!1:Me(p)};try{await this.sendBatch(u,l,e)}catch(p){if(ue(p)&&u.length>1){this.maxBatchSize=Math.max(1,Math.floor(u.length/2)),this._logger.warn(`Received 413 when sending batch of size ${u.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof G||await c(),this._events.emit("error",p),p}await c(),t.push(...u),s+=u.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await K(t,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(n,o,{retryCheck:s=>ue(s)?!1:Me(s)}),{kind:"ok"}}catch(s){return ue(s)?{kind:"too-large"}:s instanceof G?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,i=this.disableCompression?null:await K(t,this.isDebug),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...i!==null&&{"Content-Encoding":"gzip"}},body:i||t};try{return await this.fetchWithRetry(n,o,{retryCheck:s=>ue(s)?!1:Me(s)}),{kind:"ok"}}catch(s){return ue(s)?{kind:"too-large"}:Me(s)?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(e,t,n,i){let o=t.body?t.body:"",s=-1;try{s=o instanceof Blob?o.size:Buffer.byteLength(o,fn)}catch{o instanceof Blob?s=o.size:s=new TextEncoder().encode(o).length}return await hn(async()=>{let a=new AbortController,u=i??this.requestTimeout,c=I(()=>a.abort(),u),l=null;try{l=await this.fetch(e,{signal:a.signal,...t})}catch(f){throw new G(f)}finally{clearTimeout(c)}if(!(t.mode==="no-cors")&&(l.status<200||l.status>=400))throw new U(l,s);return l},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(o){if(!os(o))throw o;await Cn(o)}},i;try{return await Promise.race([new Promise((o,s)=>{i=I(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),n()])}finally{clearTimeout(i)}}async shutdown(e=3e4){return 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"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var Nn=require("fs"),Ln=require("readline"),ft=new A.ReduceableCache(25),Zn=new A.ReduceableCache(20),ar=7,ps=1e3,fs=1e4;async function Dn(r){let e={};for(let i=r.length-1;i>=0;i--){let o=r[i],s=o?.filename;if(!o||typeof s!="string"||typeof o.lineno!="number"||ms(s)||_s(o))continue;e[s]||(e[s]=[]),e[s].push(o.lineno)}let t=Object.keys(e);if(t.length==0)return r;let n=[];for(let i of t){if(Zn.get(i))continue;let o=e[i];if(!o)continue;o.sort((u,c)=>u-c);let s=vs(o);if(s.every(u=>ys(i,u)))continue;let a=bs(ft,i,{});n.push(ds(i,s,a))}return await Promise.all(n).catch(()=>{}),r&&r.length>0&&hs(r,ft),ft.reduce(),r}function ds(r,e,t){return new Promise(n=>{let i=(0,Nn.createReadStream)(r),o=(0,Ln.createInterface)({input:i});function s(){i.destroy(),n()}let a=0,u=0,c=e[u];if(c===void 0)return void s();let l=c[0],p=c[1];function f(){Zn.set(r,1),o.close(),o.removeAllListeners(),s()}i.on("error",f),o.on("error",f),o.on("close",s),o.on("line",d=>{if(a++,!(a<l)&&(t[a]=xs(d,0),a>=p)){if(u===e.length-1){o.close(),o.removeAllListeners();return}u++;let h=e[u];if(h===void 0){o.close(),o.removeAllListeners();return}l=h[0],p=h[1]}})})}function hs(r,e){for(let t of r)if(t.filename&&t.context_line===void 0&&typeof t.lineno=="number"){let n=e.get(t.filename);if(n===void 0)continue;gs(t.lineno,t,n)}}function gs(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let i=Un(r);i<r;i++){let o=t[i];if(o===void 0)return void On(e);e.pre_context.push(o)}if(t[r]===void 0)return void On(e);e.context_line=t[r];let n=jn(r);e.post_context=[];for(let i=r+1;i<=n;i++){let o=t[i];if(o===void 0)break;e.post_context.push(o)}}function On(r){delete r.pre_context,delete r.context_line,delete r.post_context}function ms(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function _s(r){return r.lineno!==void 0&&r.lineno>fs||r.colno!==void 0&&r.colno>ps}function ys(r,e){let t=ft.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function vs(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=Mn(t),i=[];for(;;){if(e===r.length-1){i.push(n);break}let o=r[e+1];if(typeof o!="number")break;o<=n[1]?n[1]=o+ar:(i.push(n),n=Mn(o)),e++}return i}function Mn(r){return[Un(r),jn(r)]}function Un(r){return Math.max(1,r-ar)}function jn(r){return r+ar}function bs(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function xs(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let i=Math.max(e-60,0);i<5&&(i=0);let o=Math.min(i+140,n);return o>n-5&&(o=n),o===n&&(i=Math.max(o-140,0)),t=t.slice(i,o),i>0&&(t=`...${t}`),o<n&&(t+="..."),t}var le=require("path");function Bn(r=process.cwd()){let e=le.sep==="\\",t=i=>e?i.replace(/\\/g,"/"):i,n=t(r);return async i=>{for(let o of i)!o.filename||o.filename.startsWith("node:")||o.filename.startsWith("data:")||(0,le.isAbsolute)(o.filename)&&(o.filename=t((0,le.relative)(n,t(o.filename))));return i}}var Hn="5.46.1";var j={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var V=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let i of e){let o=this._flags[i];o?t[i]=o:n.push(i)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,i]of Object.entries(this._flags)){let o=i.enabled===!1?!1:i.variant??!0;e[`$feature/${n}`]=o,i.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,i={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let o=[];this._errorsWhileComputing&&o.push(j.ERRORS_WHILE_COMPUTING),this._quotaLimited&&o.push(j.QUOTA_LIMITED),t===void 0&&o.push(j.FLAG_MISSING),o.length>0&&(i.$feature_flag_error=o.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}};async function Gn(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}var ws=6e4,Ps=1152921504606847e3,Es=["is_not","is_set"],pe=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function Vn(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var m=class r extends Error{constructor(e){super(e),Vn(this,r)}},L=class r extends Error{constructor(e){super(e),Vn(this,r)}},dt=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:i,host:o,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=n,this.host=o,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},i={},o={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:i,evaluationCache:o}}async getFeatureFlag(e,t,n={},i={},o={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[e],a!==void 0){let u=this.createEvaluationContext(t,n,i,o);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){c instanceof L||c instanceof m?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},i={},o=this.featureFlags.length==0,s=t?t.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(i[u.key]=l)}catch(c){c instanceof L||c instanceof m?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),o=!0}})),{response:n,payloads:i,fallbackToFlags:o}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:i,skipLoadCheck:o=!1}=n;if(o||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=i!==void 0?i:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:i,personProperties:o,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new m("Flag has experience continuity enabled");let u=(e.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${e.key}`)),new m("Flag has unknown group type index");if(!(c in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(o?.$device_id===void 0||o?.$device_id===null||o?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=s[c];return await this.matchFeatureFlagProperties(e,i[c],l,t)}{let c=this.getBucketingValueForFlag(e,n,o);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new m(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,o,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let i=n?.$device_id;return i==null||i===""?void 0:i}return t}getFeatureFlagPayload(e,t){let n=null;if(t!==!1&&t!=null&&(typeof t=="boolean"?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t=="string"&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:i}=n,o=e.key;if(!this.featureFlagsByKey)throw new m("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new m(`Flag dependency property for '${o}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new m(`Flag dependency property for '${o}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new m(`Circular dependency detected for flag '${o}' (empty dependency chain)`);for(let u of s){if(!(u in i)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);i[u]=p}catch(p){throw new m(`Error evaluating flag dependency '${u}' for flag '${o}': ${p}`)}else i[u]=!1;else throw new m(`Missing flag dependency '${u}' for flag '${o}'`)}if(i[u]==null)throw new m(`Dependency '${u}' could not be evaluated`)}let a=i[o];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,i){let o=e.filters||{},s=o.groups||[],a=o.aggregation_group_type_index,u=o.early_exit??!1,{groups:c,groupProperties:l}=i,p=!1,f;for(let d of s)try{let h=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,y=n,P=t;if(h!==a&&h!=null){let b=this.groupTypeMapping[String(h)];if(!b||!(b in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(b in l)){p=!0;continue}y=l[b],P=c[b]}let _=await this.isConditionMatch(e,P,d,y,i);if(_==="match"){let b=d.variant,O=o.multivariate?.variants||[];f=b&&O.some(R=>R.key===b)?b:await this.getMatchingVariant(e,P)||!0;break}if(u&&_==="out_of_rollout_bound")return!1}catch(h){if(h instanceof L)throw h;if(h instanceof m)p=!0;else throw h}if(f!==void 0)return f;if(p)throw new m("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,i,o){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(c==="cohort"){let p=await Qn(u,i,this.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,i,o));l=u.operator==="not_in"?!p:p}else l=c==="flag"?await this.evaluateFlagDependency(u,i,o):Xn(u,i,a);if(!l)return"no_match"}if(s==null)return"match"}return s!=null&&await Kn(e.key,t)>s/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let n=await Kn(e.key,t,"variant"),i=this.variantLookupTable(e).find(o=>n>=o.valueMin&&n<o.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],n=0,i=0;return((e.filters||{}).multivariate?.variants||[]).forEach(a=>{i=n+a.rollout_percentage/100,t.push({valueMin:n,valueMax:i,key:a.key}),n=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,n)=>(t[n.key]=n,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.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).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(ws,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new pe(`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`);case 402: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"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new pe(`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`);case 429:throw this.beginBackoff(),new pe(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(o){this.onError?.(new Error(`Failed to store in cache: ${o}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){e instanceof pe&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let i=new AbortController;n=I(()=>{i.abort()},this.timeout),t.signal=i.signal}try{let i=this.fetch;return i(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((n,i)=>setTimeout(()=>i(new Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};async function Kn(r,e,t=""){let n=await Gn(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/Ps}function Xn(r,e,t){let n=r.key,i=r.value,o=r.operator||"exact";if(n in e){if(o==="is_not_set")return!1}else{if(o==="is_not_set")return!0;throw new m(`Property ${n} not found in propertyValues`)}let s=e[n];if(s==null&&!Es.includes(o))return t&&t(`Property ${n} cannot have a value of null/undefined with the ${o} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(o){case"exact":return a(i,s);case"is_not":return!a(i,s);case"is_set":return n in e;case"icontains":return String(s).toLowerCase().includes(String(i).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(i).toLowerCase());case"regex":return qn(String(i))&&String(s).match(String(i))!==null;case"not_regex":return qn(String(i))&&String(s).match(String(i))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof i=="number"?i:parseFloat(String(i)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(c)&&Number.isFinite(l)?u(l,c,o):u(String(s),String(i),o)}case"is_date_after":case"is_date_before":{if(typeof i=="boolean")throw new m("Date operations cannot be performed on boolean values");let c=zs(String(i));if(c==null&&(c=Wn(i)),c==null)throw new m(`Invalid date: ${i}`);let l=Wn(s);return["is_date_before"].includes(o)?l<c:l>c}case"semver_eq":return T(S(String(s)),S(String(i)))===0;case"semver_neq":return T(S(String(s)),S(String(i)))!==0;case"semver_gt":return T(S(String(s)),S(String(i)))>0;case"semver_gte":return T(S(String(s)),S(String(i)))>=0;case"semver_lt":return T(S(String(s)),S(String(i)))<0;case"semver_lte":return T(S(String(s)),S(String(i)))<=0;case"semver_tilde":{let c=S(String(s)),{lower:l,upper:p}=Fs(String(i));return T(c,l)>=0&&T(c,p)<0}case"semver_caret":{let c=S(String(s)),{lower:l,upper:p}=Ss(String(i));return T(c,l)>=0&&T(c,p)<0}case"semver_wildcard":{let c=S(String(s)),{lower:l,upper:p}=Is(String(i));return T(c,l)>=0&&T(c,p)<0}default:throw new m(`Unknown operator: ${o}`)}}function $s(r,e){if(!(r in e))throw new L(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Qn(r,e,t,n=!1,i){let o=String(r.value);$s(o,t);let s=t[o];return Jn(s,e,t,n,i)}async function Jn(r,e,t,n=!1,i){if(!r)return!0;let o=r.type,s=r.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let u of s)try{let c=await Jn(u,e,t,n,i);if(o==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof L)throw c;if(c instanceof m)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new m("Can't match cohort without a given cohort property value");return o==="AND"}for(let u of s)try{let c;if(u.type==="cohort")c=await Qn(u,e,t,n,i);else if(u.type==="flag"){if(!i)throw new m(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);c=await i(u)}else c=Xn(u,e);let l=u.negation||!1;if(o==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof L)throw c;if(c instanceof m)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new m("can't match cohort without a given cohort property value");return o==="AND"}function qn(r){try{return new RegExp(r),!0}catch{return!1}}function Yn(r,e){if(!/^\d+$/.test(r))throw new m(`Invalid semver: ${e}`);if(r.length>1&&r[0]==="0")throw new m(`Invalid semver: ${e}`);return parseInt(r,10)}function S(r){let t=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new m(`Invalid semver: ${r}`);let n=t.split("."),i=u=>u===void 0||u===""?0:Yn(u,r),o=i(n[0]),s=i(n[1]),a=i(n[2]);return[o,s,a]}function T(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function Fs(r){let e=S(r),t=[e[0],e[1],e[2]],n=[e[0],e[1]+1,0];return{lower:t,upper:n}}function Ss(r){let e=S(r),[t,n,i]=e,o=[t,n,i],s;return s=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,i+1],{lower:o,upper:s}}function Is(r){let t=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!t)throw new m(`Invalid wildcard semver: ${r}`);let n=t.split("."),i=u=>{try{return Yn(u,r)}catch{throw new m(`Invalid wildcard semver: ${r}`)}},o=i(n[0]),s,a;if(n.length===1)s=[o,0,0],a=[o+1,0,0];else{let u=i(n[1]);s=[o,u,0],a=[o,u+1,0]}return{lower:s,upper:a}}function Wn(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new m(`${r} is in an invalid date format`)}throw new m(`The date provided ${r} must be a string, number, or date object`)}function zs(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let o=t.groups.interval;if(o=="h")n.setUTCHours(n.getUTCHours()-i);else if(o=="d")n.setUTCDate(n.getUTCDate()-i);else if(o=="w")n.setUTCDate(n.getUTCDate()-7*i);else if(o=="m")n.setUTCMonth(n.getUTCMonth()-i);else{if(o!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-i)}return n}}function As(r,e){let t=!1;return Object.assign(n=>{let o=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;r(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!t&&o&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function ei(r,e){globalThis.process?.on("uncaughtException",As(r,e))}function ti(r){globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var Cs=2e3,B=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Xe({...Qr(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Pe(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,i,o){let s={...o},a=e.buildFromUnknown(t,n);return a.$exception_list=await e.modifyFrames(a.$exception_list),{event:"$exception",distinctId:i,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(ei(this.onException.bind(this),this.onFatalError.bind(this)),ti(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),o=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(o)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:o}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(Cs),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var ht=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function ks(r){return r==="v0"||r==="v1"}function ri(){let r=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return ks(r)?r:"v0"}var Rs="$ai_",Le="analytics";function ni(r){return typeof r.event=="string"&&r.event.startsWith(Rs)}var fe=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:i}){super(r.buildMessage(e,t,n,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=i}static buildMessage(e,t,n,i){let o=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return i instanceof Error&&(o+=` (${i.message})`),o}};function cr(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function Ts(r){return typeof r=="string"?r:void 0}var Os=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:cr},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:cr},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:cr},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:Ts}],Ms=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function Ns(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ls(r){if(typeof r=="string"){let t=new Date(r);return Number.isNaN(t.getTime())?new Date().toISOString():r}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function ii(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function Zs(r){let t={...Ns(r.properties)?r.properties:{}},n={};for(let{property:o,optionKey:s,coerce:a}of Os)if(o in t){let u=a(t[o]);u!==void 0&&(n[s]=u),delete t[o]}let i={};for(let{property:o,field:s}of Ms)if(o in t){let a=t[o];typeof a=="string"&&(i[s]=a),delete t[o]}return delete t.$lib,delete t.$lib_version,ii(t,"$set",r.$set),ii(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:Ls(r.timestamp),...i,options:n,properties:t}}function oi(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(Zs)};return t&&(n.historical_migration=!0),n}var Ds="/i/v1/analytics/events",Us=3e4,js=new Set([408,500,502,503,504]),gt=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??Us,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(i=>I(i,n))),this.generateRequestId=t.generateRequestId??k,this.compress=t.compress??K}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:i}=oi(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),o=`${this.config.host}${Ds}`,s=[],a=i,u=Math.max(1,this.config.maxAttempts);for(let c=1;c<=u;c++){let l=c===u,p=oe({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),f;try{f=await this.sendOnce(o,p,c,t)}catch(_){if(l)return this.surfaceBatchFailure(t,s,a,_);await this.sleep(this.backoffDelay(c));continue}let{status:d}=f;if(d<200||d>=300){if(!l&&js.has(d)){let b=this.parseRetryAfter(f);await this.cancelBody(f),await this.sleep(this.backoffDelay(c,b));continue}let _=await this.buildHttpError(f,d);return this.surfaceBatchFailure(t,s,a,_)}let h;try{h=await this.parseResponse(f)}catch{return this.surfaceBatchFailure(t,s,a,new Error(`Capture V1 returned an unparseable ${d} response body`))}let y=this.classify(a,h,s);if(y.length===0)return this.surfacePartialDrops(t,s);if(l)return void this.onError(new fe({requestId:t,drops:s,retryExhausted:y.map(_=>_.uuid)}));a=y;let P=this.parseRetryAfter(f);await this.sleep(this.backoffDelay(c,P))}}async sendOnce(e,t,n,i){let o=this.buildHeaders(n,i),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);c!==null&&(s=c,o["Content-Encoding"]="gzip")}let a=new AbortController,u=I(()=>a.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:o,body:s,signal:a.signal})}finally{clearTimeout(u)}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,n){let i=t.results??{},o=[];for(let s of e){let a=i[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&o.push(s))}return o}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let i=Date.parse(n);if(Number.isNaN(i))return;let o=i-this.now();return o>0?o:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let i=n.results;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error("unexpected results shape");return{results:i??{}}}async buildHttpError(e,t){let n="";try{n=(await e.text()).slice(0,512)}catch{}let i=n?`: ${n}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${i}`)}surfaceBatchFailure(e,t,n,i){this.onError(new fe({requestId:e,drops:t,retryExhausted:n.map(o=>o.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new fe({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}};var Bs=100,si=3e4,Hs=5e4,Gs=50,Ks=500,qs="https://us.i.posthog.com",ai=new Set;function _t(r,e){ai.has(r)||(ai.add(r),console.warn(`[PostHog] ${e}`))}function Ws(r){return typeof r=="string"?r.trim():""}function Vs(r){return(typeof r=="string"?r.trim():"")||void 0}function Xs(r){return(typeof r=="string"?r.trim():"")||qs}function Qs(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function Js(r){if(!r)return{};let e={};for(let[n,i]of Object.entries(r))e[`$feature/${n}`]=i;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var yt=class extends Ne{constructor(e,t={}){let n=Ws(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:Xs(t.host),personalApiKey:Vs(t.secretKey??t.personalApiKey)};if(super(n,i),this._memoryStorage=new ht,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=ri(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof i.featureFlagsPollingInterval=="number"?Math.max(i.featureFlagsPollingInterval,Bs):si,typeof i.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),typeof i.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.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.');i.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new dt({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:n,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new B(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||Hs}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(u=>{s=u});try{e(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??Ks,i=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),i)return void this.resolveWaitUntilFlush();let o=this.options.waitUntilDebounceMs??Gs;this._waitUntilCycle.timer=I(()=>{this.resolveWaitUntilFlush()},o)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&ni(e)?"ai":Le}persistedQueueKeyForRoute(e){return e==="ai"?C.AiQueue:C.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[Le,"ai"]:[Le]}async sendBatch(e,t,n=Le){if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let i=e.filter(o=>o!==void 0);await this.getV1Sender().sendV1Batch(i)}getV1Sender(){return this._v1Sender||(this._v1Sender=new gt({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return Hn}get metrics(){return this._metrics||(this._metrics=new ze(this,ot(this.options.metrics),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,i){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:o,event:s,properties:a,options:u})=>{let c={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},l={distinctId:o,event:s,properties:{...a,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,l,c):this.enqueue(e,l,c)}).catch(o=>{o&&console.error(o)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"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."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"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."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=t,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:i,$set_once:o,$anon_distinct_id:s,...a}=t,l={$set:i||a,$set_once:o||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(n).length>0&&(i.$set_once=n),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let n=Qs(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=si){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",o=>{clearTimeout(n),i(),t(o>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},i){if(this.disabled)return void this._logger.warn("The client is disabled");let o=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let g=this._flagOverrides[e];if(g===void 0)return;let x=this._payloadOverrides?.[e];return{key:e,enabled:g!==!1,variant:typeof g=="string"?g:void 0,payload:x}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(t,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d,h=!1,y,P,_,b,O,R,v;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let g=this.featureFlagsPoller?.featureFlagsByKey[e];if(g)try{let x=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(g,f,{matchValue:i});if(x){h=!0;let $=x.value;b=g.id,R="Evaluated locally",v=g.has_experiment,d={key:e,enabled:$!==!1,variant:typeof $=="string"?$:void 0,payload:x.payload??void 0}}}catch(x){if(x instanceof L||x instanceof m)this._logger?.info(`${x.name} when computing flag locally: ${e}: ${x.message}`);else throw x}}if(!h&&!u){let g=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,l,a,[e]);if(g===void 0)_=j.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=g.minimalFlagCalledEvents===!0,y=g.requestId,P=g.evaluatedAt;let x=[];g.errorsWhileComputingFlags&&x.push(j.ERRORS_WHILE_COMPUTING),g.quotaLimited?.includes("feature_flags")&&x.push(j.QUOTA_LIMITED);let $=g.flags[e];if($===void 0)x.push(j.FLAG_MISSING);else{b=$.metadata?.id,O=$.metadata?.version,R=$.reason?.description??$.reason?.code,v=$.metadata?.has_experiment;let Et;if($.metadata?.payload!==void 0)try{Et=JSON.parse($.metadata.payload)}catch{Et=$.metadata.payload}d={key:e,enabled:$.enabled,variant:$.variant,payload:Et}}x.length>0&&(_=x.join(","))}}if(o){let g=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,x={$feature_flag:e,$feature_flag_response:g,$feature_flag_id:b,$feature_flag_version:O,$feature_flag_reason:R,locally_evaluated:h,[`$feature/${e}`]:g,$feature_flag_request_id:y,$feature_flag_evaluated_at:h?Date.now():P};if(v!==void 0&&(x.$feature_flag_has_experiment=v),h&&this.featureFlagsPoller){let $=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();$!==void 0&&(x.$feature_flag_definitions_loaded_at=$)}_&&(x.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:g,groups:s,disableGeoip:a,properties:x})}return d!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[e]}),d}async getFeatureFlag(e,t,n){_t("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(i!==void 0)return i.enabled===!1?!1:i.variant??!0}async getFeatureFlagPayload(e,t,n,i){if(_t("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let o=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},n);if(o!==void 0)return o.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:i,options:o}=this._resolveDistinctId(t,n);return i?this._getFeatureFlagResult(e,i,{...o,sendFeatureFlagEvents:o?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){_t("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return i===void 0?void 0:i.enabled===!1?!1:!!(i.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:i}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:i}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,a),h={},y={},P=!0;if(d&&(h=d.response,y=d.payloads,P=d.fallbackToFlags),P&&!u){let _=await super.getFeatureFlagsAndPayloadsStateless(f.distinctId,f.groups,c,l,s,a);h={...h,..._.flags||{}},y={...y,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(y={...y,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:y}}async evaluateFlags(e,t){let{distinctId:n,options:i}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new V({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new V({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:o,disableGeoip:s,flagKeys:a}=i||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=i||{},p=this.addLocalPersonAndGroupProperties(n,o,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(n,o,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d={},h,y,P=!1,_=!1,b=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,a),O=new Set;if(b)for(let[v,z]of Object.entries(b.response)){let g=this.featureFlagsPoller?.featureFlagsByKey[v];d[v]={key:v,enabled:z!==!1,variant:typeof z=="string"?z:void 0,payload:b.payloads[v],id:g?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:g?.has_experiment},O.add(v)}if((b?b.fallbackToFlags:!0)&&!u){let v=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,l,s,a);if(v){this._minimalFlagCalledEvents=v.minimalFlagCalledEvents===!0,h=v.requestId,y=v.evaluatedAt,P=!!v.errorsWhileComputingFlags,_=Array.isArray(v.quotaLimited)&&v.quotaLimited.includes("feature_flags");for(let[z,g]of Object.entries(v.flags)){if(O.has(z))continue;let x;if(g.metadata?.payload!==void 0)try{x=JSON.parse(g.metadata.payload)}catch{x=g.metadata.payload}d[z]={key:z,enabled:g.enabled,variant:g.variant,payload:x,id:g.metadata?.id,version:g.metadata?.version,reason:g.reason?.description??g.reason?.code,locallyEvaluated:!1,hasExperiment:g.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[v,z]of Object.entries(this._flagOverrides)){if(z===void 0){delete d[v];continue}let g=d[v];d[v]={key:v,enabled:z!==!1,variant:typeof z=="string"?z:void 0,payload:g?.payload,id:g?.id,version:g?.version,reason:g?.reason,locallyEvaluated:g?.locallyEvaluated??!1,hasExperiment:g?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[v,z]of Object.entries(this._payloadOverrides)){let g=d[v];g&&(d[v]={...g,payload:z})}return new V({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:o,disableGeoip:s,flags:d,requestId:h,evaluatedAt:y,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:P,quotaLimited:_})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:i,groups:o,disableGeoip:s,properties:a}=e,u=o&&Object.keys(o).length>0?`_${JSON.stringify(Object.entries(o).sort(([l],[p])=>l<p?-1:l>p?1:0))}`:"",c=`${n}_${i}${u}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(c):this.distinctIdHasSentFlagCalls[t]=new Set([c]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:o,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:i,disableGeoip:o}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:o},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:i,disableGeoip:o}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:o},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(i=>[i,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Promise.race([this._metrics.flush().catch(()=>{}),new Promise(i=>I(i,Math.max(0,t-Date.now())))]),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let o=new AbortController;i=I(()=>{o.abort()},this.options.requestTimeout),n.signal=o.signal}try{return await this.fetch(t,n)}catch(o){this._events.emit("error",o);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},i={};for(let[o,s]of Object.entries(e))if(Xr(s)&&t&&o in t){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);i[String(o)]=a}else n[String(o)]=String(s);return{personProperties:n,groupProperties:i}}async getFeatureFlagsForEvent(e,t,n,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let o=i?.personProperties||{},s=i?.groupProperties||{},a=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(t||{}))c[l]=String(p);return await this.getAllFlags(e,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(t||{}))c[l]=String(p);return await this.getAllFlags(e,{groups:c,personProperties:o,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,o,s,n)).flags}addLocalPersonAndGroupProperties(e,t,n,i){let o={...n||{}},s={};if(t)for(let a of Object.keys(t))s[a]={$group_key:t[a],...i?.[a]||{}};return{allPersonProperties:o,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,i){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,n,i,o){if(!B.isPreviouslyCapturedError(e)){let s=new Error("PostHog syntheticException");this.addPendingPromise(B.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,n).then(a=>this._capturePreparedEvent({...a,uuid:i,flags:o},!1)))}}async captureExceptionImmediate(e,t,n,i){if(!B.isPreviouslyCapturedError(e)){let o=new Error("PostHog syntheticException");return this.addPendingPromise(B.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:o},t,n).then(s=>this.captureImmediate({...s,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:i,properties:o,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:p}=e,f=this.context?.get(),d=t.includeContextProperties??!0,h=n||f?.distinctId,y=d?{...this.props,...f?.properties||{},...o||{}}:{...o||{}};h||(h=k(),y.$process_person_profile=!1),d&&f?.sessionId&&!y.$session_id&&(y.$session_id=f.sessionId);let P=this._shouldSendMinimalFlagCalledEvent(i,y)?xe(y):y,_=this._runBeforeSend({distinctId:h,event:i,properties:P,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:p});if(!_)return Promise.reject(null);let b=await Promise.resolve().then(async()=>{if(a)return u&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(u){_t("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let O=typeof u=="object"?u:void 0,R=await this.getFeatureFlagsForEvent(_.distinctId,s,l,O);return Js(R)}return{}}).catch(()=>({})).then(O=>{let R=_.groups||s;return{...O,..._.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof b.$raw_user_agent=="string"&&Br(b.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",b.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:b,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],i=e;for(let o of n){if(i=o(i),!i)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||Object.keys(i.properties).length===0){let s=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return i}};var ci=require("async_hooks"),vt=class{constructor(){this.storage=new ci.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var ui="posthog-node";function Ys(r,{organization:e,projectId:t,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}={}){return s=>{if(!(i==="*"||i.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[ur.POSTHOG_ID_TAG];if(u===void 0)return s;let c=r.options.host??"https://us.i.posthog.com",l=new URL(`/project/${r.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],f=p.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),d={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:f,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return e&&t&&(d.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+s.event_id),o&&r.capture({event:"$exception",distinctId:u,properties:d}),s}}var ur=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,n,i,o){this.name=ui,this.name=ui,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(Ys(e,{organization:t,projectId:u,prefix:n,severityAllowList:i,sendExceptionsToPostHog:o??!0}))}}};var bt=class extends yt{getLibraryId(){return"posthog-node"}initializeContext(){return new vt}createErrorPropertiesBuilder(){return new A.ErrorPropertiesBuilder([new A.EventCoercer,new A.ErrorCoercer,new A.ObjectCoercer,new A.StringCoercer,new A.PrimitiveCoercer],A.createStackParser("node:javascript",A.nodeStackLineParser),[Dr(),Dn,Bn()])}};var xt=null,lr=null;function wt(){return xt===null||lr===null?null:{client:xt,projectKey:lr}}function li(r){if(xt!==null)return;if(ne()){console.error("[HeyCatch] the server entry was bundled into a browser build - import '@heycatch/sdk' with your bundler's browser condition enabled. Server calls are no-ops here.");return}let e=Mr.safeParse(r);if(!e.success){let i=e.error.issues[0]?.message??"init() requires a config object with { projectKey }.";console.error(`[HeyCatch] ${i}`);return}let t=new bt(Tr,{host:Rr,flushAt:1,flushInterval:0,fetchRetryCount:1,fetchRetryDelay:250,requestTimeout:5e3});t.on("error",i=>{console.error("[HeyCatch] server send failed:",i)}),xt=t,lr=e.data.projectKey;let n=Or();n!==null&&console.warn(n)}function Pt(r){return{heycatch_project_key:r,heycatch_sdk_version:ve,heycatch_sdk_stage:ye}}async function pi(r,e,t){if(ne())return;let n=wt();if(n===null){console.error("[HeyCatch] setIdentity() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0){console.error("[HeyCatch] setIdentity() requires a non-empty string user id. Pass a stable internal user id from your auth provider \u2014 not an email or session token.");return}try{await n.client.captureImmediate({distinctId:r,event:"$identify",properties:{...e?{$set:e}:{},...t?{$set_once:t}:{},...Pt(n.projectKey)},groups:{[Ze]:n.projectKey}})}catch(i){console.error("[HeyCatch] setIdentity() failed to reach ingest:",i)}}function fi(r,e){console.error("[HeyCatch] setPersonProperties() has no ambient person on the server - use setIdentity(userId, properties) or trackEvent(..., { userId, set }).")}function di(){}var hi="X-POSTHOG-SESSION-ID";function ea(r){let e=r?.headers;if(!e)return null;try{if("get"in e&&typeof e.get=="function")return e.get(hi);let t=hi.toLowerCase();for(let[n,i]of Object.entries(e))if(n.toLowerCase()===t&&typeof i=="string")return i;return null}catch{return null}}async function gi(r,e,t){if(ne())return;let n=wt();if(n===null){console.error("[HeyCatch] trackEvent() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0||r.startsWith("$")){console.error('[HeyCatch] trackEvent() requires a non-empty event name that does not start with "$" (reserved for built-ins).');return}let i=t??{},o=i.userId;if(typeof o!="string"||o.length===0){console.error("[HeyCatch] trackEvent() on the server requires options.userId - there is no ambient person in a server process. Pass the same stable internal user id the client uses.");return}let s=ea(i.request);try{await n.client.captureImmediate({distinctId:o,event:r,properties:{...e,...s?{$session_id:s}:{},...i.set?{$set:i.set}:{},...i.setOnce?{$set_once:i.setOnce}:{},...Pt(n.projectKey),heycatch_custom_user_event:!0},groups:{[Ze]:n.projectKey}})}catch(a){console.error("[HeyCatch] trackEvent() failed to reach ingest:",a)}}var ta={init:li,resetIdentity:di,setIdentity:pi,setPersonProperties:fi,trackEvent:gi};0&&(module.exports={KNOWN_FRAMEWORKS,KNOWN_INSTALL_AGENTS,SDK_VERSION,STAGE,UNKNOWN_INSTALL_VALUE,analytics});
|
|
1
|
+
"use strict";var It=Object.defineProperty;var Bo=Object.getOwnPropertyDescriptor;var Ho=Object.getOwnPropertyNames;var Go=Object.prototype.hasOwnProperty;var mr=(r,e)=>{for(var t in e)It(r,t,{get:e[t],enumerable:!0})},Ko=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ho(e))!Go.call(r,o)&&o!==t&&It(r,o,{get:()=>e[o],enumerable:!(n=Bo(e,o))||n.enumerable});return r};var qo=r=>Ko(It({},"__esModule",{value:!0}),r);var Aa={};mr(Aa,{KNOWN_FRAMEWORKS:()=>ln,KNOWN_INSTALL_AGENTS:()=>pn,SDK_VERSION:()=>Pe,STAGE:()=>we,UNKNOWN_INSTALL_VALUE:()=>V,analytics:()=>Ca});module.exports=qo(Aa);function _r(){}function yr(){}var Be="project",Wo="[a-z0-9]",Ta=new RegExp(`^${Wo}$`);var vr;function v(r,e,t){function n(a,u){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(r))return;a._zod.traits.add(r),e(a,u);let c=s.prototype,l=Object.keys(c);for(let p=0;p<l.length;p++){let f=l[p];f in a||(a[f]=c[f].bind(a))}}let o=t?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:r});function s(a){var u;let c=t?.Parent?new i:this;n(c,a),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(r)}),Object.defineProperty(s,"name",{value:r}),s}var j=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(vr=globalThis).__zod_globalConfig??(vr.__zod_globalConfig={});var zt=globalThis.__zod_globalConfig;function ne(r){return r&&Object.assign(zt,r),zt}function xr(r){let e=Object.values(r).filter(n=>typeof n=="number");return Object.entries(r).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function wr(r,e){return typeof e=="bigint"?e.toString():e}function Pr(r){return{get value(){{let t=r();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function Er(r){let e=r.startsWith("^")?1:0,t=r.endsWith("$")?r.length-1:r.length;return r.slice(e,t)}var br=Symbol("evaluating");function W(r,e,t){let n;Object.defineProperty(r,e,{get(){if(n!==br)return n===void 0&&(n=br,n=t()),n},set(o){Object.defineProperty(r,e,{value:o})},configurable:!0})}var At="captureStackTrace"in Error?Error.captureStackTrace:(...r)=>{};function Ge(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function $r(r){if(Ge(r)===!1)return!1;let e=r.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Ge(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function kt(r){return $r(r)?{...r}:Array.isArray(r)?[...r]:r instanceof Map?new Map(r):r instanceof Set?new Set(r):r}var Fr=new Set(["string","number","symbol"]);function Sr(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rt(r,e,t){let n=new r._zod.constr(e??r._zod.def);return(!e||t?.parent)&&(n._zod.parent=r),n}function L(r){let e=r;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Ir(r){return Object.keys(r).filter(e=>r[e]._zod.optin==="optional"&&r[e]._zod.optout==="optional")}var Ma={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function me(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue!==!0)return!0;return!1}function zr(r,e=0){if(r.aborted===!0)return!0;for(let t=e;t<r.issues.length;t++)if(r.issues[t]?.continue===!1)return!0;return!1}function Tt(r,e){return e.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(r),t})}function He(r){return typeof r=="string"?r:r?.message}function oe(r,e,t){let n=r.message?r.message:He(r.inst?._zod.def?.error?.(r))??He(e?.error?.(r))??He(t.customError?.(r))??He(t.localeError?.(r))??"Invalid input",{inst:o,continue:i,input:s,...a}=r;return a.path??(a.path=[]),a.message=n,e?.reportInput&&(a.input=s),a}function Ot(...r){let[e,t,n]=r;return typeof e=="string"?{message:e,code:"custom",input:t,inst:n}:{...e}}var Cr=(r,e)=>{r.name="$ZodError",Object.defineProperty(r,"_zod",{value:r._zod,enumerable:!1}),Object.defineProperty(r,"issues",{value:e,enumerable:!1}),r.message=JSON.stringify(e,wr,2),Object.defineProperty(r,"toString",{value:()=>r.message,enumerable:!1})},Ar=v("$ZodError",Cr),ye=v("$ZodError",Cr,{Parent:Error});var Xo=r=>(e,t,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise)throw new j;if(s.issues.length){let a=new(o?.Err??r)(s.issues.map(u=>oe(u,i,ne())));throw At(a,o?.callee),a}return s.value},Ke=Xo(ye),Qo=r=>async(e,t,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=e._zod.run({value:t,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??r)(s.issues.map(u=>oe(u,i,ne())));throw At(a,o?.callee),a}return s.value},qe=Qo(ye),Jo=r=>(e,t,n)=>{let o=n?{...n,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},o);if(i instanceof Promise)throw new j;return i.issues.length?{success:!1,error:new(r??Ar)(i.issues.map(s=>oe(s,o,ne())))}:{success:!0,data:i.value}},ve=Jo(ye),Yo=r=>async(e,t,n)=>{let o=n?{...n,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new r(i.issues.map(s=>oe(s,o,ne())))}:{success:!0,data:i.value}},be=Yo(ye);var ei="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",ti=new RegExp(`^${ei}$`);var kr=r=>{let e=r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Rr=/^-?\d+(?:\.\d+)?$/,Tr=/^(?:true|false)$/i;var xe=v("$ZodCheck",(r,e)=>{var t;r._zod??(r._zod={}),r._zod.def=e,(t=r._zod).onattach??(t.onattach=[])});var Mr=v("$ZodCheckStringFormat",(r,e)=>{var t,n;xe.init(r,e),r._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(t=r._zod).check??(t.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:r,continue:!e.abort})}):(n=r._zod).check??(n.check=()=>{})}),Nr=v("$ZodCheckRegex",(r,e)=>{Mr.init(r,e),r._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:r,continue:!e.abort})}});var Zr={major:4,minor:4,patch:3};var N=v("$ZodType",(r,e)=>{var t;r??(r={}),r._zod.def=e,r._zod.bag=r._zod.bag||{},r._zod.version=Zr;let n=[...r._zod.def.checks??[]];r._zod.traits.has("$ZodCheck")&&n.unshift(r);for(let o of n)for(let i of o._zod.onattach)i(r);if(n.length===0)(t=r._zod).deferred??(t.deferred=[]),r._zod.deferred?.push(()=>{r._zod.run=r._zod.parse});else{let o=(s,a,u)=>{let c=me(s),l;for(let p of a){if(p._zod.def.when){if(zr(s)||!p._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,d=p._zod.check(s);if(d instanceof Promise&&u?.async===!1)throw new j;if(l||d instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await d,s.issues.length!==f&&(c||(c=me(s,f)))});else{if(s.issues.length===f)continue;c||(c=me(s,f))}}return l?l.then(()=>s):s},i=(s,a,u)=>{if(me(s))return s.aborted=!0,s;let c=o(a,n,u);if(c instanceof Promise){if(u.async===!1)throw new j;return c.then(l=>r._zod.parse(l,u))}return r._zod.parse(c,u)};r._zod.run=(s,a)=>{if(a.skipChecks)return r._zod.parse(s,a);if(a.direction==="backward"){let c=r._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(l=>i(l,s,a)):i(c,s,a)}let u=r._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new j;return u.then(c=>o(c,n,a))}return o(u,n,a)}}W(r,"~standard",()=>({validate:o=>{try{let i=ve(r,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return be(r,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Hr=v("$ZodString",(r,e)=>{N.init(r,e),r._zod.pattern=[...r?._zod.bag?.patterns??[]].pop()??kr(r._zod.bag),r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:r}),t}});var Gr=v("$ZodNumber",(r,e)=>{N.init(r,e),r._zod.pattern=r._zod.bag.pattern??Rr,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let o=t.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return t;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:o,inst:r,...i?{received:i}:{}}),t}});var Kr=v("$ZodBoolean",(r,e)=>{N.init(r,e),r._zod.pattern=Tr,r._zod.parse=(t,n)=>{if(e.coerce)try{t.value=!!t.value}catch{}let o=t.value;return typeof o=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:r}),t}});function Dr(r,e,t){r.issues.length&&e.issues.push(...Tt(t,r.issues)),e.value[t]=r.value}var qr=v("$ZodArray",(r,e)=>{N.init(r,e),r._zod.parse=(t,n)=>{let o=t.value;if(!Array.isArray(o))return t.issues.push({expected:"array",code:"invalid_type",input:o,inst:r}),t;t.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],u=e.element._zod.run({value:a,issues:[]},n);u instanceof Promise?i.push(u.then(c=>Dr(c,t,s))):Dr(u,t,s)}return i.length?Promise.all(i).then(()=>t):t}});function We(r,e,t,n,o,i){let s=t in n;if(r.issues.length){if(o&&i&&!s)return;e.issues.push(...Tt(t,r.issues))}if(!s&&!o){r.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}r.value===void 0?s&&(e.value[t]=void 0):e.value[t]=r.value}function ri(r){let e=Object.keys(r.shape);for(let n of e)if(!r.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let t=Ir(r.shape);return{...r,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function ni(r,e,t,n,o,i){let s=[],a=o.keySet,u=o.catchall._zod,c=u.def.type,l=u.optin==="optional",p=u.optout==="optional";for(let f in e){if(f==="__proto__"||a.has(f))continue;if(c==="never"){s.push(f);continue}let d=u.run({value:e[f],issues:[]},n);d instanceof Promise?r.push(d.then(h=>We(h,t,f,e,l,p))):We(d,t,f,e,l,p)}return s.length&&t.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:i}),r.length?Promise.all(r).then(()=>t):t}var Wr=v("$ZodObject",(r,e)=>{if(N.init(r,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let u={...a};return Object.defineProperty(e,"shape",{value:u}),u}})}let n=Pr(()=>ri(e));W(r._zod,"propValues",()=>{let a=e.shape,u={};for(let c in a){let l=a[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(let p of l.values)u[c].add(p)}}return u});let o=Ge,i=e.catchall,s;r._zod.parse=(a,u)=>{s??(s=n.value);let c=a.value;if(!o(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:r}),a;a.value={};let l=[],p=s.shape;for(let f of s.keys){let d=p[f],h=d._zod.optin==="optional",y=d._zod.optout==="optional",E=d._zod.run({value:c[f],issues:[]},u);E instanceof Promise?l.push(E.then(_=>We(_,a,f,c,h,y))):We(E,a,f,c,h,y)}return i?ni(l,c,a,u,n.value,r):l.length?Promise.all(l).then(()=>a):a}});var Vr=v("$ZodEnum",(r,e)=>{N.init(r,e);let t=xr(e.entries),n=new Set(t);r._zod.values=n,r._zod.pattern=new RegExp(`^(${t.filter(o=>Fr.has(typeof o)).map(o=>typeof o=="string"?Sr(o):o.toString()).join("|")})$`),r._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:t,input:s,inst:r}),o}});function Ur(r,e){return e===void 0&&(r.issues.length||r.fallback)?{issues:[],value:void 0}:r}var Xr=v("$ZodOptional",(r,e)=>{N.init(r,e),r._zod.optin="optional",r._zod.optout="optional",W(r._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),W(r._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${Er(t.source)})?$`):void 0}),r._zod.parse=(t,n)=>{if(e.innerType._zod.optin==="optional"){let o=t.value,i=e.innerType._zod.run(t,n);return i instanceof Promise?i.then(s=>Ur(s,o)):Ur(i,o)}return t.value===void 0?t:e.innerType._zod.run(t,n)}});var Qr=v("$ZodDefault",(r,e)=>{N.init(r,e),r._zod.optin="optional",W(r._zod,"values",()=>e.innerType._zod.values),r._zod.parse=(t,n)=>{if(n.direction==="backward")return e.innerType._zod.run(t,n);if(t.value===void 0)return t.value=e.defaultValue,t;let o=e.innerType._zod.run(t,n);return o instanceof Promise?o.then(i=>jr(i,e)):jr(o,e)}});function jr(r,e){return r.value===void 0&&(r.value=e.defaultValue),r}var Jr=v("$ZodCustom",(r,e)=>{xe.init(r,e),N.init(r,e),r._zod.parse=(t,n)=>t,r._zod.check=t=>{let n=t.value,o=e.fn(n);if(o instanceof Promise)return o.then(i=>Br(i,t,n,r));Br(o,t,n,r)}});function Br(r,e,t,n){if(!r){let o={code:"custom",input:t,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Ot(o))}}function Yr(r,e){return new r({type:"string",...L(e)})}function en(r,e){return new r({type:"number",checks:[],...L(e)})}function tn(r,e){return new r({type:"boolean",...L(e)})}function Mt(r,e){return new Nr({check:"string_format",format:"regex",...L(e),pattern:r})}function rn(r,e,t){let n=L(t);return n.abort??(n.abort=!0),new r({type:"custom",check:"custom",fn:e,...n})}var B=v("ZodMiniType",(r,e)=>{if(!r._zod)throw new Error("Uninitialized schema in ZodMiniType.");N.init(r,e),r.def=e,r.type=e.type,r.parse=(t,n)=>Ke(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>ve(r,t,n),r.parseAsync=async(t,n)=>qe(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>be(r,t,n),r.check=(...t)=>r.clone({...e,checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]},{parent:!0}),r.with=r.check,r.clone=(t,n)=>Rt(r,t,n),r.brand=()=>r,r.register=((t,n)=>(t.add(r,n),r)),r.apply=t=>t(r)}),ii=v("ZodMiniString",(r,e)=>{Hr.init(r,e),B.init(r,e)});function Q(r){return Yr(ii,r)}var si=v("ZodMiniNumber",(r,e)=>{Gr.init(r,e),B.init(r,e)});function nn(r){return en(si,r)}var ai=v("ZodMiniBoolean",(r,e)=>{Kr.init(r,e),B.init(r,e)});function J(r){return tn(ai,r)}var ci=v("ZodMiniArray",(r,e)=>{qr.init(r,e),B.init(r,e)});function Nt(r,e){return new ci({type:"array",element:r,...L(e)})}var ui=v("ZodMiniObject",(r,e)=>{Wr.init(r,e),B.init(r,e),W(r,"shape",()=>e.shape)});function Lt(r,e){let t={type:"object",shape:r??{},...L(e)};return new ui(t)}var li=v("ZodMiniEnum",(r,e)=>{Vr.init(r,e),B.init(r,e),r.options=Object.values(e.entries)});function on(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new li({type:"enum",entries:t,...L(e)})}var pi=v("ZodMiniOptional",(r,e)=>{Xr.init(r,e),B.init(r,e)});function T(r){return new pi({type:"optional",innerType:r})}var fi=v("ZodMiniDefault",(r,e)=>{Qr.init(r,e),B.init(r,e)});function ie(r,e){return new fi({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():kt(e)}})}var di=v("ZodMiniCustom",(r,e)=>{Jr.init(r,e),B.init(r,e)});function Zt(r,e){return rn(di,r??(()=>!0),e)}var sn="https://in.dev.heycatch.ai",we="dev",Pe="0.7.0-dev.974",an="phc_CqKdgm7xbFBs3mSdtqzrHNTfzTRKrwRmCrEB9aftENY9";function se(){return typeof globalThis.window<"u"}function cn(r=we){return r!=="dev"?null:`[HeyCatch] WARNING: this is an internal development build (v${Pe}). Events are being sent to the HeyCatch development environment and will NEVER appear in your dashboard. Reinstall the latest stable version - resolve it with \`npm view @heycatch/sdk version\` - or re-run the install guide: https://heycatch.ai/agents.md`}var V="unknown",mi=["localStorage","cookie","memory","localStorage+cookie","sessionStorage"];var un=Lt({projectKey:Q({error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'}).check(Mt(/^hck_pk_/,{error:'config.projectKey is missing or malformed \u2014 expected a string starting with "hck_pk_". Copy it from your project page in the HeyCatch dashboard.'})),tracingHosts:ie(Nt(Q()),[]),install:ie(Lt({framework:ie(Q(),V),frameworkVersion:ie(Q(),V),agent:ie(Q(),V)}),{framework:V,frameworkVersion:V,agent:V}),autocapture:T(J()),maskAllText:T(J()),maskAllElementAttributes:T(J()),propertyDenylist:T(Nt(Q())),sanitizeProperties:T(Zt(r=>typeof r=="function")),beforeSend:T(Zt(r=>typeof r=="function"||Array.isArray(r)&&r.every(e=>typeof e=="function"))),persistence:T(on(mi)),disablePersistence:T(J()),cookieExpirationDays:T(nn()),optOutCapturingByDefault:T(J()),respectDnt:T(J())}),ln=["nextjs","vite-react","react","vue","svelte","astro","angular","react-native","web"],pn=["lovable","bolt","v0","replit","cursor","claude-code","codex","windsurf","other"];var ae=require("path");function dn(){let r=_i();return async e=>{for(let t of e)t.module=r(t.filename);return e}}function _i(r=process.argv[1]?(0,ae.dirname)(process.argv[1]):process.cwd(),e=ae.sep==="\\"){let t=e?fn(r):r;return n=>{if(!n)return;let o=e?fn(n):n,{dir:i,base:s,ext:a}=ae.posix.parse(o);(a===".js"||a===".mjs"||a===".cjs")&&(s=s.slice(0,-1*a.length));let u=decodeURIComponent(s);i||(i=".");let c=i.lastIndexOf("/node_modules");if(c>-1)return`${i.slice(c+14).replace(/\//g,".")}:${u}`;if(i.startsWith(t)){let l=i.slice(t.length+1).replace(/\//g,".");return l?`${l}:${u}`:u}return u}}function fn(r){return r.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var Dt=r=>{if("flags"in r){let e=hn(r.flags),t=gn(r.flags);return{...r,featureFlags:e,featureFlagPayloads:t}}{let e=r.featureFlags??{},t=Object.fromEntries(Object.entries(r.featureFlagPayloads||{}).map(([o,i])=>[o,Ve(i)])),n=Object.fromEntries(Object.entries(e).map(([o,i])=>[o,yi(o,i,t[o])]));return{...r,featureFlags:e,featureFlagPayloads:t,flags:n}}};function yi(r,e,t){return{key:r,enabled:typeof e=="string"?!0:e,variant:typeof e=="string"?e:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:t?JSON.stringify(t):void 0,description:void 0}}}var hn=r=>Object.fromEntries(Object.entries(r??{}).map(([e,t])=>[e,Ee(t)]).filter(([,e])=>e!==void 0)),gn=r=>{let e=r??{};return Object.fromEntries(Object.keys(e).filter(t=>{let n=e[t];return n.enabled&&n.metadata&&n.metadata.payload!==void 0}).map(t=>{let n=e[t].metadata?.payload;return[t,n?Ve(n):void 0]}))},Ee=r=>r===void 0?void 0:r.variant??r.enabled,Ve=r=>{if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}};var vi=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],$e=(r,e=[])=>{let t={},n=o=>{r[o]!==void 0&&(t[o]=r[o])};return vi.forEach(n),e.forEach(n),t};var A=(function(r){return r.AnonymousId="anonymous_id",r.DistinctId="distinct_id",r.Props="props",r.EnablePersonProcessing="enable_person_processing",r.PersonMode="person_mode",r.FeatureFlagDetails="feature_flag_details",r.FeatureFlags="feature_flags",r.FeatureFlagPayloads="feature_flag_payloads",r.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",r.BootstrapFeatureFlags="bootstrap_feature_flags",r.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",r.OverrideFeatureFlags="override_feature_flags",r.Queue="queue",r.AiQueue="ai_queue",r.LogsQueue="logs_queue",r.OptedOut="opted_out",r.SessionId="session_id",r.SessionStartTimestamp="session_start_timestamp",r.SessionLastTimestamp="session_timestamp",r.PersonProperties="person_properties",r.GroupProperties="group_properties",r.InstalledAppBuild="installed_app_build",r.InstalledAppVersion="installed_app_version",r.SessionReplay="session_replay",r.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",r.SurveyLastSeenDate="survey_last_seen_date",r.SurveysSeen="surveys_seen",r.Surveys="surveys",r.RemoteConfig="remote_config",r.FlagsEndpointWasHit="flags_endpoint_was_hit",r.DeviceId="device_id",r})({});function Ut(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}var xi="NativeGzipValidationError",wi=31,Pi=139,Ei=8,$i=r=>r.length>=2&&r[0]===wi&&r[1]===Pi;var Fe,Fi=()=>{if(Fe)return Fe;Fe=[];for(let r=0;r<256;r++){let e=r;for(let t=0;t<8;t++)e=1&e?3988292384^e>>>1:e>>>1;Fe[r]=e>>>0}return Fe},Si=r=>{let e=Fi(),t=4294967295;for(let n=0;n<r.length;n++)t=e[(t^r[n])&255]^t>>>8;return(4294967295^t)>>>0},Xe=r=>{let e=new Error(`Native gzip produced invalid output: ${r}`);throw e.name=xi,e},Ii=async(r,e)=>{r.size<18&&Xe("too-short");let t=new Uint8Array(await r.slice(0,10).arrayBuffer());(!$i(t)||t[2]!==Ei)&&Xe("invalid-header");let n=new DataView(await r.slice(r.size-8).arrayBuffer());n.getUint32(0,!0)!==Si(e)&&Xe("invalid-crc");let o=e.length>>>0;n.getUint32(4,!0)!==o&&Xe("invalid-size")};async function Y(r,e=!0,t){try{let n=new TextEncoder().encode(r),o=new globalThis.CompressionStream("gzip"),i=o.writable.getWriter(),s=i.write(n).then(()=>i.close()).catch(async c=>{try{await i.abort(c)}catch{}throw c}),a=new Response(o.readable).blob(),[u]=await Promise.all([a,s]);return await Ii(u,n),u}catch(n){if(t?.rethrow)throw n;return e&&console.error("Failed to gzip compress data",n),null}}var zi=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],mn=function(r,e=[]){if(!r)return!1;let t=r.toLowerCase();return zi.concat(e).some(n=>{let o=n.toLowerCase();return t.indexOf(o)!==-1})};function ce(r){let e=[];return JSON.stringify(r,function(t,n){if(typeof n=="bigint")return n.toString();if(!(typeof n=="function"||typeof n=="symbol")){if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack};if(n&&typeof n=="object"){for(;e.length>0&&e[e.length-1]!==this;)e.pop();if(e.includes(n))return"[Circular]";e.push(n)}return n}})??"null"}var Ai=Array.isArray,_n=Object.prototype,Dp=_n.hasOwnProperty,Qe=_n.toString,Z=Ai||function(r){return Qe.call(r)==="[object Array]"};var Se=r=>r===Object(r)&&!Z(r);var ee=r=>r===void 0,H=r=>Qe.call(r)=="[object String]",yn=r=>H(r)&&r.trim().length===0,vn=r=>r===null;var Ie=r=>Qe.call(r)=="[object Number]"&&r===r;var bn=r=>Qe.call(r)==="[object Boolean]";var xn=r=>r instanceof Error;function Je(r){return r===null||typeof r!="object"}function te(r,e){return Object.prototype.toString.call(r)===`[object ${e}]`}function wn(r){return te(r,"ErrorEvent")}function ue(r){return typeof Event<"u"&&ki(r,Event)}function Pn(r){return te(r,"Object")}function ki(r,e){try{return r instanceof e}catch{return!1}}function ze(r,e,t,n,o){return e>t&&(n.warn("min cannot be greater than max."),e=t),Ie(r)?r>t?(n.warn(" cannot be greater than max: "+t+". Using max value instead."),t):r<e?(n.warn(" cannot be less than min: "+e+". Using min value instead."),e):r:(n.warn(" must be a number. using max or fallback. max: "+t+", fallback: "+o),ze(o||t,e,t,n))}var Ri=864e5,Ti=1,Oi=10;function En(r={}){return{refillRate:r.exceptionRateLimiterRefillRate??r.__exceptionRateLimiterRefillRate??Ti,bucketSize:r.exceptionRateLimiterBucketSize??r.__exceptionRateLimiterBucketSize??Oi}}var Ye=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=ze(e.bucketSize,0,100,e._logger),this._refillRate=ze(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=ze(e.refillInterval,0,Ri,e._logger)}_applyRefill(e,t){let n=t-e.lastAccess,o=Math.floor(n/this._refillInterval);if(o>0){let i=o*this._refillRate;e.tokens=Math.min(e.tokens+i,this._bucketSize),e.lastAccess=e.lastAccess+o*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),n=String(e),o=this._buckets[n];return o?this._applyRefill(o,t):(o={tokens:this._bucketSize,lastAccess:t},this._buckets[n]=o),o.tokens===0?!0:(o.tokens--,o.tokens===0&&this._onBucketRateLimited?.(e),o.tokens===0)}stop(){this._buckets={}}};var et="0123456789abcdef",tt=class r{constructor(e){this.bytes=e}static ofInner(e){if(e.length===16)return new r(e);throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,n,o){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(o)||e<0||t<0||n<0||o<0||e>0xffffffffffff||t>4095||n>1073741823||o>4294967295)throw new RangeError("invalid field value");let i=new Uint8Array(16);return i[0]=e/2**40,i[1]=e/2**32,i[2]=e/2**24,i[3]=e/2**16,i[4]=e/256,i[5]=e,i[6]=112|t>>>8,i[7]=t,i[8]=128|n>>>24,i[9]=n>>>16,i[10]=n>>>8,i[11]=n,i[12]=o>>>24,i[13]=o>>>16,i[14]=o>>>8,i[15]=o,new r(i)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;default:break}if(t){let n=new Uint8Array(16);for(let o=0;o<16;o+=4){let i=parseInt(t.substring(2*o,2*o+8),16);n[o+0]=i>>>24,n[o+1]=i>>>16,n[o+2]=i>>>8,n[o+3]=i}return new r(n)}throw new SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=et.charAt(this.bytes[t]>>>4),e+=et.charAt(15&this.bytes[t]),(t===3||t===5||t===7||t===9)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=et.charAt(this.bytes[t]>>>4),e+=et.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw new Error("unreachable");if(e<=7)return this.bytes.every(t=>t===0)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(t=>t===255)?"MAX":"VAR_RESERVED";throw new Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new r(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(let t=0;t<16;t++){let n=this.bytes[t]-e.bytes[t];if(n!==0)return Math.sign(n)}return 0}},jt=class{constructor(e){this.timestamp=0,this.counter=0,this.random=e??Mi()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let n=this.generateOrAbortCore(e,t);return n===void 0&&(this.timestamp=0,n=this.generateOrAbortCore(e,t)),n}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw new RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw new RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return tt.fromFieldsV7(this.timestamp,Math.trunc(this.counter/2**30),this.counter&2**30-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,tt.ofInner(e)}},Mi=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),$n,k=()=>Ni().toString(),Ni=()=>($n||($n=new jt)).generate();var rt=class{add(e){let t=k(),n=++this.nextId;return this.promiseByIds[t]={id:n,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length;for(;t>0;)await Promise.all(e),e=Object.values(this.promiseByIds).map(n=>n.promise),t=e.length}getPromises(e=[],t=this.nextId){let n=new Set(e);return Object.values(this.promiseByIds).filter(o=>o.id<=t&&!n.has(o.promise)).map(o=>o.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}};function Li(r=console){return{log:r.log.bind(r),warn:r.warn.bind(r),error:r.error.bind(r),debug:r.debug.bind(r)}}var Fn=(r,e,t)=>{function n(i,...s){e(()=>{let a=t[i];a(r,...s)})}return{debug:(...i)=>{n("debug",...i)},info:(...i)=>{n("log",...i)},warn:(...i)=>{n("warn",...i)},error:(...i)=>{n("error",...i)},critical:(...i)=>{t.error(r,...i)},createLogger:i=>Fn(`${r} ${i}`,e,t)}},Zi=r=>r();function Sn(r,e=Zi){return Fn(r,e,Li())}var pe="Mobile",ot="iOS",le="Android",kn="Tablet",Jp=le+" "+kn;var Ui="Apple",Yp=Ui+" Watch",Rn="Safari",it="BlackBerry",Tn="Samsung",ji=Tn+"Browser",Bi=Tn+" Internet",st="Chrome",Hi=st+" OS",Gi=st+" "+ot,On="Internet Explorer",Ki=On+" "+pe,Ht="Opera",ef=Ht+" Mini",Mn="Edge",qi="Microsoft "+Mn,Gt="Firefox",Wi=Gt+" "+ot,Kt="Nintendo",qt="PlayStation",nt="Xbox",Vi=le+" "+pe,Xi=pe+" "+Rn,Ce="Windows",Qi=Ce+" Phone";var Nn="Generic",tf=Nn+" "+pe.toLowerCase(),rf=Nn+" "+kn.toLowerCase(),Ji="Konqueror",Yi="Oculus Browser",In="Vivaldi",es="Yandex",zn="Whale",ts="DuckDuckGo",rs="Pale Moon",Cn="Waterfox",An="Brave",ns="Google Search App",P="(\\d+(\\.\\d+)?)",Bt=new RegExp("Version/"+P);var nf=new RegExp(nt,"i"),of=new RegExp(qt+" \\w+","i"),sf=new RegExp(Kt+" \\w+","i"),os=new RegExp(it+"|PlayBook|BB10","i"),is={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"};var af={[Ki]:[new RegExp("rv:"+P)],[qi]:[new RegExp(Mn+"?\\/"+P)],[st]:[new RegExp("("+st+"|CrMo)\\/"+P)],[Gi]:[new RegExp("CriOS\\/"+P)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+P)],[Rn]:[Bt],[Xi]:[Bt],[Ht]:[new RegExp("("+Ht+"|OPR)\\/"+P)],[Gt]:[new RegExp(Gt+"\\/"+P)],[Wi]:[new RegExp("FxiOS\\/"+P)],[Ji]:[new RegExp("Konqueror[:/]?"+P,"i")],[it]:[new RegExp(it+" "+P),Bt],[Vi]:[new RegExp("android\\s"+P,"i")],[Bi]:[new RegExp(ji+"\\/"+P)],[Yi]:[new RegExp("OculusBrowser\\/"+P)],[In]:[new RegExp(In+"\\/"+P)],[es]:[new RegExp("YaBrowser\\/"+P)],[zn]:[new RegExp(zn+"\\/"+P)],[An]:[new RegExp(An+"\\/"+P)],[ts]:[new RegExp("(DuckDuckGo|Ddg)\\/"+P)],[rs]:[new RegExp("PaleMoon\\/"+P)],[Cn]:[new RegExp(Cn+"\\/"+P)],[ns]:[new RegExp("GSA\\/"+P)],[On]:[new RegExp("(rv:|MSIE )"+P)],Mozilla:[new RegExp("rv:"+P)]};var cf=[[new RegExp(nt+"; "+nt+" (.*?)[);]","i"),r=>[nt,r&&r[1]||""]],[new RegExp(Kt,"i"),[Kt,""]],[new RegExp(qt,"i"),[qt,""]],[os,[it,""]],[new RegExp(Ce,"i"),(r,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Qi,""];if(new RegExp(pe).test(e)&&!/IEMobile\b/.test(e))return[Ce+" "+pe,""];let t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){let n=t[1],o=is[n]||"";return/arm/i.test(e)&&(o="RT"),[Ce,o]}return[Ce,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,r=>{if(r&&r[3]){let e=[r[3],r[4],r[5]||"0"];return[ot,e.join(".")]}return[ot,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,r=>{let e="";return r&&r.length>=3&&(e=ee(r[2])?r[3]:r[2]),["watchOS",e]}],[new RegExp("("+le+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+le+")","i"),r=>{if(r&&r[2]){let e=[r[2],r[3],r[4]||"0"];return[le,e.join(".")]}return[le,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,r=>{let e=["Mac OS X",""];if(r&&r[1]){let t=[r[1],r[2],r[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Hi,""]],[/Linux|debian/i,["Linux",""]]];var Ln="utf8",ss=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function as(r){return typeof r=="string"&&ss.test(r)}function at(r,e){return as(r)?r:e()}function Zn(r){return r?.replace(/\/+$/,"")}async function Dn(r,e){let t=null;for(let n=0;n<e.retryCount+1;n++){n>0&&await new Promise(o=>setTimeout(o,e.retryDelay));try{return await r()}catch(o){if(t=o,!e.retryCheck(o))throw o}}throw t}function Wt(){return new Date().toISOString()}function I(r,e){let t=setTimeout(r,e);return t?.unref&&t?.unref(),t}var Un=r=>r instanceof Error;function Vt(r){return Promise.all(r.map(e=>(e??Promise.resolve()).then(t=>({status:"fulfilled",value:t}),t=>({status:"rejected",reason:t}))))}var us={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},bf=us.info;function Xt(r){if(bn(r))return{boolValue:r};if(typeof r=="number")return Number.isFinite(r)?Number.isInteger(r)?{intValue:r}:{doubleValue:r}:{stringValue:String(r)};if(typeof r=="string")return{stringValue:r};if(Z(r))return{arrayValue:{values:r.map(e=>Xt(e))}};try{return{stringValue:JSON.stringify(r)}}catch{return{stringValue:String(r)}}}function Ae(r){let e=[];for(let t in r){let n=r[t];vn(n)||ee(n)||e.push({key:t,value:Xt(n)})}return e}var ke=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Qt(r){return String(r)+"000000"}function Jt(r,e,t,n){let o="";return n&&(o=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${r}\0${e}\0${t??""}\0${o}`}function jn(r,e){for(let t=0;t<e.length;t++)if(r<=e[t])return t;return e.length}function Yt(r,e,t){return{...r.resourceAttributes,"service.name":r.serviceName||"unknown_service",...r.environment&&{"deployment.environment":r.environment},...r.serviceVersion&&{"service.version":r.serviceVersion},"telemetry.sdk.name":e,"telemetry.sdk.version":t}}function er(r,e,t,n){return{resourceMetrics:[{resource:{attributes:Ae(e)},scopeMetrics:[{scope:{name:t,version:n},metrics:r}]}]}}function ct(r){let e=r?.resourceAttributes;return{serviceName:e?.["service.name"]??r?.serviceName,serviceVersion:e?.["service.version"]??r?.serviceVersion,environment:e?.["deployment.environment"]??r?.environment,resourceAttributes:e,beforeSend:r?.beforeSend,flushIntervalMs:r?.flushIntervalMs??1e4,maxSeriesPerFlush:r?.maxSeriesPerFlush??1e3}}var Bn=1,Re=class{constructor(e,t,n){this._instance=e,this._config=t,this._logger=n,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,n){this._capture({name:e,type:"count",value:t,unit:n?.unit,attributes:n?.attributes})}gauge(e,t,n){this._capture({name:e,type:"gauge",value:t,unit:n?.unit,attributes:n?.attributes})}histogram(e,t,n){this._capture({name:e,type:"histogram",value:t,unit:n?.unit,attributes:n?.attributes})}flush(){let e=this._flushPromise,n=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===n&&(this._flushPromise=null)});return this._flushPromise=n,n}drainWindow(){if(this._series.size===0)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(this._instance.isDisabled||this._instance.optedOut)return;let t=this._runBeforeSend(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this._logger.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&t.value<0)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let n,o;try{n=t.attributes?{...t.attributes}:void 0,o=Jt(t.type,t.name,t.unit,n)}catch(a){this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,a);return}let i=this._series.get(o);if(!i){if(!this._admitNewSeries())return;i={name:t.name,type:t.type,unit:t.unit,attributes:n,windowStartMs:Date.now()},this._series.set(o,i)}let s=this._typeByName.get(t.name);s===void 0?this._typeByName.set(t.name,t.type):s!==t.type&&!this._typeCollisionWarned.has(t.name)&&(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(i,t.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush?!0:(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(ke.length+1).fill(0)});let n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[jn(t,ke)]+=1;break}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let n=Z(t)?t:[t],o=e;for(let i of n)try{let s=i(o);if(!s)return this._logger.info("Metric was rejected in beforeSend function"),null;o=s}catch(s){return this._logger.error("Error in beforeSend function for metric:",s),null}return o}_armFlushTimer(){this._flushTimer||(this._flushTimer=I(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(this._series.size===0)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,n=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(n.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",n.error);return}}_buildPayload(e){return er(this._buildMetrics(e),Yt(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),this._instance.getLibraryId(),this._instance.getLibraryVersion())}_buildMetrics(e){let t=Qt(Date.now()),n=new Map;for(let o of e.values()){let i=Jt(o.type,o.name,o.unit,void 0),s=n.get(i);s||(s={name:o.name,...o.unit&&{unit:o.unit}},o.type==="count"?s.sum={aggregationTemporality:Bn,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:Bn,dataPoints:[]},n.set(i,s));let a=Ae(o.attributes??{}),u=Qt(o.windowStartMs);if(o.type==="count"){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,asDouble:o.total??0};s.sum.dataPoints.push(c)}else if(o.type==="gauge"){let c={attributes:a,timeUnixNano:t,asDouble:o.last??0};s.gauge.dataPoints.push(c)}else if(o.hist){let c={attributes:a,startTimeUnixNano:u,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:ke};s.histogram.dataPoints.push(c)}}return Array.from(n.values())}_mergeWindowBack(e){for(let[t,n]of e){let o=this._series.get(t);if(!o){this._admitNewSeries()&&this._series.set(t,n);continue}switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(o.total??0)+(n.total??0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(let i=0;i<o.hist.bucketCounts.length;i++)o.hist.bucketCounts[i]+=n.hist.bucketCounts[i]}else o.hist=n.hist;break}}}};var ut=class{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(n=>n!==t)}}emit(e,t){for(let n of this.events[e]||[])n(t);for(let n of this.events["*"]||[])n(e,t)}};var C={};mr(C,{DEFAULT_EXCEPTION_STEPS_CONFIG:()=>ht,DOMExceptionCoercer:()=>or,EXCEPTION_STEP_INTERNAL_FIELDS:()=>Ze,ErrorCoercer:()=>Oe,ErrorEventCoercer:()=>ir,ErrorPropertiesBuilder:()=>Te,EventCoercer:()=>sr,ExceptionStepsBuffer:()=>lr,ObjectCoercer:()=>Ne,PrimitiveCoercer:()=>Le,PromiseRejectionEventCoercer:()=>ar,ReduceableCache:()=>cr,StringCoercer:()=>Me,chromeStackLineParser:()=>tr,createDefaultStackParser:()=>nr,createStackParser:()=>eo,geckoStackLineParser:()=>rr,getUtf8ByteLength:()=>ro,nodeStackLineParser:()=>Xn,opera10StackLineParser:()=>qn,opera11StackLineParser:()=>Wn,resolveExceptionStepsConfig:()=>ur,reverseAndStripFrames:()=>Yn,stripReservedExceptionStepFields:()=>As,winjsStackLineParser:()=>Kn});var lt,Hn,pt;function Gn(r){let e=globalThis._posthogChunkIds;if(!e)return;let t=Object.keys(e);return pt&&t.length===Hn||(Hn=t.length,pt=t.reduce((n,o)=>{lt||(lt={});let i=lt[o];if(i)n[i[0]]=i[1];else{let s=r(o);for(let a=s.length-1;a>=0;a--){let c=s[a]?.filename,l=e[o];if(c&&l){n[c]=l,lt[o]=[c,l];break}}}return n},{})),pt}var ds=4,Te=class{constructor(e,t,n=[]){this.coercers=e,this.stackParser=t,this.modifiers=n}buildFromUnknown(e,t={}){let o=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(o,t,0).apply(e),a=this.buildParsingContext(t),u=this.parseStacktrace(s,a);return{$exception_list:this.convertToExceptionList(u,o),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&Z(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let n;e.cause!=null&&(n=this.parseStacktrace(e.cause,t));let o;return e.stack!=""&&e.stack!=null&&(o=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:n,stack:o}}applyChunkIds(e,t){return e.map(n=>(n.filename&&t&&(n.chunk_id=t[n.filename]),n))}applyCoercers(e,t){for(let n of this.coercers)if(n.match(e))return n.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let n of this.modifiers)t=await n(t);return t}convertToExceptionList(e,t){let n={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(n.stacktrace={type:"raw",frames:e.stack});let o=[n];return e.cause!=null&&o.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),o}buildParsingContext(e){return{chunkIdMap:Gn(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,n=0){let o=(s,a)=>{if(a<=ds){let u=this.buildCoercingContext(e,t,a);return this.applyCoercers(s,u)}};return{...t,syntheticException:n==0?t.syntheticException:void 0,mechanism:e,apply:s=>o(s,n),next:s=>o(s,n+1)}}};var F="?";function D(r,e,t,n,o){let i={platform:r,filename:e,function:t==="<anonymous>"?F:t,in_app:!0};return ee(n)||(i.lineno=n),ee(o)||(i.colno=o),i}var ft=(r,e)=>{let t=r.indexOf("safari-extension")!==-1,n=r.indexOf("safari-web-extension")!==-1;return t||n?[r.indexOf("@")!==-1?r.split("@")[0]:F,t?`safari-extension:${e}`:`safari-web-extension:${e}`]:[r,e]};var hs=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gs=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ms=/\((\S*)(?::(\d+))(?::(\d+))\)/,tr=(r,e)=>{let t=hs.exec(r);if(t){let[,o,i,s]=t;return D(e,o,F,+i,+s)}let n=gs.exec(r);if(n){if(n[2]&&n[2].indexOf("eval")===0){let a=ms.exec(n[2]);a&&(n[2]=a[1],n[3]=a[2],n[4]=a[3])}let[i,s]=ft(n[1]||F,n[2]);return D(e,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}};var _s=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ys=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,rr=(r,e)=>{let t=_s.exec(r);if(t){if(t[3]&&t[3].indexOf(" > eval")>-1){let s=ys.exec(t[3]);s&&(t[1]=t[1]||"eval",t[3]=s[1],t[4]=s[2],t[5]="")}let o=t[3],i=t[1]||F;return[i,o]=ft(i,o),D(e,o,i,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}};var vs=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,Kn=(r,e)=>{let t=vs.exec(r);return t?D(e,t[2],t[1]||F,+t[3],t[4]?+t[4]:void 0):void 0};var bs=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,qn=(r,e)=>{let t=bs.exec(r);return t?D(e,t[2],t[3]||F,+t[1]):void 0},xs=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,Wn=(r,e)=>{let t=xs.exec(r);return t?D(e,t[5],t[3]||t[4]||F,+t[1],+t[2]):void 0};var ws=/^\s*[-]{4,}$/,Ps=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,Es=/^Promise\.(?:all|any)$/,$s=/^index \d+$/,Fs="node:internal/promise",Xn=(r,e)=>{let t=r.match(Ps);if(t){let n,o,i,s,a;if(t[1]){i=t[1];let l=i.lastIndexOf(".");if(i[l-1]==="."&&l--,l>0){n=i.slice(0,l),o=i.slice(l+1);let p=n.indexOf(".Module");p>0&&(i=i.slice(p+1),n=n.slice(0,p))}s=void 0}o&&(s=n,a=o),o==="<anonymous>"&&(a=void 0,i=void 0),i===void 0&&(a=a||F,i=s?`${s}.${a}`:a);let u=t[2]?.startsWith("file://")?t[2].slice(7):t[2],c=t[5]==="native";return u?.match(/\/[A-Z]:/)&&(u=u.slice(1)),!u&&t[5]&&!c&&(u=t[5]),Es.test(i)&&$s.test(u||"")&&(u=Fs),{filename:u?decodeURI(u):void 0,module:void 0,function:i,lineno:Vn(t[3]),colno:Vn(t[4]),in_app:Ss(u||"",c),platform:e}}if(r.match(ws))return{filename:r,platform:e}};function Ss(r,e=!1){return!(e||r&&!r.startsWith("/")&&!r.match(/^[A-Z]:/)&&!r.startsWith(".")&&!r.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&r!==void 0&&!r.includes("node_modules/")}function Vn(r){return parseInt(r||"",10)||void 0}var Qn=/\(error: (.*)\)/,Jn=50;function Yn(r){if(!r.length)return[];let e=Array.from(r);return e.reverse(),e.slice(0,Jn).map(t=>({...t,filename:t.filename||Is(e).filename,function:t.function||F}))}function Is(r){return r[r.length-1]||{}}function nr(){return eo("web:javascript",tr,rr)}function eo(r,...e){return(t,n=0)=>{let o=[],i=t.split(`
|
|
2
|
+
`);for(let s=n;s<i.length;s++){let a=i[s];if(a.length>1024)continue;let u=Qn.test(a)?a.replace(Qn,"$1"):a;if(!u.match(/\S*Error: /)){for(let c of e){let l=c(u,r);if(l){o.push(l);break}}if(o.length>=Jn)break}}return Yn(o)}}var or=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let n=H(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:n?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return te(e,"DOMException")}isDOMError(e){return te(e,"DOMError")}};var Oe=class{match(e){return xn(e)}coerce(e,t){return{type:this.getType(e),value:this.getMessage(e,t),stack:this.getStack(e),cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let n=e.message;return n.error&&typeof n.error.message=="string"?String(n.error.message):String(n)}getStack(e){return e.stacktrace||e.stack||void 0}};var ir=class{constructor(){}match(e){return wn(e)&&e.error!=null}coerce(e,t){let n=t.apply(e.error);return n||{type:"ErrorEvent",value:e.message,stack:t.syntheticException?.stack,synthetic:!0}}};var zs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,Me=class{match(e){return typeof e=="string"}coerce(e,t){let[n,o]=this.getInfos(e);return{type:n??"Error",value:o??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",n=e,o=e.match(zs);return o&&(t=o[1],n=o[2]),[t,n]}};var to=["fatal","error","warning","log","info","debug"];function dt(r,e=40){let t=Object.keys(r);if(t.sort(),!t.length)return"[object has no keys]";for(let n=t.length;n>0;n--){let o=t.slice(0,n).join(", ");if(!(o.length>e))return n===t.length||o.length<=e?o:`${o.slice(0,e)}...`}return""}var Ne=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){let n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{type:this.getType(e),value:this.getValue(e),stack:t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return ue(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let o=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(o+=` with message: '${e.message}'`),o}if("message"in e&&typeof e.message=="string")return e.message;let t=this.getObjectClassName(e),n=dt(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${n}`}isSeverityLevel(e){return H(e)&&!yn(e)&&to.indexOf(e)>=0}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let n=e[t];if(Un(n))return n}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}};var sr=class{match(e){return ue(e)}coerce(e,t){let n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${dt(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var Le=class{match(e){return Je(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}};var ar=class{match(e){return te(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ue(e))return!1;try{let t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){let n=this.getUnhandledRejectionReason(e);return Je(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var cr=class{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(t!==void 0)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}};var Ze={MESSAGE:"$message",TIMESTAMP:"$timestamp"},Cs=new Set([Ze.MESSAGE,Ze.TIMESTAMP]),ht={enabled:!0,max_bytes:32768};function ur(r){return r?{enabled:r.enabled??ht.enabled,max_bytes:ks(r.max_bytes,ht.max_bytes)}:{...ht}}function As(r){if(!r)return{sanitizedProperties:{},droppedKeys:[]};let e=[];return{sanitizedProperties:Object.keys(r).reduce((n,o)=>Cs.has(o)?(e.push(o),n):(n[o]=r[o],n),{}),droppedKeys:e}}var lr=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=ur(e)}setConfig(e){this._config=ur(e),this._trimToMaxBytes()}add(e){let t=Rs(e);if(!t)return;let n=ro(t.json);n>this._config.max_bytes||(this._entries.push({step:t.step,bytes:n}),this._totalBytes+=n,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function ks(r,e){if(!Ie(r)||r===1/0||r===-1/0)return e;let t=Math.floor(r);return t<0?e:t}function Rs(r){let e;try{e=ce(r)}catch{return}try{let t=JSON.parse(e);if(!Se(t))return;let n=t,o=n[Ze.MESSAGE],i=n[Ze.TIMESTAMP];return!H(o)||o.trim().length===0||!H(i)&&!Ie(i)?void 0:{step:n,json:e}}catch{return}}function ro(r){if(typeof TextEncoder<"u")return new TextEncoder().encode(r).length;let e=encodeURIComponent(r),t=0;for(let n=0;n<e.length;n++)e[n]==="%"?(t+=1,n+=2):t+=1;return t}var G=class extends Error{constructor(e,t){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}},X=class extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}};var io=(r,e)=>{for(let t of Object.keys(e))(t.startsWith("$feature/")||t==="$active_feature_flags")&&(r[t]=e[t])};async function no(r){if(r instanceof G){let e="";try{e=await r.text}catch{}console.error(`Error while flushing PostHog: message=${r.message}, response body=${e}`,r)}else console.error("Error while flushing PostHog",r);return Promise.resolve()}function Ts(r){return typeof r=="object"&&(r instanceof G||so(r))}function so(r){return r instanceof X}function Os(r){if(r instanceof G)return r.status===502||r.status===504;if(!(r instanceof X))return!1;let e=r.error;return(e?.code??e?.cause?.code)!=="ECONNREFUSED"}function fe(r){return typeof r=="object"&&r instanceof G&&r.status===413}function De(r){return r instanceof G?r.status===408||r.status===429||r.status>=500:so(r)}function oo(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var pr="default",Ue=class{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new Te([new Oe,new Ne,new Me,new Le],nr())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new rt,this._events=new ut,this._isInitialized=!1;let n=typeof e=="string"?e.trim():"",o=typeof t.host=="string"?t.host.trim():"",i=!n;this._logger=Sn("[PostHog]",this.logMsgIfDebug.bind(this)),i&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=n,this.host=Zn(o||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:De},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||i,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!Ut()||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return e();this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(A.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(A.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(A.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let t=this.on("*",(n,o)=>this._logger.info(n,o));this.removeDebugCallback=()=>{t(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},n={...t,...this.getCommonEventProperties()};return io(n,t),e.event==="$feature_flag_called"&&n.$feature_flag_has_experiment===!1&&this.isMinimalFlagCalledEventsEnabled()&&(n=$e(n)),{distinct_id:e.distinct_id,event:e.event,properties:n}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,n){this.wrap(()=>{let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",o,n)})}async identifyStatelessImmediate(e,t,n){let o={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",o,n)}captureStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({distinct_id:e,event:t,properties:n});this.enqueue("capture",i,o)})}async captureStatelessImmediate(e,t,n,o){let i=this.buildPayload({distinct_id:e,event:t,properties:n});await this.sendImmediate("capture",i,o)}aliasStateless(e,t,n,o){this.wrap(()=>{let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});this.enqueue("alias",i,o)})}async aliasStatelessImmediate(e,t,n,o){let i=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...n||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",i,o)}groupIdentifyStateless(e,t,n,o,i,s){this.wrap(()=>{let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});this.enqueue("capture",a,o)})}async groupIdentifyStatelessImmediate(e,t,n,o,i,s){let a=this.buildPayload({distinct_id:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{},...s||{}}});await this.sendImmediate("capture",a,o)}async getRemoteConfig(){await this._initPromise;let e=this.host;e==="https://us.i.posthog.com"?e="https://us-assets.i.posthog.com":e==="https://eu.i.posthog.com"&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,n,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(o=>o.json()).catch(o=>{this._logger.error("Remote config could not be loaded",o),this._events.emit("error",o)})}async getFlags(e,t={},n={},o={},i={},s=!1){await this._initPromise;let a=s?"&config=true":"",u=`${this.host}/flags/?v=2${a}`,c={token:this.apiKey,distinct_id:e,groups:t,person_properties:n,group_properties:o,...i};n.$device_id&&(c.$device_id=n.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(c.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(c)};return this._logger.info("Flags URL",u),this.fetchWithRetry(u,l,{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:Os},this.featureFlagsRequestTimeoutMs).then(p=>p.json()).then(p=>({success:!0,response:Dt(p)})).catch(p=>(this._events.emit("error",p),{success:!1,error:this.categorizeRequestError(p)}))}categorizeRequestError(e){if(e instanceof G)return{type:"api_error",statusCode:e.status};if(e instanceof X){let t=e.error;return t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailStateless(e,t,n,o,i,s);if(a===void 0)return{response:void 0,requestId:void 0};let u=Ee(a.response);return u===void 0&&(u=!1),{response:u,requestId:a.requestId}}async getFeatureFlagDetailStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(t,n,o,i,s,[e]);return a===void 0?void 0:{response:a.flags[e],requestId:a.requestId,evaluatedAt:a.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,n={},o={},i={},s){await this._initPromise;let a=await this.getFeatureFlagPayloadsStateless(t,n,o,i,s,[e]);if(!a)return;let u=a[e];return u===void 0?null:u}async getFeatureFlagPayloadsStateless(e,t={},n={},o={},i,s){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)).payloads}async getFeatureFlagsStateless(e,t={},n={},o={},i,s){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,n,o,i,s)}async getFeatureFlagsAndPayloadsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a=await this.getFeatureFlagDetailsStateless(e,t,n,o,i,s);return a?{flags:a.featureFlags,payloads:a.featureFlagPayloads,requestId:a.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},n={},o={},i,s){await this._initPromise;let a={geoip_disable:i??this.disableGeoip};s&&(a.flag_keys_to_evaluate=s);let u=await this.getFlags(e,t,n,o,a);if(!u.success)return;let c=u.response;return c.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"),c.quotaLimited?.includes("feature_flags")?(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"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:c?.requestId,quotaLimited:c.quotaLimited}):c}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},o=(await this.fetchWithRetry(e,t).then(i=>{if(i.status!==200||!i.json){let s=`Surveys API could not be loaded: ${i.status}`,a=new Error(s);this._logger.error(a),this._events.emit("error",new Error(s));return}return i.json()}).catch(i=>{this._logger.error("Surveys API could not be loaded",i),this._events.emit("error",i)}))?.surveys;return o&&this._logger.info("Surveys fetched from API: ",JSON.stringify(o)),o??[]}get props(){return this._props||(this._props=this.getPersistedProperty(A.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(A.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(A.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return pr}persistedQueueKeyForRoute(e){return A.Queue}getActiveQueueRoutes(){return[pr]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,n){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o===null)return;o=this.normalizeMessage(o);let i=this.persistedQueueKeyForRoute(this.getQueueRouteKey(o)),s=this.getPersistedProperty(i)||[];s.length>=this.maxQueueSize&&(s.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),s.push({message:o}),this.setPersistedProperty(i,s),this._events.emit(e,o),s.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=I(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,n){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let o=this.prepareMessage(t,n);if(o=this.processBeforeEnqueue(o),o!==null){o=this.normalizeMessage(o);try{await this.sendBatch([o],void 0,this.getQueueRouteKey(o))}catch(i){this._events.emit("error",i)}}}normalizeMessage(e){let{type:t,library:n,library_version:o,...i}=e,s=oo(i.properties)?i.properties:void 0;return n!==void 0&&s?.$lib===void 0&&(s={...s||{},$lib:n}),o!==void 0&&s?.$lib_version===void 0&&(s={...s||{},$lib_version:o}),s&&(i.properties=s),i.uuid=at(i.uuid,k),i}prepareMessage(e,t){let n={...e,timestamp:t?.timestamp?t?.timestamp:Wt(),uuid:at(t?.uuid,k)};return(t?.disableGeoip??this.disableGeoip)&&(oo(n.properties)||(n.properties={}),n.properties.$geoip_disable=!0),n.distinctId&&(n.distinct_id=n.distinctId,delete n.distinctId),n}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await no(e)})}async waitForPendingPromises(e,t=[]){let n=t.filter(i=>!!i),o=0;for(;;){let i=this.promiseQueue.getPromises([...n,...this.flushPromises],e);if(i.length===0)return;o>0&&this._logger.debug(`flush() re-checking ${i.length} pending promise(s) before flushing`),await Promise.all(i.map(s=>s.catch(()=>{}))),o++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,n=this.promiseQueue.maxId,o=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(n,[t,o])}).then(()=>Vt([t])).then(()=>(this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=o,this.flushPromise=o,this.flushPromises.add(o),this.addPendingPromise(o),Vt([o]).then(()=>{this.flushPromises.delete(o),this.pendingFlushPromise===o&&(this.pendingFlushPromise=null),this.flushPromise===o&&(this.flushPromise=null)}),o}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&e!==""&&(t["User-Agent"]=e),t}async sendBatch(e,t,n=pr){let o={api_key:this.apiKey,batch:e,sent_at:Wt()};this.historicalMigration&&(o.historical_migration=!0);let i=ce(o),s=`${this.host}/batch/`,a=this.disableCompression?null:await Y(i,this.isDebug),u={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...a!==null&&{"Content-Encoding":"gzip"}},body:a||i};await(await this.fetchWithRetry(s,u,t)).body?.cancel()?.catch(()=>{})}async _flush(){this.clearFlushTimer(),await this._initPromise;let e=this.getActiveQueueRoutes();if(!e.some(o=>this.getRouteQueue(o).length>0))return;let t=[],n;for(let o of e)try{await this._flushRoute(o,t)}catch(i){n===void 0&&(n=i)}if(n!==void 0)throw n;this._events.emit("flush",t)}async _flushRoute(e,t){let n=this.persistedQueueKeyForRoute(e),o=this.getPersistedProperty(n)||[];if(!o.length)return;let i=o.length,s=0;for(;o.length>0&&s<i;){let a=o.slice(0,this.maxBatchSize),u=a.map(p=>p.message===void 0?p.message:this.normalizeMessage(p.message)),c=async()=>{let f=(this.getPersistedProperty(n)||[]).slice(a.length);this.setPersistedProperty(n,f),o=f,this._dequeuedMessagesCount+=a.length,await this.flushStorage()},l={retryCheck:p=>fe(p)?!1:De(p)};try{await this.sendBatch(u,l,e)}catch(p){if(fe(p)&&u.length>1){this.maxBatchSize=Math.max(1,Math.floor(u.length/2)),this._logger.warn(`Received 413 when sending batch of size ${u.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw p instanceof X||await c(),this._events.emit("error",p),p}await c(),t.push(...u),s+=u.length}}async _sendLogsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await Y(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>fe(s)?!1:De(s)}),{kind:"ok"}}catch(s){return fe(s)?{kind:"too-large"}:s instanceof X?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async _sendMetricsBatch(e){if(this.disabled)return{kind:"fatal",error:new Error("The client is disabled")};let t=JSON.stringify(e),n=`${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`,o=this.disableCompression?null:await Y(t,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...o!==null&&{"Content-Encoding":"gzip"}},body:o||t};try{return await this.fetchWithRetry(n,i,{retryCheck:s=>fe(s)?!1:De(s)}),{kind:"ok"}}catch(s){return fe(s)?{kind:"too-large"}:De(s)?{kind:"retry-later",error:s}:{kind:"fatal",error:s}}}async fetchWithRetry(e,t,n,o){let i=t.body?t.body:"",s=-1;try{s=i instanceof Blob?i.size:Buffer.byteLength(i,Ln)}catch{i instanceof Blob?s=i.size:s=new TextEncoder().encode(i).length}return await Dn(async()=>{let a=new AbortController,u=o??this.requestTimeout,c=I(()=>a.abort(),u),l=null;try{l=await this.fetch(e,{signal:a.signal,...t})}catch(f){throw new X(f)}finally{clearTimeout(c)}if(!(t.mode==="no-cors")&&(l.status<200||l.status>=400))throw new G(l,s);return l},{...this._retryOptions,...n})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),this.disabled)return;let n=async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let s=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===s){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(i){if(!Ts(i))throw i;await no(i)}},o;try{return await Promise.race([new Promise((i,s)=>{o=I(()=>{this._logger.error("Timed out while shutting down PostHog"),t=!0,s("Timeout while shutting down PostHog. Some events may not have been sent.")},e)}),n()])}finally{clearTimeout(o)}}async shutdown(e=3e4){return 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"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}};var uo=require("fs"),lo=require("readline"),gt=new C.ReduceableCache(25),po=new C.ReduceableCache(20),fr=7,Ds=1e3,Us=1e4;async function fo(r){let e={};for(let o=r.length-1;o>=0;o--){let i=r[o],s=i?.filename;if(!i||typeof s!="string"||typeof i.lineno!="number"||Gs(s)||Ks(i))continue;e[s]||(e[s]=[]),e[s].push(i.lineno)}let t=Object.keys(e);if(t.length==0)return r;let n=[];for(let o of t){if(po.get(o))continue;let i=e[o];if(!i)continue;i.sort((u,c)=>u-c);let s=Ws(i);if(s.every(u=>qs(o,u)))continue;let a=Vs(gt,o,{});n.push(js(o,s,a))}return await Promise.all(n).catch(()=>{}),r&&r.length>0&&Bs(r,gt),gt.reduce(),r}function js(r,e,t){return new Promise(n=>{let o=(0,uo.createReadStream)(r),i=(0,lo.createInterface)({input:o});function s(){o.destroy(),n()}let a=0,u=0,c=e[u];if(c===void 0)return void s();let l=c[0],p=c[1];function f(){po.set(r,1),i.close(),i.removeAllListeners(),s()}o.on("error",f),i.on("error",f),i.on("close",s),i.on("line",d=>{if(a++,!(a<l)&&(t[a]=Xs(d,0),a>=p)){if(u===e.length-1){i.close(),i.removeAllListeners();return}u++;let h=e[u];if(h===void 0){i.close(),i.removeAllListeners();return}l=h[0],p=h[1]}})})}function Bs(r,e){for(let t of r)if(t.filename&&t.context_line===void 0&&typeof t.lineno=="number"){let n=e.get(t.filename);if(n===void 0)continue;Hs(t.lineno,t,n)}}function Hs(r,e,t){if(e.lineno===void 0||t===void 0)return;e.pre_context=[];for(let o=ho(r);o<r;o++){let i=t[o];if(i===void 0)return void ao(e);e.pre_context.push(i)}if(t[r]===void 0)return void ao(e);e.context_line=t[r];let n=go(r);e.post_context=[];for(let o=r+1;o<=n;o++){let i=t[o];if(i===void 0)break;e.post_context.push(i)}}function ao(r){delete r.pre_context,delete r.context_line,delete r.post_context}function Gs(r){return r.startsWith("node:")||r.endsWith(".min.js")||r.endsWith(".min.cjs")||r.endsWith(".min.mjs")||r.startsWith("data:")}function Ks(r){return r.lineno!==void 0&&r.lineno>Us||r.colno!==void 0&&r.colno>Ds}function qs(r,e){let t=gt.get(r);if(t===void 0)return!1;for(let n=e[0];n<=e[1];n++)if(t[n]===void 0)return!1;return!0}function Ws(r){if(!r.length)return[];let e=0,t=r[0];if(typeof t!="number")return[];let n=co(t),o=[];for(;;){if(e===r.length-1){o.push(n);break}let i=r[e+1];if(typeof i!="number")break;i<=n[1]?n[1]=i+fr:(o.push(n),n=co(i)),e++}return o}function co(r){return[ho(r),go(r)]}function ho(r){return Math.max(1,r-fr)}function go(r){return r+fr}function Vs(r,e,t){let n=r.get(e);return n===void 0?(r.set(e,t),t):n}function Xs(r,e){let t=r,n=t.length;if(n<=150)return t;e>n&&(e=n);let o=Math.max(e-60,0);o<5&&(o=0);let i=Math.min(o+140,n);return i>n-5&&(i=n),i===n&&(o=Math.max(i-140,0)),t=t.slice(o,i),o>0&&(t=`...${t}`),i<n&&(t+="..."),t}var de=require("path");function mo(r=process.cwd()){let e=de.sep==="\\",t=o=>e?o.replace(/\\/g,"/"):o,n=t(r);return async o=>{for(let i of o)!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:")||(0,de.isAbsolute)(i.filename)&&(i.filename=t((0,de.relative)(n,t(i.filename))));return o}}var _o="5.46.1";var K={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};var re=class r{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e){let t=this._flags[e];return this._recordAccess(e),t?.enabled??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),!!t)return t.enabled?t.variant??!0:!1}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let n=this._flags[t];n&&(e[t]=n)}return this._cloneWith(e)}only(e){let t={},n=[];for(let o of e){let i=this._flags[o];i?t[o]=i:n.push(o)}return n.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${n.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[n,o]of Object.entries(this._flags)){let i=o.enabled===!1?!1:o.variant??!0;e[`$feature/${n}`]=i,o.enabled&&t.push(n)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new r({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),this._distinctId===""||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],n=t===void 0?void 0:t.enabled===!1?!1:t.variant??!0,o={$feature_flag:e,$feature_flag_response:n,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:n,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(o.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&this._flagDefinitionsLoadedAt!==void 0&&(o.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let i=[];this._errorsWhileComputing&&i.push(K.ERRORS_WHILE_COMPUTING),this._quotaLimited&&i.push(K.QUOTA_LIMITED),t===void 0&&i.push(K.FLAG_MISSING),i.length>0&&(o.$feature_flag_error=i.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:n,groups:this._groups,disableGeoip:this._disableGeoip,properties:o})}};async function yo(r){let e=globalThis.crypto?.subtle;if(!e)throw new Error("SubtleCrypto API not available");let t=await e.digest("SHA-1",new TextEncoder().encode(r));return Array.from(new Uint8Array(t)).map(o=>o.toString(16).padStart(2,"0")).join("")}var Qs=6e4,Js=1152921504606847e3,Ys=["is_not","is_set"],he=class r extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,r.prototype)}};function wo(r,e){r.name=e.name,Error.captureStackTrace(r,e),Object.setPrototypeOf(r,e.prototype)}var m=class r extends Error{constructor(e){super(e),wo(this,r)}},U=class r extends Error{constructor(e){super(e),wo(this,r)}},mt=class{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:n,timeout:o,host:i,customHeaders:s,...a}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=o,this.projectApiKey=n,this.host=i,this.poller=void 0,this.fetch=a.fetch||fetch,this.onError=a.onError,this.customHeaders=s,this.onLoad=a.onLoad,this.onMinimalFlagCalledEvents=a.onMinimalFlagCalledEvents,this.cacheProvider=a.cacheProvider,this.strictLocalEvaluation=a.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},n={},o={},i={}){return{distinctId:e,groups:t,personProperties:n,groupProperties:o,evaluationCache:i}}async getFeatureFlag(e,t,n={},o={},i={}){await this.loadFeatureFlags();let s,a;if(!this.loadedSuccessfullyOnce)return s;if(a=this.featureFlagsByKey[e],a!==void 0){let u=this.createEvaluationContext(t,n,o,i);try{s=(await this.computeFlagAndPayloadLocally(a,u)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${s}`))}catch(c){c instanceof U||c instanceof m?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${e}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${e}: ${c}`))}}return s}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let n={},o={},i=this.featureFlags.length==0,s=t?t.map(u=>this.featureFlagsByKey[u]).filter(Boolean):this.featureFlags,a={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(s.map(async u=>{try{let{value:c,payload:l}=await this.computeFlagAndPayloadLocally(u,a);n[u.key]=c,l&&(o[u.key]=l)}catch(c){c instanceof U||c instanceof m?this.logMsgIfDebug(()=>console.debug(`${c.name} when computing flag locally: ${u.key}: ${c.message}`)):c instanceof Error&&this.onError?.(new Error(`Error computing flag locally: ${u.key}: ${c}`)),i=!0}})),{response:n,payloads:o,fallbackToFlags:i}}async computeFlagAndPayloadLocally(e,t,n={}){let{matchValue:o,skipLoadCheck:i=!1}=n;if(i||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let s;s=o!==void 0?o:await this.computeFlagValueLocally(e,t);let a=this.getFeatureFlagPayload(e.key,s);return{value:s,payload:a}}async computeFlagValueLocally(e,t){let{distinctId:n,groups:o,personProperties:i,groupProperties:s}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new m("Flag has experience continuity enabled");let u=(e.filters||{}).aggregation_group_type_index;if(u!=null){let c=this.groupTypeMapping[String(u)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${u} for feature flag ${e.key}`)),new m("Flag has unknown group type index");if(!(c in o))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;e.bucketing_identifier==="device_id"&&(i?.$device_id===void 0||i?.$device_id===null||i?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let l=s[c];return await this.matchFeatureFlagProperties(e,o[c],l,t)}{let c=this.getBucketingValueForFlag(e,n,i);if(c===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new m(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,c,i,t)}}getBucketingValueForFlag(e,t,n){if(e.filters?.aggregation_group_type_index!=null)return t;if(e.bucketing_identifier==="device_id"){let o=n?.$device_id;return o==null||o===""?void 0:o}return t}getFeatureFlagPayload(e,t){let n=null;if(t!==!1&&t!=null&&(typeof t=="boolean"?n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:typeof t=="string"&&(n=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),n!=null)){if(typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}return null}async evaluateFlagDependency(e,t,n){let{evaluationCache:o}=n,i=e.key;if(!this.featureFlagsByKey)throw new m("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new m(`Flag dependency property for '${i}' is missing required 'dependency_chain' field`);let s=e.dependency_chain;if(!Array.isArray(s))throw new m(`Flag dependency property for '${i}' has an invalid 'dependency_chain' (expected array, got ${typeof s})`);if(s.length===0)throw new m(`Circular dependency detected for flag '${i}' (empty dependency chain)`);for(let u of s){if(!(u in o)){let l=this.featureFlagsByKey[u];if(l)if(l.active)try{let p=await this.computeFlagValueLocally(l,n);o[u]=p}catch(p){throw new m(`Error evaluating flag dependency '${u}' for flag '${i}': ${p}`)}else o[u]=!1;else throw new m(`Missing flag dependency '${u}' for flag '${i}'`)}if(o[u]==null)throw new m(`Dependency '${u}' could not be evaluated`)}let a=o[i];return this.flagEvaluatesToExpectedValue(e.value,a)}flagEvaluatesToExpectedValue(e,t){return typeof e=="boolean"?e===t||typeof t=="string"&&t!==""&&e===!0:typeof e=="string"?t===e:!1}async matchFeatureFlagProperties(e,t,n,o){let i=e.filters||{},s=i.groups||[],a=i.aggregation_group_type_index,u=i.early_exit??!1,{groups:c,groupProperties:l}=o,p=!1,f;for(let d of s)try{let h=d.aggregation_group_type_index!==void 0?d.aggregation_group_type_index:a,y=n,E=t;if(h!==a&&h!=null){let x=this.groupTypeMapping[String(h)];if(!x||!(x in c)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${h} not available`));continue}if(!(x in l)){p=!0;continue}y=l[x],E=c[x]}let _=await this.isConditionMatch(e,E,d,y,o);if(_==="match"){let x=d.variant,M=i.multivariate?.variants||[];f=x&&M.some(R=>R.key===x)?x:await this.getMatchingVariant(e,E)||!0;break}if(u&&_==="out_of_rollout_bound")return!1}catch(h){if(h instanceof U)throw h;if(h instanceof m)p=!0;else throw h}if(f!==void 0)return f;if(p)throw new m("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,n,o,i){let s=n.rollout_percentage,a=u=>{this.logMsgIfDebug(()=>console.warn(u))};if((n.properties||[]).length>0){for(let u of n.properties){let c=u.type,l=!1;if(c==="cohort"){let p=await Eo(u,o,this.cohorts,this.debugMode,f=>this.evaluateFlagDependency(f,o,i));l=u.operator==="not_in"?!p:p}else l=c==="flag"?await this.evaluateFlagDependency(u,o,i):Po(u,o,a);if(!l)return"no_match"}if(s==null)return"match"}return s!=null&&await vo(e.key,t)>s/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let n=await vo(e.key,t,"variant"),o=this.variantLookupTable(e).find(i=>n>=i.valueMin&&n<i.valueMax);if(o)return o.key}variantLookupTable(e){let t=[],n=0,o=0;return((e.filters||{}).multivariate?.variants||[]).forEach(a=>{o=n+a.rollout_percentage/100,t.push({valueMin:n,valueMax:o,key:a.key}),n=o}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((t,n)=>(t[n.key]=n,t),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(e.minimalFlagCalledEvents===!0)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(n=>n.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(n=>n.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).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();return t?(this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0):!1}catch(t){return this.onError?.(new Error(`Failed to load from cache: ${t}`)),!1}}async loadFeatureFlags(e=!1){if(!(this.loadedSuccessfullyOnce&&!e))return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(t=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${t}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(Qs,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(n){this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${n}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new he(`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`);case 402: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"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new he(`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`);case 429:throw this.beginBackoff(),new he(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let n=await t.json()??{};if(!("flags"in n))return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(n)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let o={flags:n.flags??[],groupTypeMapping:n.group_type_mapping||{},cohorts:n.cohorts||{},minimalFlagCalledEvents:n.minimal_flag_called_events===!0};if(this.updateFlagState(o),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(o)}catch(i){this.onError?.(new Error(`Failed to store in cache: ${i}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(o.flags);break}default:return}}catch(e){e instanceof he&&this.onError?.(e)}}getPersonalApiKeyRequestOptions(e="GET",t){let n={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(n["If-None-Match"]=t),{method:e,headers:n}}_requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),n=null;if(this.timeout&&typeof this.timeout=="number"){let o=new AbortController;n=I(()=>{o.abort()},this.timeout),t.signal=o.signal}try{let o=this.fetch;return o(e,t)}finally{clearTimeout(n)}}async stopPoller(e=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Promise.race([t,new Promise((n,o)=>setTimeout(()=>o(new Error(`Cache shutdown timeout after ${e}ms`)),e))])}catch(t){this.onError?.(new Error(`Error during cache shutdown: ${t}`))}}};async function vo(r,e,t=""){let n=await yo(`${r}.${e}${t}`);return parseInt(n.slice(0,15),16)/Js}function Po(r,e,t){let n=r.key,o=r.value,i=r.operator||"exact";if(n in e){if(i==="is_not_set")return!1}else{if(i==="is_not_set")return!0;throw new m(`Property ${n} not found in propertyValues`)}let s=e[n];if(s==null&&!Ys.includes(i))return t&&t(`Property ${n} cannot have a value of null/undefined with the ${i} operator`),!1;function a(c,l){return Array.isArray(c)?c.map(p=>String(p).toLowerCase()).includes(String(l).toLowerCase()):String(c).toLowerCase()===String(l).toLowerCase()}function u(c,l,p){if(p==="gt")return c>l;if(p==="gte")return c>=l;if(p==="lt")return c<l;if(p==="lte")return c<=l;throw new Error(`Invalid operator: ${p}`)}switch(i){case"exact":return a(o,s);case"is_not":return!a(o,s);case"is_set":return n in e;case"icontains":return String(s).toLowerCase().includes(String(o).toLowerCase());case"not_icontains":return!String(s).toLowerCase().includes(String(o).toLowerCase());case"regex":return bo(String(o))&&String(s).match(String(o))!==null;case"not_regex":return bo(String(o))&&String(s).match(String(o))===null;case"gt":case"gte":case"lt":case"lte":{let c=typeof o=="number"?o:parseFloat(String(o)),l;return l=typeof s=="number"?s:s!=null?parseFloat(String(s)):NaN,Number.isFinite(c)&&Number.isFinite(l)?u(l,c,i):u(String(s),String(o),i)}case"is_date_after":case"is_date_before":{if(typeof o=="boolean")throw new m("Date operations cannot be performed on boolean values");let c=oa(String(o));if(c==null&&(c=xo(o)),c==null)throw new m(`Invalid date: ${o}`);let l=xo(s);return["is_date_before"].includes(i)?l<c:l>c}case"semver_eq":return O(S(String(s)),S(String(o)))===0;case"semver_neq":return O(S(String(s)),S(String(o)))!==0;case"semver_gt":return O(S(String(s)),S(String(o)))>0;case"semver_gte":return O(S(String(s)),S(String(o)))>=0;case"semver_lt":return O(S(String(s)),S(String(o)))<0;case"semver_lte":return O(S(String(s)),S(String(o)))<=0;case"semver_tilde":{let c=S(String(s)),{lower:l,upper:p}=ta(String(o));return O(c,l)>=0&&O(c,p)<0}case"semver_caret":{let c=S(String(s)),{lower:l,upper:p}=ra(String(o));return O(c,l)>=0&&O(c,p)<0}case"semver_wildcard":{let c=S(String(s)),{lower:l,upper:p}=na(String(o));return O(c,l)>=0&&O(c,p)<0}default:throw new m(`Unknown operator: ${i}`)}}function ea(r,e){if(!(r in e))throw new U(`cohort ${r} not found in local cohorts - likely a static cohort that requires server evaluation`)}async function Eo(r,e,t,n=!1,o){let i=String(r.value);ea(i,t);let s=t[i];return $o(s,e,t,n,o)}async function $o(r,e,t,n=!1,o){if(!r)return!0;let i=r.type,s=r.values;if(!s||s.length===0)return!0;let a=!1;if("values"in s[0]){for(let u of s)try{let c=await $o(u,e,t,n,o);if(i==="AND"){if(!c)return!1}else if(c)return!0}catch(c){if(c instanceof U)throw c;if(c instanceof m)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new m("Can't match cohort without a given cohort property value");return i==="AND"}for(let u of s)try{let c;if(u.type==="cohort")c=await Eo(u,e,t,n,o);else if(u.type==="flag"){if(!o)throw new m(`Flag dependency '${u.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);c=await o(u)}else c=Po(u,e);let l=u.negation||!1;if(i==="AND"){if(!c&&!l||c&&l)return!1}else if(c&&!l||!c&&l)return!0}catch(c){if(c instanceof U)throw c;if(c instanceof m)n&&console.debug(`Failed to compute property ${u} locally: ${c}`),a=!0;else throw c}if(a)throw new m("can't match cohort without a given cohort property value");return i==="AND"}function bo(r){try{return new RegExp(r),!0}catch{return!1}}function Fo(r,e){if(!/^\d+$/.test(r))throw new m(`Invalid semver: ${e}`);if(r.length>1&&r[0]==="0")throw new m(`Invalid semver: ${e}`);return parseInt(r,10)}function S(r){let t=String(r).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new m(`Invalid semver: ${r}`);let n=t.split("."),o=u=>u===void 0||u===""?0:Fo(u,r),i=o(n[0]),s=o(n[1]),a=o(n[2]);return[i,s,a]}function O(r,e){for(let t=0;t<3;t++){if(r[t]<e[t])return-1;if(r[t]>e[t])return 1}return 0}function ta(r){let e=S(r),t=[e[0],e[1],e[2]],n=[e[0],e[1]+1,0];return{lower:t,upper:n}}function ra(r){let e=S(r),[t,n,o]=e,i=[t,n,o],s;return s=t>0?[t+1,0,0]:n>0?[0,n+1,0]:[0,0,o+1],{lower:i,upper:s}}function na(r){let t=String(r).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!t)throw new m(`Invalid wildcard semver: ${r}`);let n=t.split("."),o=u=>{try{return Fo(u,r)}catch{throw new m(`Invalid wildcard semver: ${r}`)}},i=o(n[0]),s,a;if(n.length===1)s=[i,0,0],a=[i+1,0,0];else{let u=o(n[1]);s=[i,u,0],a=[i,u+1,0]}return{lower:s,upper:a}}function xo(r){if(r instanceof Date)return r;if(typeof r=="string"||typeof r=="number"){let e=new Date(r);if(!isNaN(e.valueOf()))return e;throw new m(`${r} is in an invalid date format`)}throw new m(`The date provided ${r} must be a string, number, or date object`)}function oa(r){let e=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,t=r.match(e),n=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let o=parseInt(t.groups.number);if(o>=1e4)return null;let i=t.groups.interval;if(i=="h")n.setUTCHours(n.getUTCHours()-o);else if(i=="d")n.setUTCDate(n.getUTCDate()-o);else if(i=="w")n.setUTCDate(n.getUTCDate()-7*o);else if(i=="m")n.setUTCMonth(n.getUTCMonth()-o);else{if(i!="y")return null;n.setUTCFullYear(n.getUTCFullYear()-o)}return n}}function ia(r,e){let t=!1;return Object.assign(n=>{let i=global.process.listeners("uncaughtException").filter(s=>s.name!=="domainUncaughtExceptionClear"&&s._posthogErrorHandler!==!0).length===0;r(n,{mechanism:{type:"onuncaughtexception",handled:!1}}),!t&&i&&(t=!0,e(n))},{_posthogErrorHandler:!0})}function So(r,e){globalThis.process?.on("uncaughtException",ia(r,e))}function Io(r){globalThis.process?.on("unhandledRejection",e=>r(e,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var sa=2e3,q=class r{constructor(e,t,n){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=n,this._rateLimiter=new Ye({...En(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return Se(e)&&"__posthog_previously_captured_error"in e&&e.__posthog_previously_captured_error===!0}static async buildEventMessage(e,t,n,o,i){let s={...i},a=e.buildFromUnknown(t,n);return a.$exception_list=await e.modifyFrames(a.$exception_list),{event:"$exception",distinctId:o,properties:{...a,...s},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(So(this.onException.bind(this),this.onFatalError.bind(this)),Io(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!r.isPreviouslyCapturedError(e)){let n=await r.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=n.properties?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(i)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:i}):this.client._capturePreparedEvent(n,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(sa),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};var _t=class{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=t!==null?t:void 0}constructor(){this._memoryStorage={}}};function aa(r){return r==="v0"||r==="v1"}function zo(){let r=typeof process<"u"?process.env?.POSTHOG_CAPTURE_MODE:void 0;return aa(r)?r:"v0"}var ca="$ai_",je="analytics";function Co(r){return typeof r.event=="string"&&r.event.startsWith(ca)}var ge=class r extends Error{constructor({requestId:e,drops:t,retryExhausted:n,cause:o}){super(r.buildMessage(e,t,n,o)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=n,this.cause=o}static buildMessage(e,t,n,o){let i=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${n.length} undelivered`;return o instanceof Error&&(i+=` (${o.message})`),i}};function dr(r){if(typeof r=="boolean")return r;if(typeof r=="number")return r!==0;if(typeof r=="string"){let e=r.trim().toLowerCase();if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1}}function ua(r){return typeof r=="string"?r:void 0}var la=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dr},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dr},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dr},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:ua}],pa=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function fa(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function da(r){if(typeof r=="string"){let t=new Date(r);return Number.isNaN(t.getTime())?new Date().toISOString():r}if(r instanceof Date)return Number.isNaN(r.getTime())?new Date().toISOString():r.toISOString();let e=r==null?new Date:new Date(r);return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString()}function Ao(r,e,t){t!==void 0&&!(e in r)&&(r[e]=t)}function ha(r){let t={...fa(r.properties)?r.properties:{}},n={};for(let{property:i,optionKey:s,coerce:a}of la)if(i in t){let u=a(t[i]);u!==void 0&&(n[s]=u),delete t[i]}let o={};for(let{property:i,field:s}of pa)if(i in t){let a=t[i];typeof a=="string"&&(o[s]=a),delete t[i]}return delete t.$lib,delete t.$lib_version,Ao(t,"$set",r.$set),Ao(t,"$set_once",r.$set_once),{event:String(r.event??""),uuid:String(r.uuid??""),distinct_id:String(r.distinct_id??""),timestamp:da(r.timestamp),...o,options:n,properties:t}}function ko(r,{createdAt:e,historicalMigration:t}){let n={created_at:e,batch:r.map(ha)};return t&&(n.historical_migration=!0),n}var ga="/i/v1/analytics/events",ma=3e4,_a=new Set([408,500,502,503,504]),yt=class{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??ma,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(n=>new Promise(o=>I(o,n))),this.generateRequestId=t.generateRequestId??k,this.compress=t.compress??Y}async sendV1Batch(e){if(e.length===0)return;let t=this.generateRequestId(),n=new Date(this.now()).toISOString(),{batch:o}=ko(e,{createdAt:n,historicalMigration:this.config.historicalMigration}),i=`${this.config.host}${ga}`,s=[],a=o,u=Math.max(1,this.config.maxAttempts);for(let c=1;c<=u;c++){let l=c===u,p=ce({created_at:n,...this.config.historicalMigration?{historical_migration:!0}:{},batch:a}),f;try{f=await this.sendOnce(i,p,c,t)}catch(_){if(l)return this.surfaceBatchFailure(t,s,a,_);await this.sleep(this.backoffDelay(c));continue}let{status:d}=f;if(d<200||d>=300){if(!l&&_a.has(d)){let x=this.parseRetryAfter(f);await this.cancelBody(f),await this.sleep(this.backoffDelay(c,x));continue}let _=await this.buildHttpError(f,d);return this.surfaceBatchFailure(t,s,a,_)}let h;try{h=await this.parseResponse(f)}catch{return this.surfaceBatchFailure(t,s,a,new Error(`Capture V1 returned an unparseable ${d} response body`))}let y=this.classify(a,h,s);if(y.length===0)return this.surfacePartialDrops(t,s);if(l)return void this.onError(new ge({requestId:t,drops:s,retryExhausted:y.map(_=>_.uuid)}));a=y;let E=this.parseRetryAfter(f);await this.sleep(this.backoffDelay(c,E))}}async sendOnce(e,t,n,o){let i=this.buildHeaders(n,o),s=t;if(this.config.compressionEnabled){let c=await this.compress(t,this.config.isDebug);c!==null&&(s=c,i["Content-Encoding"]="gzip")}let a=new AbortController,u=I(()=>a.abort(),this.config.requestTimeoutMs);try{return await this.fetchFn(e,{method:"POST",headers:i,body:s,signal:a.signal})}finally{clearTimeout(u)}}buildHeaders(e,t){let n=`${this.config.libraryId}/${this.config.libraryVersion}`,o={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":n,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(o["User-Agent"]=this.config.userAgent),o}classify(e,t,n){let o=t.results??{},i=[];for(let s of e){let a=o[s.uuid];a&&(a.result==="drop"?n.push({uuid:s.uuid,details:a.details??void 0}):a.result==="retry"&&i.push(s))}return i}backoffDelay(e,t){let n=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return t===void 0?n:Math.max(n,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let n=t.trim();if(/^\d+$/.test(n)){let s=parseInt(n,10);return Number.isFinite(s)&&s>0?1e3*s:void 0}let o=Date.parse(n);if(Number.isNaN(o))return;let i=o-this.now();return i>0?i:void 0}async parseResponse(e){let t=await e.text(),n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error("unexpected response shape");let o=n.results;if(o!==void 0&&(typeof o!="object"||o===null||Array.isArray(o)))throw new Error("unexpected results shape");return{results:o??{}}}async buildHttpError(e,t){let n="";try{n=(await e.text()).slice(0,512)}catch{}let o=n?`: ${n}`:"";return new Error(`Capture V1 request failed with HTTP ${t}${o}`)}surfaceBatchFailure(e,t,n,o){this.onError(new ge({requestId:e,drops:t,retryExhausted:n.map(i=>i.uuid),cause:o}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new ge({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){await e.body?.cancel()?.catch(()=>{})}};var ya=100,Ro=3e4,va=5e4,ba=50,xa=500,wa="https://us.i.posthog.com",To=new Set;function bt(r,e){To.has(r)||(To.add(r),console.warn(`[PostHog] ${e}`))}function Pa(r){return typeof r=="string"?r.trim():""}function Ea(r){return(typeof r=="string"?r.trim():"")||void 0}function $a(r){return(typeof r=="string"?r.trim():"")||wa}function Fa(r){return(Array.isArray(r)?r:[r]).filter(t=>typeof t=="string"&&t.trim().length>0)}function Sa(r){if(!r)return{};let e={};for(let[n,o]of Object.entries(r))e[`$feature/${n}`]=o;let t=Object.keys(r).filter(n=>r[n]!==!1).sort();return t.length>0&&(e.$active_feature_flags=t),e}var xt=class extends Ue{constructor(e,t={}){let n=Pa(e),o={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:$a(t.host),personalApiKey:Ea(t.secretKey??t.personalApiKey)};if(super(n,o),this._memoryStorage=new _t,this._minimalFlagCalledEvents=!1,this.options=o,this.captureMode=zo(),this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof o.featureFlagsPollingInterval=="number"?Math.max(o.featureFlagsPollingInterval,ya):Ro,typeof o.waitUntilDebounceMs=="number"&&(this.options.waitUntilDebounceMs=Math.max(o.waitUntilDebounceMs,0)),typeof o.waitUntilMaxWaitMs=="number"&&(this.options.waitUntilMaxWaitMs=Math.max(o.waitUntilMaxWaitMs,0)),!this.disabled&&o.personalApiKey){if(o.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.');o.enableLocalEvaluation!==!1&&(this.featureFlagsPoller=new mt({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:o.personalApiKey,projectApiKey:n,timeout:o.requestTimeout??1e4,host:this.host,fetch:o.fetch,onError:s=>{this._events.emit("error",s)},onLoad:s=>{this._events.emit("localEvaluationFlagsLoaded",s)},onMinimalFlagCalledEvents:s=>{this._minimalFlagCalledEvents=s},customHeaders:this.getCustomHeaders(),cacheProvider:o.flagDefinitionCacheProvider,strictLocalEvaluation:o.strictLocalEvaluation}))}this.errorTracking=new q(this,o,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=o.maxCacheSize||va}enqueue(e,t,n){super.enqueue(e,t,n),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let s,a=new Promise(u=>{s=u});try{e(a)}catch{return}this._waitUntilCycle={resolve:s,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,n=this.options.waitUntilMaxWaitMs??xa,o=t>=n;if(this._waitUntilCycle.timer!==void 0&&clearTimeout(this._waitUntilCycle.timer),o)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??ba;this._waitUntilCycle.timer=I(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){return this.captureMode==="v1"&&Co(e)?"ai":je}persistedQueueKeyForRoute(e){return e==="ai"?A.AiQueue:A.Queue}getActiveQueueRoutes(){return this.captureMode==="v1"?[je,"ai"]:[je]}async sendBatch(e,t,n=je){if(this.captureMode!=="v1"||n==="ai")return super.sendBatch(e,t,n);let o=e.filter(i=>i!==void 0);await this.getV1Sender().sendV1Batch(o)}getV1Sender(){return this._v1Sender||(this._v1Sender=new yt({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e)})),this._v1Sender}getLibraryVersion(){return _o}get metrics(){return this._metrics||(this._metrics=new Re(this,ct(this.options.metrics),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,n){typeof e=="string"&&this._logger.warn(t),e.event==="$exception"&&!e._originatedFromCaptureException&&this._logger.warn(n)}_sendPreparedEvent(e,t,n,o){return this.addPendingPromise(this._prepareEventMessage(t,o).then(({distinctId:i,event:s,properties:a,options:u})=>{let c={timestamp:u.timestamp,disableGeoip:u.disableGeoip,uuid:u.uuid},l={distinctId:i,event:s,properties:{...a,...this.getCommonEventProperties()}};return n?this.sendImmediate(e,l,c):this.enqueue(e,l,c)}).catch(i=>{i&&console.error(i)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"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."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"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."),this._capturePreparedEvent(e,!0)}identify({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:n}){let{$set:o,$set_once:i,$anon_distinct_id:s,...a}=t,l={$set:o||a,$set_once:i||{},$anon_distinct_id:s??void 0};await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:l,disableGeoip:n},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:n={}}){if(Object.keys(t).length===0&&Object.keys(n).length===0)return;let o={};Object.keys(t).length>0&&(o.$set=t),Object.keys(n).length>0&&(o.$set_once=n),this.capture({distinctId:e,event:"$set",properties:o})}unsetPersonProperties({distinctId:e,properties:t}){let n=Fa(t);n.length!==0&&this.capture({distinctId:e,event:"$set",properties:{$unset:n}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=Ro){return this.isLocalEvaluationReady()?!0:this.featureFlagsPoller===void 0?!1:new Promise(t=>{let n=setTimeout(()=>{o(),t(!1)},e),o=this._events.on("localEvaluationFlagsLoaded",i=>{clearTimeout(n),o(),t(i>0)})})}_resolveDistinctId(e,t){return typeof e=="string"?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,n={},o){if(this.disabled)return void this._logger.warn("The client is disabled");let i=n.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&e in this._flagOverrides){let g=this._flagOverrides[e];if(g===void 0)return;let w=this._payloadOverrides?.[e];return{key:e,enabled:g!==!1,variant:typeof g=="string"?g:void 0,payload:w}}let{groups:s,disableGeoip:a}=n,{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=n,p=this.addLocalPersonAndGroupProperties(t,s,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(t,s,this.personPropertiesForLocalEvaluation(t,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d,h=!1,y,E,_,x,M,R,b;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let g=this.featureFlagsPoller?.featureFlagsByKey[e];if(g)try{let w=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(g,f,{matchValue:o});if(w){h=!0;let $=w.value;x=g.id,R="Evaluated locally",b=g.has_experiment,d={key:e,enabled:$!==!1,variant:typeof $=="string"?$:void 0,payload:w.payload??void 0}}}catch(w){if(w instanceof U||w instanceof m)this._logger?.info(`${w.name} when computing flag locally: ${e}: ${w.message}`);else throw w}}if(!h&&!u){let g=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,l,a,[e]);if(g===void 0)_=K.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=g.minimalFlagCalledEvents===!0,y=g.requestId,E=g.evaluatedAt;let w=[];g.errorsWhileComputingFlags&&w.push(K.ERRORS_WHILE_COMPUTING),g.quotaLimited?.includes("feature_flags")&&w.push(K.QUOTA_LIMITED);let $=g.flags[e];if($===void 0)w.push(K.FLAG_MISSING);else{x=$.metadata?.id,M=$.metadata?.version,R=$.reason?.description??$.reason?.code,b=$.metadata?.has_experiment;let St;if($.metadata?.payload!==void 0)try{St=JSON.parse($.metadata.payload)}catch{St=$.metadata.payload}d={key:e,enabled:$.enabled,variant:$.variant,payload:St}}w.length>0&&(_=w.join(","))}}if(i){let g=d===void 0?void 0:d.enabled===!1?!1:d.variant??!0,w={$feature_flag:e,$feature_flag_response:g,$feature_flag_id:x,$feature_flag_version:M,$feature_flag_reason:R,locally_evaluated:h,[`$feature/${e}`]:g,$feature_flag_request_id:y,$feature_flag_evaluated_at:h?Date.now():E};if(b!==void 0&&(w.$feature_flag_has_experiment=b),h&&this.featureFlagsPoller){let $=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();$!==void 0&&(w.$feature_flag_definitions_loaded_at=$)}_&&(w.$feature_flag_error=_),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:g,groups:s,disableGeoip:a,properties:w})}return d!==void 0&&this._payloadOverrides!==void 0&&e in this._payloadOverrides&&(d={...d,payload:this._payloadOverrides[e]}),d}async getFeatureFlag(e,t,n){bt("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(o!==void 0)return o.enabled===!1?!1:o.variant??!0}async getFeatureFlagPayload(e,t,n,o){if(bt("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request."),this._payloadOverrides!==void 0&&e in this._payloadOverrides)return this._payloadOverrides[e];let i=await this._getFeatureFlagResult(e,t,{...o,sendFeatureFlagEvents:!1},n);if(i!==void 0)return i.payload??null}async getFeatureFlagResult(e,t,n){let{distinctId:o,options:i}=this._resolveDistinctId(t,n);return o?this._getFeatureFlagResult(e,o,{...i,sendFeatureFlagEvents:i?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw new Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let n=await t.json();if(typeof n=="string")try{return JSON.parse(n)}catch{}return n}async isFeatureEnabled(e,t,n){bt("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead \u2014 this consolidates flag evaluation into a single `/flags` request per incoming request.");let o=await this._getFeatureFlagResult(e,t,{...n,sendFeatureFlagEvents:n?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return o===void 0?void 0:o.enabled===!1?!1:!!(o.variant??!0)||!1}async getAllFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);return n?(await this.getAllFlagsAndPayloads(n,o)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},p=this.addLocalPersonAndGroupProperties(n,i,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,a),h={},y={},E=!0;if(d&&(h=d.response,y=d.payloads,E=d.fallbackToFlags),E&&!u){let _=await super.getFeatureFlagsAndPayloadsStateless(f.distinctId,f.groups,c,l,s,a);h={...h,..._.flags||{}},y={...y,..._.payloads||{}}}return this._flagOverrides!==void 0&&(h={...h,...this._flagOverrides}),this._payloadOverrides!==void 0&&(y={...y,...this._payloadOverrides}),{featureFlags:h,featureFlagPayloads:y}}async evaluateFlags(e,t){let{distinctId:n,options:o}=this._resolveDistinctId(e,t);if(!n)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()"),new re({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new re({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,flags:{}});let{groups:i,disableGeoip:s,flagKeys:a}=o||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:l}=o||{},p=this.addLocalPersonAndGroupProperties(n,i,c,l);c=p.allPersonProperties,l=p.allGroupProperties;let f=this.createFeatureFlagEvaluationContext(n,i,this.personPropertiesForLocalEvaluation(n,c),l);u==null&&(u=this.options.strictLocalEvaluation??!1);let d={},h,y,E=!1,_=!1,x=await this.featureFlagsPoller?.getAllFlagsAndPayloads(f,a),M=new Set;if(x)for(let[b,z]of Object.entries(x.response)){let g=this.featureFlagsPoller?.featureFlagsByKey[b];d[b]={key:b,enabled:z!==!1,variant:typeof z=="string"?z:void 0,payload:x.payloads[b],id:g?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:g?.has_experiment},M.add(b)}if((x?x.fallbackToFlags:!0)&&!u){let b=await super.getFeatureFlagDetailsStateless(f.distinctId,f.groups,c,l,s,a);if(b){this._minimalFlagCalledEvents=b.minimalFlagCalledEvents===!0,h=b.requestId,y=b.evaluatedAt,E=!!b.errorsWhileComputingFlags,_=Array.isArray(b.quotaLimited)&&b.quotaLimited.includes("feature_flags");for(let[z,g]of Object.entries(b.flags)){if(M.has(z))continue;let w;if(g.metadata?.payload!==void 0)try{w=JSON.parse(g.metadata.payload)}catch{w=g.metadata.payload}d[z]={key:z,enabled:g.enabled,variant:g.variant,payload:w,id:g.metadata?.id,version:g.metadata?.version,reason:g.reason?.description??g.reason?.code,locallyEvaluated:!1,hasExperiment:g.metadata?.has_experiment}}}}if(this._flagOverrides!==void 0)for(let[b,z]of Object.entries(this._flagOverrides)){if(z===void 0){delete d[b];continue}let g=d[b];d[b]={key:b,enabled:z!==!1,variant:typeof z=="string"?z:void 0,payload:g?.payload,id:g?.id,version:g?.version,reason:g?.reason,locallyEvaluated:g?.locallyEvaluated??!1,hasExperiment:g?.hasExperiment}}if(this._payloadOverrides!==void 0)for(let[b,z]of Object.entries(this._payloadOverrides)){let g=d[b];g&&(d[b]={...g,payload:z})}return new re({host:this._getFeatureFlagEvaluationsHost(),distinctId:n,groups:i,disableGeoip:s,flags:d,requestId:h,evaluatedAt:y,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:E,quotaLimited:_})}_shouldSendMinimalFlagCalledEvent(e,t){return e==="$feature_flag_called"&&this._minimalFlagCalledEvents&&t.$feature_flag_has_experiment===!1}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:n,response:o,groups:i,disableGeoip:s,properties:a}=e,u=i&&Object.keys(i).length>0?`_${JSON.stringify(Object.entries(i).sort(([l],[p])=>l<p?-1:l>p?1:0))}`:"",c=`${n}_${o}${u}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(c)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(c):this.distinctIdHasSentFlagCalls[t]=new Set([c]),this.capture({distinctId:t,event:"$feature_flag_called",properties:a,groups:i,disableGeoip:s}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{this.options.featureFlagsLogWarnings!==!1&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:n,distinctId:o,disableGeoip:i}){await this._sendPreparedEvent("capture",{distinctId:o||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:n||{}},disableGeoip:i},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=n=>Object.fromEntries(n.map(o=>[o,!0]));if(e===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(e.flags===!1?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):e.flags!==void 0&&(this._flagOverrides={...e.flags})),"payloads"in e&&(e.payloads===!1?this._payloadOverrides=void 0:e.payloads!==void 0&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if("flags"in t){let n=t.flags;if(n===!1||Array.isArray(n)||typeof n=="object"&&n!==null)return!0}if("payloads"in t){let n=t.payloads;if(n===!1||typeof n=="object"&&n!==null)return!0}return!1}withContext(e,t,n){return this.context?this.context.run(e,t,n):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),n=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Promise.race([this._metrics.flush().catch(()=>{}),new Promise(o=>I(o,Math.max(0,t-Date.now())))]),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},n?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,n={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},o=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let i=new AbortController;o=I(()=>{i.abort()},this.options.requestTimeout),n.signal=i.signal}try{return await this.fetch(t,n)}catch(i){this._events.emit("error",i);return}finally{o&&clearTimeout(o)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let n={},o={};for(let[i,s]of Object.entries(e))if(Pn(s)&&t&&i in t){let a={};for(let[u,c]of Object.entries(s))a[String(u)]=String(c);o[String(i)]=a}else n[String(i)]=String(s);return{personProperties:n,groupProperties:o}}async getFeatureFlagsForEvent(e,t,n,o){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let i=o?.personProperties||{},s=o?.groupProperties||{},a=o?.flagKeys;if(o?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(t||{}))c[l]=String(p);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}else return{};if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let c={};for(let[l,p]of Object.entries(t||{}))c[l]=String(p);return await this.getAllFlags(e,{groups:c,personProperties:i,groupProperties:s,disableGeoip:n,onlyEvaluateLocally:!0,flagKeys:a})}return(await super.getFeatureFlagsStateless(e,t,i,s,n)).flags}addLocalPersonAndGroupProperties(e,t,n,o){let i={...n||{}},s={};if(t)for(let a of Object.keys(t))s[a]={$group_key:t[a],...o?.[a]||{}};return{allPersonProperties:i,allGroupProperties:s}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,n,o){return{distinctId:e,groups:t||{},personProperties:n||{},groupProperties:o||{},evaluationCache:{}}}captureException(e,t,n,o,i){if(!q.isPreviouslyCapturedError(e)){let s=new Error("PostHog syntheticException");this.addPendingPromise(q.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,n).then(a=>this._capturePreparedEvent({...a,uuid:o,flags:i},!1)))}}async captureExceptionImmediate(e,t,n,o){if(!q.isPreviouslyCapturedError(e)){let i=new Error("PostHog syntheticException");return this.addPendingPromise(q.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:i},t,n).then(s=>this.captureImmediate({...s,flags:o})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:n,event:o,properties:i,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:p}=e,f=this.context?.get(),d=t.includeContextProperties??!0,h=n||f?.distinctId,y=d?{...this.props,...f?.properties||{},...i||{}}:{...i||{}};h||(h=k(),y.$process_person_profile=!1),d&&f?.sessionId&&!y.$session_id&&(y.$session_id=f.sessionId);let E=this._shouldSendMinimalFlagCalledEvent(o,y)?$e(y):y,_=this._runBeforeSend({distinctId:h,event:o,properties:E,groups:s,flags:a,sendFeatureFlags:u,timestamp:c,disableGeoip:l,uuid:p});if(!_)return Promise.reject(null);let x=await Promise.resolve().then(async()=>{if(a)return u&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),a._getEventProperties();if(u){bt("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead \u2014 it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");let M=typeof u=="object"?u:void 0,R=await this.getFeatureFlagsForEvent(_.distinctId,s,l,M);return Sa(R)}return{}}).catch(()=>({})).then(M=>{let R=_.groups||s;return{...M,..._.properties||{},...R!==void 0&&Object.keys(R).length>0?{$groups:R}:{}}});return _.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof x.$raw_user_agent=="string"&&mn(x.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(_.event="$bot_pageview",x.$browser_type="bot"),{distinctId:_.distinctId,event:_.event,properties:x,options:{timestamp:_.timestamp,disableGeoip:_.disableGeoip,uuid:_.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let n=Array.isArray(t)?t:[t],o=e;for(let i of n){if(o=i(o),!o)return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!o.properties||Object.keys(o.properties).length===0){let s=`Event '${o.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(s)}}return o}};var Oo=require("async_hooks"),wt=class{constructor(){this.storage=new Oo.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,n){return this.storage.run(this.resolve(e,n),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let n=this.get()||{};return{distinctId:e.distinctId??n.distinctId,sessionId:e.sessionId??n.sessionId,properties:{...n.properties||{},...e.properties||{}}}}};var Mo="posthog-node";function Ia(r,{organization:e,projectId:t,prefix:n,severityAllowList:o=["error"],sendExceptionsToPostHog:i=!0}={}){return s=>{if(!(o==="*"||o.includes(s.level)))return s;s.tags||(s.tags={});let u=s.tags[hr.POSTHOG_ID_TAG];if(u===void 0)return s;let c=r.options.host??"https://us.i.posthog.com",l=new URL(`/project/${r.apiKey}/person/${u}`,c).toString();s.tags["PostHog Person URL"]=l;let p=s.exception?.values||[],f=p.map(h=>({...h,stacktrace:h.stacktrace?{...h.stacktrace,type:"raw",frames:(h.stacktrace.frames||[]).map(y=>({...y,platform:"node:javascript"}))}:void 0})),d={$exception_message:p[0]?.value||s.message,$exception_type:p[0]?.type,$exception_level:s.level,$exception_list:f,$sentry_event_id:s.event_id,$sentry_exception:s.exception,$sentry_exception_message:p[0]?.value||s.message,$sentry_exception_type:p[0]?.type,$sentry_tags:s.tags};return e&&t&&(d.$sentry_url=(n||"https://sentry.io/organizations/")+e+"/issues/?project="+t+"&query="+s.event_id),i&&r.capture({event:"$exception",distinctId:u,properties:d}),s}}var hr=class{static#e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,n,o,i){this.name=Mo,this.name=Mo,this.setupOnce=function(s,a){let u=a()?.getClient()?.getDsn()?.projectId;s(Ia(e,{organization:t,projectId:u,prefix:n,severityAllowList:o,sendExceptionsToPostHog:i??!0}))}}};var Pt=class extends xt{getLibraryId(){return"posthog-node"}initializeContext(){return new wt}createErrorPropertiesBuilder(){return new C.ErrorPropertiesBuilder([new C.EventCoercer,new C.ErrorCoercer,new C.ObjectCoercer,new C.StringCoercer,new C.PrimitiveCoercer],C.createStackParser("node:javascript",C.nodeStackLineParser),[dn(),fo,mo()])}};var Et=null,gr=null;function $t(){return Et===null||gr===null?null:{client:Et,projectKey:gr}}function No(r){if(Et!==null)return;if(se()){console.error("[HeyCatch] the server entry was bundled into a browser build - import '@heycatch/sdk' with your bundler's browser condition enabled. Server calls are no-ops here.");return}let e=un.safeParse(r);if(!e.success){let o=e.error.issues[0]?.message??"init() requires a config object with { projectKey }.";console.error(`[HeyCatch] ${o}`);return}let t=new Pt(an,{host:sn,flushAt:1,flushInterval:0,fetchRetryCount:1,fetchRetryDelay:250,requestTimeout:5e3});t.on("error",o=>{console.error("[HeyCatch] server send failed:",o)}),Et=t,gr=e.data.projectKey;let n=cn();n!==null&&console.warn(n)}function Ft(r){return{heycatch_project_key:r,heycatch_sdk_version:Pe,heycatch_sdk_stage:we}}async function Lo(r,e,t){if(se())return;let n=$t();if(n===null){console.error("[HeyCatch] setIdentity() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0){console.error("[HeyCatch] setIdentity() requires a non-empty string user id. Pass a stable internal user id from your auth provider \u2014 not an email or session token.");return}try{await n.client.captureImmediate({distinctId:r,event:"$identify",properties:{...e?{$set:e}:{},...t?{$set_once:t}:{},...Ft(n.projectKey)},groups:{[Be]:n.projectKey}})}catch(o){console.error("[HeyCatch] setIdentity() failed to reach ingest:",o)}}function Zo(r,e){console.error("[HeyCatch] setPersonProperties() has no ambient person on the server - use setIdentity(userId, properties) or trackEvent(..., { userId, set }).")}function Do(){}var Uo="X-POSTHOG-SESSION-ID";function za(r){let e=r?.headers;if(!e)return null;try{if("get"in e&&typeof e.get=="function")return e.get(Uo);let t=Uo.toLowerCase();for(let[n,o]of Object.entries(e))if(n.toLowerCase()===t&&typeof o=="string")return o;return null}catch{return null}}async function jo(r,e,t){if(se())return;let n=$t();if(n===null){console.error("[HeyCatch] trackEvent() called before init() - call init({ projectKey }) once at module scope.");return}if(typeof r!="string"||r.length===0||r.startsWith("$")){console.error('[HeyCatch] trackEvent() requires a non-empty event name that does not start with "$" (reserved for built-ins).');return}let o=t??{},i=o.userId;if(typeof i!="string"||i.length===0){console.error("[HeyCatch] trackEvent() on the server requires options.userId - there is no ambient person in a server process. Pass the same stable internal user id the client uses.");return}let s=za(o.request);try{await n.client.captureImmediate({distinctId:i,event:r,properties:{...e,...s?{$session_id:s}:{},...o.set?{$set:o.set}:{},...o.setOnce?{$set_once:o.setOnce}:{},...Ft(n.projectKey),heycatch_custom_user_event:!0},groups:{[Be]:n.projectKey}})}catch(a){console.error("[HeyCatch] trackEvent() failed to reach ingest:",a)}}var Ca={init:No,optInCapturing:_r,optOutCapturing:yr,resetIdentity:Do,setIdentity:Lo,setPersonProperties:Zo,trackEvent:jo};0&&(module.exports={KNOWN_FRAMEWORKS,KNOWN_INSTALL_AGENTS,SDK_VERSION,STAGE,UNKNOWN_INSTALL_VALUE,analytics});
|
|
3
3
|
//# sourceMappingURL=server.cjs.map
|