posthog-js 1.438.8 → 1.438.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/all-external-dependencies.js +1 -1
- package/dist/array.full.es5.js +1 -1
- package/dist/array.full.js +1 -1
- package/dist/array.full.no-external.js +1 -1
- package/dist/array.js +1 -1
- package/dist/array.no-external.js +1 -1
- package/dist/customizations.full.js +1 -1
- package/dist/customizations.full.js.map +1 -1
- package/dist/customizations.js +1 -1
- package/dist/customizations.js.map +1 -1
- package/dist/default-extensions.js +1 -1
- package/dist/extension-bundles.js +1 -1
- package/dist/lazy-recorder.js +1 -1
- package/dist/main.js +1 -1
- package/dist/module.full.cjs +1 -1
- package/dist/module.full.js +1 -1
- package/dist/module.full.no-external.cjs +1 -1
- package/dist/module.full.no-external.js +1 -1
- package/dist/module.js +1 -1
- package/dist/module.mjs +1 -1
- package/dist/module.no-external.cjs +1 -1
- package/dist/module.no-external.js +1 -1
- package/dist/module.slim.js +1 -1
- package/dist/module.slim.no-external.js +1 -1
- package/dist/posthog-recorder.js +1 -1
- package/lib/package.json +1 -1
- package/lib/src/customizations/before-send.js +0 -9
- package/lib/src/customizations/before-send.js.map +1 -1
- package/package.json +6 -6
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e="0.9.4",t={DEBUG:(!1,!1),LIB_VERSION:(e,"1.438.8"),LIB_NAME:("browser-common","web"),JS_SDK_VERSION:e};var i=t;const s="$early_access_features",r="$active_feature_flags",n="$feature_flag_details",o="$feature_flag_errors",a="$feature_flag_evaluated_at",l="$feature_flag_request_id",c="$minimal_flag_called_events",u="$enabled_feature_flags",d="$stored_group_properties",h="$stored_person_properties",_="$flag_call_reported",p="$flag_call_reported_session_id",g="$feature_flag_payloads",v="$override_feature_flags",f="$override_feature_flag_payloads",m="visibilitychange",y="$people_distinct_id",b="distinct_id",S="$device_id",w="$device_model",E="__alias",C="__cmpns",k="$fbc",P="$fbc_persistence",x="$fbp",F="$fbp_persistence",I="__timers",T="$autocapture_disabled_server_side",R="$heatmaps_enabled_server_side",M="$exception_capture_enabled_server_side",A="$error_tracking_suppression_rules",O="$error_tracking_capture_extension_exceptions",L="$web_vitals_enabled_server_side",D="$dead_clicks_enabled_server_side",N="$product_tours_enabled_server_side",B="$logs_capture_enabled_server_side",q="$web_vitals_allowed_metrics",U="$session_recording_remote_config",H="$session_recording_enabled_server_side",z="$replay_sample_rate",j="$replay_override_sampling",W="$replay_override_linked_flag",V="$replay_override_url_trigger",G="$replay_override_event_trigger",K="$sesid",Q="$session_is_sampled",J="$session_past_minimum_duration",Y="$session_recording_url_trigger_activated_session",Z="$session_recording_event_trigger_activated_session",X="$debug_first_full_snapshot_timestamp",ee="$sess_rec_flush_size",te="$groups",ie="$surveys",se="$surveys_loaded_at",re="$surveys_activated",ne="$surveys_activated_session",oe="$surveys_activated_timestamps",ae="ph_product_tours",le="$product_tours_activated",ce="$product_tours_activated_session",ue="$conversations_widget_session_id",de="$conversations_ticket_id",he="$conversations_widget_state",_e="$conversations_user_traits",pe="$user_state",ge="$client_session_props",ve="$capture_rate_limit",fe="$initial_campaign_params",me="$initial_referrer_info",ye="$initial_person_info",be="$epp",Se="$posthog_cookieless",we="$cookieless_mode",Ee="$sdk_debug_extensions_init_method",Ce="$sdk_debug_extensions_init_time_ms",ke="$sdk_debug_recording_script_not_loaded",Pe="$sdk_debug_replay_stale_config",xe="$sdk_debug_replay_event_trigger_status",Fe="$sdk_debug_replay_linked_flag_trigger_status",Ie="$sdk_debug_replay_matched_recording_trigger_groups",Te="$sdk_debug_replay_pending_trigger_conditions",Re="$sdk_debug_replay_remote_trigger_matching_config",$e="$sdk_debug_replay_trigger_groups_count",Me="$sdk_debug_replay_url_trigger_status",Ae="$session_recording_start_reason",Oe="PostHog loadExternalDependency extension not found.",Le="anonymous",De="identified",Ne="identified_only",Be="beforeunload",qe="$pageview",Ue="$pageleave",He="$identify",ze="$groupidentify",je="u">typeof window?window:void 0,We="u">typeof globalThis?globalThis:je,Ve=null==We?void 0:We.navigator,Ge=null==We?void 0:We.document,Ke=null==We?void 0:We.location,Qe=null==We?void 0:We.fetch,Je=(null==We?void 0:We.XMLHttpRequest)&&"withCredentials"in new We.XMLHttpRequest?We.XMLHttpRequest:void 0,Ye=null==We?void 0:We.AbortController,Ze=null==We?void 0:We.CompressionStream,Xe=null==Ve?void 0:Ve.userAgent,et="undefined"!=typeof globalThis?globalThis:je;et&&"undefined"==typeof self&&(et.self=et),et&&"undefined"==typeof File&&(et.File=function(){});const tt=null!=je?je:{};var it=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({}),st=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({});const rt=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],nt=["token"];function ot(e,t){return-1!==e.indexOf(t)}const at=function(e){return e.trim()},lt=function(e){return e.replace(/^\$/,"")};function ct(e){var t;const i=[];return null!==(t=JSON.stringify(e,function(e,t){if("bigint"==typeof t)return t.toString();if("function"!=typeof t&&"symbol"!=typeof t){if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if(t&&"object"==typeof t){for(;i.length>0&&i[i.length-1]!==this;)i.pop();if(i.includes(t))return"[Circular]";i.push(t)}return t}}))&&void 0!==t?t:"null"}const ut=Object.prototype,dt=ut.hasOwnProperty,ht=ut.toString,_t=Array.isArray||function(e){return"[object Array]"===ht.call(e)},pt=e=>"function"==typeof e,gt=e=>e===Object(e)&&!_t(e),vt=e=>{if(gt(e)){for(const t in e)if(dt.call(e,t))return!1;return!0}return!1},ft=e=>void 0===e,mt=e=>"[object String]"==ht.call(e),yt=e=>mt(e)&&0===e.trim().length,bt=e=>null===e,St=e=>ft(e)||bt(e),wt=e=>"[object Number]"==ht.call(e)&&e==e,Et=e=>wt(e)&&e>0,Ct=e=>"[object Boolean]"===ht.call(e),kt=e=>ot(rt,e),Pt=e=>ot(nt,e);function xt(e){return null===e||"object"!=typeof e}function Ft(e,t){return{}.toString.call(e)===`[object ${t}]`}function It(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rt(e,Error)}}function Tt(e){return"u">typeof Event&&Rt(e,Event)}function Rt(e,t){try{return e instanceof t}catch(e){return!1}}const $t=[!0,"true",1,"1","yes"],Mt=e=>ot($t,e),At=[!1,"false",0,"0","no"];function Ot(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function Lt(e){return function(){var t=this,i=arguments;return new Promise(function(s,r){var n=e.apply(t,i);function o(e){Ot(n,s,r,o,a,"next",e)}function a(e){Ot(n,s,r,o,a,"throw",e)}o(void 0)})}}const Dt=["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","pinterestbot","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"],Nt=new Map,Bt=function(e,t=[]){if(!e)return!1;const i=function(e,t){let i="";for(let e=0;t.length>e;e++){const s=t[e];i+=s.length+":"+s}return e.length+":"+e+"|"+t.length+":"+i}(e,t),s=Nt.get(i);if(void 0!==s)return s;const r=e.toLowerCase(),n=Dt.concat(t).some(e=>-1!==r.indexOf(e.toLowerCase()));return 256>Nt.size||Nt.clear(),Nt.set(i,n),n};function qt(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),wt(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),qt(null!=r?r:i,t,i,s))}var Ut=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=qt(e.bucketSize,0,100,e._logger),this._refillRate=qt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=qt(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){const i=Math.floor((t-e.lastAccess)/this._refillInterval);i>0&&(e.tokens=Math.min(e.tokens+i*this._refillRate,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval)}consumeRateLimit(e){var t;const i=Date.now(),s=String(e);let r=this._buckets[s];return r?this._applyRefill(r,i):(r={tokens:this._bucketSize,lastAccess:i},this._buckets[s]=r),0===r.tokens||(r.tokens--,0===r.tokens&&(null===(t=this._onBucketRateLimited)||void 0===t||t.call(this,e)),0===r.tokens)}stop(){this._buckets={}}};const Ht="Mobile",zt="Android",jt="Tablet",Wt="Android Tablet",Vt="iPad",Gt="Apple Watch",Kt="Safari",Qt="BlackBerry",Jt="Samsung Internet",Yt="Chrome",Zt="Chrome iOS",Xt="Internet Explorer",ei="Internet Explorer Mobile",ti="Opera",ii="Microsoft Edge",si="Firefox",ri="Firefox iOS",ni="Nintendo",oi="PlayStation",ai="Xbox",li="Android Mobile",ci="Mobile Safari",ui="Windows",di="Windows Phone",hi="Nokia",_i="Ouya",pi="Generic "+Ht.toLowerCase(),gi="Generic "+jt.toLowerCase(),vi="Konqueror",fi="Oculus Browser",mi="Vivaldi",yi="Yandex",bi="Whale",Si="DuckDuckGo",wi="Pale Moon",Ei="Waterfox",Ci="Brave",ki="Claude",Pi="Codex",xi="ChatGPT",Fi="Google Search App",Ii=new RegExp("Version/(\\d+(\\.\\d+)?)"),Ti=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),Ri=new RegExp(ai,"i"),$i=new RegExp("PlayStation \\w+","i"),Mi=new RegExp("Nintendo \\w+","i"),Ai=new RegExp("BlackBerry|PlayBook|BB10","i"),Oi={"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"},Li=function(e,t,i,s){t=t||"";const r=function(e){return(null==e?void 0:e.brave)?Ci:null}(i);return r||((null==s?void 0:s.detectGoogleSearchApp)&&ot(e,"GSA/")?Fi:ot(e," OPR/")&&ot(e,"Mini")?"Opera Mini":ot(e," OPR/")?ti:Ai.test(e)?Qt:ot(e,"IEMobile")||ot(e,"WPDesktop")?ei:ot(e,"OculusBrowser")?fi:ot(e,"SamsungBrowser")?Jt:ot(e,"Edge")||ot(e,"Edg/")?ii:ot(e,"Vivaldi/")?mi:ot(e,"YaBrowser/")?yi:ot(e,"Whale/")?bi:ot(e,"DuckDuckGo/")||ot(e,"Ddg/")?Si:ot(e,"Claude/")?ki:ot(e,"Codex/")?Pi:ot(e,"ChatGPT/")?xi:ot(e,"FBIOS")?"Facebook Mobile":ot(e,"UCWEB")||ot(e,"UCBrowser")?"UC Browser":ot(e,"CriOS")?Zt:ot(e,"CrMo")||ot(e,Yt)?Yt:ot(e,zt)&&ot(e,Kt)?li:ot(e,"FxiOS")?ri:ot(e.toLowerCase(),vi.toLowerCase())?vi:ot(e,"Brave/")?Ci:((e,t)=>t&&ot(t,"Apple")||function(e){return ot(e,Kt)&&!ot(e,Yt)&&!ot(e,zt)}(e))(e,t)?ot(e,Ht)?ci:Kt:ot(e,"PaleMoon/")?wi:ot(e,"Waterfox/")?Ei:ot(e,si)?si:ot(e,"MSIE")||ot(e,"Trident/")?Xt:ot(e,"Gecko")?si:"")},Di={[ei]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[ii]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Yt]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Zt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Kt]:[Ii],[ci]:[Ii],[ti]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[si]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[ri]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[vi]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Qt]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ii],[li]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[Jt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[fi]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[mi]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[yi]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[bi]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Ci]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[ki]:[Ti],[Pi]:[Ti],[xi]:[Ti],[Si]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[wi]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Ei]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Fi]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[Xt]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},Ni=function(e,t,i,s){const r=Li(e,t,i,s),n=Di[r];if(ft(n))return null;for(let t=0;n.length>t;t++){const i=e.match(n[t]);if(i)return parseFloat(i[i.length-2])}return null},Bi=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[ai,e&&e[1]||""]],[new RegExp(ni,"i"),[ni,""]],[new RegExp(oi,"i"),[oi,""]],[Ai,[Qt,""]],[new RegExp(ui,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[di,""];if(new RegExp(Ht).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){let e=Oi[i[1]]||"";return/arm/i.test(t)&&(e="RT"),[ui,e]}return[ui,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=ft(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[zt,[e[2],e[3],e[4]||"0"].join(".")]:[zt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],qi=function(e){for(let t=0;Bi.length>t;t++){const[i,s]=Bi[t],r=i.exec(e),n=r&&(pt(s)?s(r,e):s);if(n)return n}return["",""]},Ui=function(e){return Mi.test(e)?ni:$i.test(e)?oi:Ri.test(e)?ai:new RegExp(_i,"i").test(e)?_i:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?di:/iPad/.test(e)?Vt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Gt:Ai.test(e)?Qt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(hi,"i").test(e)?hi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Ht).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?zt:Wt:new RegExp("(pda|Mobile)","i").test(e)?pi:new RegExp(jt,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?gi:""},Hi=function(e,t){var i;const s=Ui(e);return s===Vt||s===Wt||"Kobo"===s||"Kindle Fire"===s||s===gi?jt:s===ni||s===ai||s===oi||s===_i?"Console":s===Gt?"Wearable":s?Ht:"Android"===(null==t?void 0:t.userAgentDataPlatform)&&(null!==(i=null==t?void 0:t.maxTouchPoints)&&void 0!==i?i:0)>0?600>Math.min(null!==(r=null==t?void 0:t.screenWidth)&&void 0!==r?r:0,null!==(n=null==t?void 0:t.screenHeight)&&void 0!==n?n:0)/(null!==(o=null==t?void 0:t.devicePixelRatio)&&void 0!==o?o:1)?Ht:jt:"Desktop";var r,n,o},zi=/\bFBAV\/(\d+(?:\.\d+)*)/i,ji=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",zi],[/\bFBAN\/EMA\b/i,"Facebook Lite",zi],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",zi],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],Wi="[Truncated]",Vi="[Unserializable]";function Gi(e){let t="";for(let i=0;e.length>i;i++){const s=e.charCodeAt(i);if(55296>s||s>56319)t+=56320>s||s>57343?e[i]:"�";else{const s=e.charCodeAt(i+1);56320>s||s>57343?t+="�":(t+=e[i]+e[i+1],i++)}}return t}function Ki(e,t){if(!t)return e;let i=[];try{i=Object.keys(t)}catch(e){i=[]}for(const s of i){let i;try{i=t[s]}catch(e){i=Vi}Object.defineProperty(e,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}Date,Date;const Qi=3e5;var Ji=class{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;const t=this.isOpen(),i=Date.now(),s=Math.min(e.retryAfterMs,Qi);if(!t)return this._installedAt=i,void(this._until=i+s);this._until=Math.max(this._until,Math.min(i+s,this._installedAt+Qi))}remainingMs(){const e=Date.now();if(this._installedAt-5e3>e)return this.reset(),0;const t=Math.min(Qi,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};const Yi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zi(e,t){return"string"==typeof(i=e)&&Yi.test(i)?e:t();var i}function Xi(e,t){const i=new Error(t);try{Object.defineProperty(i,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){}return i}function es(e){return e?e.split("#")[0]:e}function ts(e){try{return e()}catch(e){return}}function is(e,t){const i=setTimeout(e,t);return null!=i&&i.unref&&(null==i||i.unref()),i}function ss(e,t,i){return rs.apply(this,arguments)}function rs(){return(rs=Lt(function*(e,t,i){let s;try{return yield Promise.race([e,new Promise((e,r)=>{s=is(()=>{try{null==i||i(),e()}catch(e){r(e)}},t)})])}finally{clearTimeout(s)}})).apply(this,arguments)}function ns(e){return ns="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ns(e)}function os(e,t,i){return(t=function(e){var t=function(e){if("object"!=ns(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!=ns(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ns(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function as(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function ls(e){for(var t=1;arguments.length>t;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?as(Object(i),!0).forEach(function(t){os(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):as(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let cs,us,ds,hs;function _s(e){var t;const i=globalThis._posthogChunkIds,s=globalThis._debugIds;if(!i&&!s)return;const r=i?Object.keys(i):[],n=s?Object.keys(s):[];if(hs&&ps(i,r,us)&&ps(s,n,ds))return hs;us=i?ls({},i):void 0,ds=s?ls({},s):void 0,hs={},null!==(t=cs)&&void 0!==t||(cs={});const o=(t,i)=>{for(const r of t){const t=i[r];if(!t)continue;const n=null==cs?void 0:cs[r];if(n){hs[n]=t;continue}const o=e(r);for(let e=o.length-1;e>=0;e--){var s;const i=null===(s=o[e])||void 0===s?void 0:s.filename;if(i){hs[i]=t,cs[r]=i;break}}}};return s&&o(n,s),i&&o(r,i),hs}function ps(e,t,i){return e&&i?t.length===Object.keys(i).length&&t.every(t=>e[t]===i[t]):e===i}var gs=class{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){const i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(t),n=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(n,i),$exception_level:"error"}}modifyFrames(e){var t=this;return Lt(function*(){for(const i of e)i.stacktrace&&i.stacktrace.frames&&_t(i.stacktrace.frames)&&(i.stacktrace.frames=yield t.applyModifiers(i.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null===(t=e.syntheticException)||void 0===t?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var i;let s,r;if(null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch(e){}return ls(ls({},e),{},{cause:s,stack:r,errors:null===(i=e.errors)||void 0===i?void 0:i.map(e=>this.parseStacktrace(e,t))})}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(const i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Lt(function*(){let i=e;for(const e of t.modifiers)i=yield e(i);return i})()}convertToExceptionList(e,t){const i=[],s=(e,r,n)=>{var o;const a=i.length,l=void 0===r?ls(ls({type:"string"==typeof t.type&&t.type.length>0?t.type:"generic"},"boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{}),{},{synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}):{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:r},c={type:e.type,value:e.value,mechanism:l};e.stack&&(c.stacktrace={type:"raw",frames:e.stack}),i.push(c),e.cause&&s(e.cause,a,"cause");for(const t of null!==(o=e.errors)&&void 0!==o?o:[])s(t,a,"member")};return s(e),i}buildParsingContext(e){var t;return{chunkIdMap:_s(this.stackParser),skipFirstLines:null!==(t=e.skipFirstLines)&&void 0!==t?t:1}}getAggregateErrors(e){try{if(It(e)){let i=Object.getPrototypeOf(e);for(let s=0;i&&100>s;s++){var t;const s=null===(t=Object.getOwnPropertyDescriptor(i,"constructor"))||void 0===t?void 0:t.value;if("function"==typeof s&&"AggregateError"===s.name){const t=e.errors;return _t(t)?t:void 0}i=Object.getPrototypeOf(i)}}}catch(e){}}buildCoercingContext(e,t,i=0){let s=0,r=0,n=!1;const o=new Set,a=[],l={},c=(e,t,i=0)=>{const c=u(t,i),d=c.apply;if(c.apply=t=>{a.push(e);try{return d(t)}finally{a.pop()}},i>4||i>0&&-1!==a.indexOf(e))return this.coerceFallback(c);const h="object"==typeof e&&null!==e||"function"==typeof e;if(0===i&&s>=50||h&&o.has(e))return;h&&o.add(e),0===i&&s++;const _=this.getAggregateErrors(e);let p,g;n||(n=!!_);try{if(p=this.applyCoercers(e,c),!p)throw l}catch(e){if(e===l)return void(0===i&&s--);if(!n)throw e;p=this.coerceFallback(c)}if(!_||s>=50)return p;try{g=_.length}catch(e){return p}if(!Number.isInteger(g)||0>g||g>4294967295)return p;const v=[];for(let e=0;50>s&&1e3>r&&g>e;e++){let i;r++;try{i=c.next(_[e])}catch(e){s++,i=this.coerceFallback(u(t+1))}i&&v.push(i)}return ls(ls({},p),{},{errors:v})},u=(i,s=0)=>ls(ls({},t),{},{syntheticException:0==i?t.syntheticException:void 0,mechanism:0==i?e:{},apply(e){const t=c(e,i,s+1);if(!t)throw l;return t},next:e=>c(e,i+1)}),d=u(i);return ls(ls({},d),{},{apply:e=>{var t;return null!==(t=c(e,i))&&void 0!==t?t:this.coerceFallback(d)}})}};const vs=/^([a-z][a-z0-9.+-]+):/i,fs=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ms(e){if(!e||"<anonymous>"===e)return!1;const t=vs.exec(e);return!t||fs.includes(t[1].toLowerCase())}function ys(e,t,i,s,r){const n={platform:e,filename:t,function:"<anonymous>"===i?"?":i,in_app:ms(t)};return ft(s)||(n.lineno=s),ft(r)||(n.colno=r),n}const bs=(e,t)=>{const i=-1!==e.indexOf("safari-extension"),s=-1!==e.indexOf("safari-web-extension");return i||s?[-1!==e.indexOf("@")?e.split("@")[0]:"?",i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Ss=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ws=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Es=/\((\S*)(?::(\d+))(?::(\d+))\)/,Cs=(e,t)=>{const i=Ss.exec(e);if(i){const[,e,s,r]=i;return ys(t,e,"?",+s,+r)}const s=ws.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){const e=Es.exec(s[2]);e&&(s[2]=e[1],s[3]=e[2],s[4]=e[3])}const[e,i]=bs(s[1]||"?",s[2]);return ys(t,i,e,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},ks=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ps=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xs=(e,t)=>{const i=ks.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){const e=Ps.exec(i[3]);e&&(i[1]=i[1]||"eval",i[3]=e[1],i[4]=e[2],i[5]="")}let e=i[3],s=i[1]||"?";return[s,e]=bs(s,e),ys(t,e,s,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},Fs=/\(error: (.*)\)/;function Is(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function Ts(e){for(let t=1;10>=t;t++){const i=e.length-2*t;if(0>i)break;let s=!0;for(let r=0;t>r;r++)if(!Is(e[i+r],e[i+t+r])){s=!1;break}if(s){for(let s=0;t>s;s++)e[i+s]=e[i+t+s];return e.length=i+t,{start:i,length:t}}}}function Rs(e,t){const i=t.start+t.length,s=Ms(e,t);s&&e.splice(i+s===e.length?i:t.start,s)}function $s(e,t){let i=t.start;for(;i>0&&Is(e[i-1],e[i-1+t.length]);)i--;return t.start-i}function Ms(e,t){const i=t.start+t.length;let s=i;for(;e.length>s&&Is(e[s],e[s-t.length]);)s++;return s-i}function As(e,t){const i=t[0];let s=e.length-(i?$s(e,i):0);for(const i of t)s-=Ms(e,i);return s}function Os(e,t,i){for(let s=0;e.length>s;s++){const r=e[(t+s)%e.length],n=e[(i+s)%e.length];if(r!==n)return n>r}return!1}var Ls=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const i=mt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?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){const t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ft(e,"DOMException")}isDOMError(e){return Ft(e,"DOMError")}},Ds=class{match(e){return It(e)}coerce(e,t){var i;const s=this.getStack(e),r=void 0===s?null===(i=t.syntheticException)||void 0===i?void 0:i.stack:void 0,n=!!r;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:r,cause:e.cause?t.next(e.cause):void 0,synthetic:n}}getType(e){return e.name||e.constructor.name}getMessage(e,t){const i=e.message;return String(i.error&&"string"==typeof i.error.message?i.error.message:i)}getStack(e){try{const t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;const i=e.stack;return"string"==typeof i&&i.length>0?i:void 0}catch(e){return}}},Ns=class{match(e){return!!Ft(e,"ErrorEvent")&&(null!=e.error||this._hasUsableMessage(e))}coerce(e,t){var i;if(null!=e.error)return t.apply(e.error);const s=t.apply(e.message);return ls(ls({},s),{},{stack:null!==(i=this._buildLocationStack(e))&&void 0!==i?i:s.stack,synthetic:!0})}_hasUsableMessage(e){return mt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i;const s=e,r=null!==(t=s.lineno)&&void 0!==t?t:0,n=null!==(i=s.colno)&&void 0!==i?i:0;if(mt(s.filename)&&0!==s.filename.length&&0!==r)return`Error\n at ${s.filename}:${r}:${n}`}};const Bs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var qs=class{match(e){return"string"==typeof e}coerce(e,t){var i;const[s,r]=this.getInfos(e);return{type:null!=s?s:"Error",value:null!=r?r:e,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}getInfos(e){let t="Error",i=e;const s=e.match(Bs);return s&&(t=s[1],i=s[2]),[t,i]}};const Us=["fatal","error","warning","log","info","debug"];function Hs(e,t=40){const i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let e=i.length;e>0;e--){const s=i.slice(0,e).join(", ");if(t>=s.length)return e===i.length?s:s.length>t?`${s.slice(0,t)}...`:s}return""}var zs=class{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s;const r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null!==(i=this.getStack(e))&&void 0!==i?i:null===(s=t.syntheticException)||void 0===s?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Tt(e))return e.constructor.name;const t="name"in e?e.name:void 0;return mt(t)&&!yt(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;const t=this.getObjectClassName(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${Hs(e)}`}isSeverityLevel(e){return mt(e)&&!yt(e)&&Us.indexOf(e)>=0}getStack(e){try{return mt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:mt(e.stack)&&e.stack.length>0?e.stack:void 0}catch(e){return}}getErrorPropertyFromObject(e){for(const t in e)if({}.hasOwnProperty.call(e,t)){const i=e[t];if(It(i))return i}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}},js=class{match(e){return Tt(e)}coerce(e,t){var i;const s=e.constructor.name;return{type:s,value:`${s} captured as exception with keys: ${Hs(e)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}},Ws=class{match(e){return xt(e)}coerce(e,t){var i;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}},Vs=class{match(e){return Ft(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Tt(e))return!1;try{const t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch(e){return!1}}coerce(e,t){var i;const s=this.getUnhandledRejectionReason(e);return xt(s)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(s)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch(e){}return e}};const Gs="$message",Ks="$timestamp",Qs=new Set([Gs,Ks]),Js={enabled:!0,max_bytes:32768};function Ys(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Js.enabled,max_bytes:Xs(e.max_bytes,Js.max_bytes)}:ls({},Js)}var Zs=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Ys(e)}setConfig(e){this._config=Ys(e),this._trimToMaxBytes()}add(e){const t=function(e){let t;try{t=ct(e)}catch(e){return}try{const e=JSON.parse(t);if(!gt(e))return;const i=e,s=i[Gs],r=i[Ks];if(!mt(s)||0===s.trim().length)return;if(!mt(r)&&!wt(r))return;return{step:i,json:t}}catch(e){return}}(e);if(!t)return;const i=function(e){if("u">typeof TextEncoder)return(new TextEncoder).encode(e).length;const t=encodeURIComponent(e);let i=0;for(let e=0;t.length>e;e++)"%"===t[e]?(i+=1,e+=2):i+=1;return i}(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,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;){const e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Xs(e,t){if(!wt(e)||1/0===e||-1/0===e)return t;const i=Math.floor(e);return 0>i?t:i}const er=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function tr(e){return"string"==typeof e||e}function ir(e){return"string"==typeof e?e:void 0}const sr=["$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","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],rr="NativeGzipValidationError",nr=e=>e.length>=2&&31===e[0]&&139===e[1],or=(e,t)=>e===st.GZipJS||t===st.GZipJS||"gzip"===t,ar=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):"");let lr;const cr=e=>{throw Xi(rr,`Native gzip produced invalid output: ${e}`)},ur=(dr=Lt(function*(e,t){18>e.size&&cr("too-short");const i=new Uint8Array(yield e.slice(0,10).arrayBuffer());nr(i)&&8===i[2]||cr("invalid-header");const s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{const t=(()=>{if(lr)return lr;lr=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)t=1&t?3988292384^t>>>1:t>>>1;lr[e]=t>>>0}return lr})();let i=4294967295;for(let s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&cr("invalid-crc");const r=t.length>>>0;s.getUint32(4,!0)!==r&&cr("invalid-size")}),function(e,t){return dr.apply(this,arguments)});var dr;function hr(){return hr=Lt(function*(e,t=!0,i){try{const t=(new TextEncoder).encode(e),i=new globalThis.CompressionStream("gzip"),r=i.writable.getWriter(),n=r.write(t).then(()=>r.close()).catch((s=Lt(function*(e){try{yield r.abort(e)}catch(e){}throw e}),function(e){return s.apply(this,arguments)})),o=new Response(i.readable).blob(),[a]=yield Promise.all([o,n]);return yield ur(a,t),a}catch(e){if(null==i?void 0:i.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}var s}),hr.apply(this,arguments)}function _r(e,t){if(null==e)return{};var i,s,r=function(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.includes(s))continue;i[s]=e[s]}return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;n.length>s;s++)t.includes(i=n[s])||{}.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}const pr="[redacted]",gr=/^[A-Za-z0-9+/\n\r]+=*$/,vr=/^[A-Za-z0-9_-]+={0,2}$/,fr=/[-_]/,mr=/^data:[^,\s]*;base64,/i,yr=/^[A-Za-z0-9+/_-]+={0,2}$/,br=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,Sr=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,wr=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,Er=/[\s<>"]/,Cr=new RegExp(wr.source,"i"),kr=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Pr=new RegExp(`^${kr.source}`,"i"),xr=new RegExp(kr.source,"gi"),Fr=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,Ir=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,Tr=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,Rr=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,$r=/\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g,Mr=/(^|[^\w:])((?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g,Ar=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,Or=/\b\d(?:[ ./-]?\d){12,}\b/g,Lr=/\d+/g,Dr=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,Nr=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;function Br(e){return function(e){return Sr.test(e)}(e)||Fr.test(e)||Ir.test(e)}function qr(e){return e.split("&",129).length>128}function Ur(e,t,i){return Br(e)||t.includes(";")&&function(e){return e.split(";").some(e=>Br(e.split("=",1)[0]))}(t)?pr:Cr.test(t)?i?Gr(t,{allowNestedUrls:!1,stripPunctuation:!0}):pr:t}function Hr(e,t){const i=new URLSearchParams;let s=!1,r=!1;for(const[n,o]of new URLSearchParams(e)){const e=Kr(n),a=Kr(o);s||(s=e!==n||a!==o);const l=Ur(e,a,t);s||(s=l!==a),r=Br(e)||l!==a,i.append(e,l)}return{changed:s,lastFieldSensitive:r,serialized:i.toString()}}function zr(e,t){if(!e.includes("="))return{value:jr(e,t),lastFieldSensitive:!1};const i=Hr(e,t);return{value:i.changed?i.serialized:e,lastFieldSensitive:i.lastFieldSensitive}}function jr(e,t){return t?Gr(e,{allowNestedUrls:!1,stripPunctuation:!0}):Cr.test(e)?pr:e}function Wr(e,t,i){return"#"===e?!t.fragment&&(t.fragment=!0):"?"===e&&(t.fragment?"="!==i&&!t.fragmentQuery&&(t.fragmentQuery=!0):!t.query&&(t.query=!0))}function Vr(e,t){var i;if(e.length>8192&&Pr.test(e))return pr;const{address:s,suffix:r}=t.stripPunctuation?function(e){let t=e.length;for(;t>0&&".,;:!?)]}'".includes(e[t-1]);)t--;return{address:e.slice(0,t),suffix:e.slice(t)}}(e):{address:e,suffix:""};let n;try{n=new URL(s)}catch(e){return pr+r}const o=n.search.slice(1),a=""!==n.hash,l=function(e){const t=e.slice(1),i=t.indexOf("?");return 0>i?{head:t,tail:null}:{head:t.slice(0,i),tail:t.slice(i+1)}}(n.hash);if(qr(o)||qr(l.head)||qr(null!==(i=l.tail)&&void 0!==i?i:""))return pr+r;let c=!1;(n.username||n.password)&&(n.username=pr,n.password="",c=!0);const u=Hr(o,t.allowNestedUrls);u.changed&&(n.search=u.serialized,c=!0);const d=zr(l.head,t.allowNestedUrls),h=null===l.tail?null:(_=l.tail,d.lastFieldSensitive?{value:""===_?"":pr,lastFieldSensitive:!0}:zr(_,t.allowNestedUrls));var _;const p=null===h?d.value:`${d.value}?${h.value}`;p!==n.hash.slice(1)&&(n.hash=p,c=!0);const g=a?null!=h?h:d:u;return(c?Kr(n.toString()):s)+(g.lastFieldSensitive?"":r)}function Gr(e,t){return e.replace(wr,i=>function(e,t){const i=function(e){if(!e.includes("://"))return[];const t=[...e.matchAll(xr)].map(e=>e.index),i=[],s={query:!1,fragment:!1,fragmentQuery:!1};let r=0,n=!1,o="";for(let a=0;e.length>a&&t.length>r;a++){t[r]===a&&(a>0&&"="!==o&&i.push(a),r++);const l=e[a];Wr(l,s,o)?(o=l,n=!0):n&&"=&".includes(l)&&(o=l)}return i}(e);if(0===i.length)return Vr(e,t);let s="",r=0;for(const n of i)s+=Vr(e.slice(r,n),ls(ls({},t),{},{stripPunctuation:!1})),r=n;return s+Vr(e.slice(r),t)}(i,ls(ls({},t),{},{stripPunctuation:t.stripPunctuation&&i.length!==e.length})))}function Kr(e){return e.replace(br,pr)}function Qr(e,t){return function(e){return e.length>=10240&&(gr.test(e)||function(e){const t=mr.exec(e);if(!t)return!1;let i;try{i=decodeURIComponent(e.slice(t[0].length))}catch(e){return!1}return yr.test(i.replace(/[\r\n]/g,""))}(e)||fr.test(e)&&vr.test(e))}(e)?"[binary data redacted - not supported by PostHog MCP analytics]":function(e,t,i){const s=4*i.maxStringLength;if(e.length>s){const r=t(e.slice(0,function(e,t){let i=t;for(;i>0&&!Er.test(e[i-1]);)i--;return i}(e,s)));if(r.length>=2*i.maxStringLength)return r+i.truncationSuffix}return t(e)}(e,e=>function(e){return Gr(e,{allowNestedUrls:!0,stripPunctuation:!0})}(function(e){let t=e.replace(Tr," ");return t=t.replace(Rr,pr),t=t.replace($r,pr),t=t.replace(Mr,`$1${pr}`),t=t.replace(Or,Yr),t=t.replace(Ar,pr),t=t.replace(Dr,`$1${pr}`),t=t.replace(Nr,`$1${pr}`),t}(Kr(e))),t)}function Jr(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let r=e.charCodeAt(s)-48;if(0>r||r>9)return!1;i&&(r*=2,r>9&&(r-=9)),t+=r,i=!i}return t%10==0}function Yr(e){const t=[];for(let i=Lr.exec(e);null!==i;i=Lr.exec(e))t.push({digits:i[0],start:i.index,end:i.index+i[0].length});let i="",s=0,r=0;for(;t.length>r;){let n="",o=-1;for(let e=r;t.length>e&&(n+=t[e].digits,19>=n.length);e++)n.length>=13&&Jr(n)&&(o=e);0>o?r++:(i+=e.slice(s,t[r].start)+pr,s=t[o].end,r=o+1)}return i+e.slice(s)}const Zr={}.propertyIsEnumerable;function Xr(e,t){try{return sn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch(e){return[]}}function en(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:Wi};if(i.remainingNodes--,Ct(e))return{boolValue:e};if("bigint"==typeof e)return function(e,t){const i=e.toString(),s=BigInt("9223372036854775808");return e>=s||-s>e?(null==t||t.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}(e,t);if("number"==typeof e){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=0x8000000000000000||-0x8000000000000000>e?(null==t||t.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if("string"==typeof e)return{stringValue:Gi(e)};if("function"==typeof e)return{stringValue:"[Function]"};if("symbol"==typeof e)return{stringValue:String(e)};if("object"==typeof e&&null!==e){if(i.ancestors.has(e))return{stringValue:"[Circular]"};if(s>=20)return{stringValue:Wi};if(e instanceof Date){const t=e.getTime(),i=Number.isFinite(t)?e.toISOString():String(e);return{stringValue:"string"==typeof i?Gi(i):String(i)}}i.ancestors.add(e);try{try{const r=e.toJSON;if("function"==typeof r)return en(r.call(e),t,i,s+1)}catch(e){}return _t(e)?{arrayValue:{values:tn(e,t,i,s+1)}}:{kvlistValue:{values:sn(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Gi(String(e))}}function tn(e,t,i,s){const r=[],n=Math.min(e.length,1e3);let o=0;for(;n>o&&i.remainingNodes>0;o++)try{const n=o in e?e[o]:void 0;if(St(n))continue;r.push(en(n,t,i,s))}catch(e){r.push({stringValue:Vi})}return e.length>o&&r.push({stringValue:Wi}),r}function sn(e,t,i,s){const r=[];for(const n in e)if(Zr.call(e,n)){if(!n){null==t||t.debug("Dropping an attribute with an empty key");continue}if(r.length>=1e3||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[n];if(bt(o)||ft(o))continue;r.push({key:Gi(n),value:en(o,t,i,s)})}catch(e){r.push({key:Gi(n),value:{stringValue:Vi}})}}return r}function rn(e,t,i){return ls(ls(ls(ls({},Ki({},e.resourceAttributes)),{},{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment}),e.serviceVersion&&{"service.version":e.serviceVersion}),{},{"telemetry.sdk.name":t,"telemetry.sdk.version":i})}const nn=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function on(e,t){const i=Ki({},e),s={};for(const e of nn)({}).hasOwnProperty.call(i,e)&&(s[e]=i[e],delete i[e]);return[...Xr(i,t),...Xr(s,t)]}const an={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};const ln={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}},cn=ln.info;function un(e){try{return Gi(String(e))}catch(e){return Vi}}function dn(e,t,i,s){const r=e.level||"info",{text:n,number:o}=ln[r]||cn,a=function(e=Date.now()){return String(e)+"000000"}(wt(s)?s:void 0),l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),St(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),St(t.lastActivityTimestamp)||(l.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(l["url.full"]=t.currentUrl),t.screenName&&(l["screen.name"]=t.screenName),t.appState&&(l["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(l.feature_flags=t.activeFeatureFlags);const c=ls({},l),u=e.attributes;if(u){let e=[];try{e=Object.keys(u)}catch(t){e=[]}for(const t of e){let e;try{e=u[t]}catch(t){e=Vi}Object.defineProperty(c,t,{value:e,enumerable:!0,writable:!0,configurable:!0})}}const d={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:n,body:{stringValue:un(e.body)},attributes:Xr(c,i)};return e.trace_id&&(d.traceId=e.trace_id),e.span_id&&(d.spanId=e.span_id),ft(e.trace_flags)||(d.flags=e.trace_flags),d}function hn(e,t,i){return rn(e,t,i)}function _n(e,t,i,s){return{resourceLogs:[{resource:{attributes:on(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}var pn=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=is(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function gn(){return.75+.5*Math.random()}function vn(e,t,i,s){const r=Math.min(Math.max(0,t-1),6),n=e*Math.pow(2,r);return Math.round((void 0===s?n:Math.min(n,Math.max(s,e)))*i)}var fn=class{constructor(e,t,i,s,r,n=()=>Promise.resolve(),o){var a;this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=r,this._waitForStoragePersist=n,this._scopeName=o,this._flushTimer=new pn(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._retryAfter=new Ji,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(a=t.maxQueueSize)&&void 0!==a?a:t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(it.LogsQueue,[])}reset(){this._flushTimer.clear(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.isOpen()?this._hasQueuedRecords()&&this._armFlushTimer():this._flushInBackground()}captureLog(e,t){var i;if(this._instance.isDisabled)return;if(this._instance.optedOut)return;if(!(null==e?void 0:e.body))return;const s=this._runBeforeSend(e);if(null===s)return;if(!s.body)return void this._logger.info("Log was rejected in beforeSend function");if(!this._checkRateLimit())return;const r={record:dn(s,null!==(i=null==t?void 0:t.context)&&void 0!==i?i:this._getContext(),this._logger,null==t?void 0:t.occurredAtMs)};this._onReady(()=>this._enqueue(r))}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=_t(t)?t:[t];let s=e;for(const e of i)try{const t=e(s);if(!t)return this._logger.info("Log was rejected in beforeSend function"),null;s=t}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return s}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;const e=Date.now(),t=e-this._intervalWindowStart;return this._rateCapWindowMs>t&&t>=0||(this._intervalWindowStart=e,this._intervalLogCount=0,this._droppedWarned=!1),this._maxLogsPerInterval>this._intervalLogCount?(this._intervalLogCount++,!0):(this._droppedWarned||(this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`),this._droppedWarned=!0),!1)}flush(){var e=this;return Lt(function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally(()=>{e._flushPromise=null})),e._flushPromise})()}_flushInner(){var e=this;return Lt(function*(){var t;e._flushTimer.clear();let i=null!==(t=e._instance.getPersistedProperty(it.LogsQueue))&&void 0!==t?t:[];if(0===i.length)return;const s=i.length;let r=0;for(;i.length>0&&s>r;){var n,o;const t=e._queueGeneration;e._evictedSinceAdvance=0;const s=Math.min(i.length,e._maxBatchRecordsPerPost),a=i.slice(0,s),l=_n(a.map(e=>e.record),e._buildResourceAttributes(),null!==(n=e._scopeName)&&void 0!==n?n:e._instance.getLibraryId(),e._instance.getLibraryVersion()),c=yield e._instance._sendLogsBatch(l);if(e._queueGeneration!==t)return;if("too-large"===c.kind&&a.length>1)e._maxBatchRecordsPerPost=Math.max(1,Math.floor(a.length/2)),e._logger.warn(`Logs batch of size ${a.length} was too large for the ingestion endpoint, reducing batch size to ${e._maxBatchRecordsPerPost}`);else{if(e._retryAfter.record(c),e._flushTimer.pending&&e._flushTimer.arm(Math.max(e._flushIntervalMs,e._retryAfter.remainingMs())),"retry-later"===c.kind)throw c.error;if("too-large"===c.kind?e._logger.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===c.kind&&e._config.maxBatchRecordsPerPost>e._maxBatchRecordsPerPost&&(e._maxBatchRecordsPerPost=Math.min(e._config.maxBatchRecordsPerPost,e._maxBatchRecordsPerPost+1)),yield e._persistQueueAdvance(a.length),i=null!==(o=e._instance.getPersistedProperty(it.LogsQueue))&&void 0!==o?o:[],r+=a.length,"fatal"===c.kind)throw c.error}}})()}_persistQueueAdvance(e){var t=this;return Lt(function*(){var i;const s=Math.max(0,e-t._evictedSinceAdvance),r=null!==(i=t._instance.getPersistedProperty(it.LogsQueue))&&void 0!==i?i:[];t._instance.setPersistedProperty(it.LogsQueue,r.slice(s)),yield t._waitForStoragePersist()})()}_buildResourceAttributes(){return hn(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(this._instance.optedOut)return;const i=null!==(t=this._instance.getPersistedProperty(it.LogsQueue))&&void 0!==t?t:[];this._maxQueueSize>i.length||(i.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),i.push(e),this._instance.setPersistedProperty(it.LogsQueue,i),this._maxBufferSize>i.length||this._retryAfter.isOpen()?this._armFlushTimer():this._flushInBackground()}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs()))}_nextFlushDelay(){return Math.max(vn(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){const e=this._instance.getPersistedProperty(it.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Lt(function*(){t._flushTimer.clear();const i=t.flush().catch(()=>{});void 0!==e?yield ss(i,e):yield i})()}flushWithTimeout(e){var t=this;return Lt(function*(){const i=t.flush();yield ss(i,e,()=>{i.catch(()=>{})})})()}_flushInBackground(){this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},e=>{this._consecutiveFlushFailures++,this._flushJitter=gn(),this._logger.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())})}};const mn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function yn(e){return String(e)+"000000"}function bn(e,t,i,s){let r="";return s&&(r=Object.keys(s).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(s[e])}`).join(",")),`${e}\0${t}\0${null!=i?i:""}\0${r}`}var Sn=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushTimer=new pn(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new Ji,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}flush(){var e=this;const t=this._flushPromise,i=function(){var i=Lt(function*(){t&&(yield t.catch(()=>{})),yield e._doFlush()});return function(){return i.apply(this,arguments)}}()().finally(()=>{this._flushPromise===i&&(this._flushPromise=null)});return this._flushPromise=i,i}drainWindow(){if(0===this._series.size)return null;const 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._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),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;const t=this._runBeforeSend(e);if(null===t)return;if(!t.name||"string"!=typeof t.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof t.value||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if("count"===t.type&&0>t.value)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let i,s;try{i=t.attributes?ls({},t.attributes):void 0,s=bn(t.type,t.name,t.unit,i)}catch(e){return void this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,e)}let r=this._series.get(s);if(!r){if(!this._admitNewSeries())return;r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now()},this._series.set(s,r)}const n=this._typeByName.get(t.name);void 0===n?this._typeByName.set(t.name,t.type):n===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${n}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(r,t.value),this._armFlushTimer()}_admitNewSeries(){return this._config.maxSeriesPerFlush>this._series.size||(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":var i;e.total=(null!==(i=e.total)&&void 0!==i?i: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(mn.length+1).fill(0)});const i=e.hist;i.count+=1,i.sum+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),i.bucketCounts[function(e,t){for(let i=0;t.length>i;i++)if(t[i]>=e)return i;return t.length}(t,mn)]+=1;break}}}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=_t(t)?t:[t];let s=e;for(const e of i)try{const t=e(s);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;s=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(vn(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_doFlush(){var e=this;return Lt(function*(){if(e._flushTimer.clear(),0===e._series.size)return;const t=e._series;e._series=new Map,e._seriesCapWarned=!1,e._typeByName=new Map,e._typeCollisionWarned=new Set;const i=e._generation,s=yield e._instance._sendMetricsBatch(e._buildPayload(t));if(i===e._generation)switch(e._retryAfter.record(s),"retry-later"===s.kind?(e._consecutiveFlushFailures++,e._flushJitter=gn()):(e._consecutiveFlushFailures=0,e._flushJitter=1),e._flushTimer.pending&&e._flushTimer.arm(e._nextFlushDelay()),s.kind){case"ok":return;case"retry-later":return e._mergeWindowBack(t),void e._flushTimer.armNoEarlierThan(e._nextFlushDelay());case"too-large":return void e._logger.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void e._logger.error("Failed to send metrics batch:",s.error)}})()}_buildPayload(e){return t=this._buildMetrics(e),i=function(e,t,i){return rn(e,t,i)}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),s=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:on(i)},scopeMetrics:[{scope:{name:s,version:r},metrics:t}]}]};var t,i,s,r}_buildMetrics(e){const t=yn(Date.now()),i=new Map;for(const o of e.values()){var s;const e=bn(o.type,o.name,o.unit,void 0);let a=i.get(e);a||(a=ls({name:o.name},o.unit&&{unit:o.unit}),"count"===o.type?a.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===o.type?a.gauge={dataPoints:[]}:a.histogram={aggregationTemporality:1,dataPoints:[]},i.set(e,a));const l=Xr(null!==(s=o.attributes)&&void 0!==s?s:{},this._logger),c=yn(o.windowStartMs);if("count"===o.type){var r;const e={attributes:l,startTimeUnixNano:c,timeUnixNano:t,asDouble:null!==(r=o.total)&&void 0!==r?r:0};a.sum.dataPoints.push(e)}else if("gauge"===o.type){var n;const e={attributes:l,timeUnixNano:t,asDouble:null!==(n=o.last)&&void 0!==n?n:0};a.gauge.dataPoints.push(e)}else o.hist&&a.histogram.dataPoints.push({attributes:l,startTimeUnixNano:c,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:mn})}return Array.from(i.values())}_mergeWindowBack(e){for(const[s,r]of e){const e=this._series.get(s);if(e)switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.type){case"count":var t,i;e.total=(null!==(t=e.total)&&void 0!==t?t:0)+(null!==(i=r.total)&&void 0!==i?i:0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;e.hist.bucketCounts.length>t;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}else this._admitNewSeries()&&this._series.set(s,r)}}};const wn=(e,{debugEnabled:i}={})=>{const s={_log(s,...r){let n;try{n=typeof window>"u"?void 0:window}catch(e){return}n&&(t.DEBUG||n.POSTHOG_DEBUG||i)&&!ft(n.console)&&n.console&&("__rrweb_original__"in n.console[s]?n.console[s].__rrweb_original__:n.console[s])(e,...r)},debug(...e){s._log("debug",...e)},info(...e){s._log("log",...e)},warn(...e){s._log("warn",...e)},error(...e){s._log("error",...e)},critical(...t){console.error(e,...t)},uninitializedWarning(e){s.error(`You must initialize PostHog before calling ${e}`)},createLogger:(t,i)=>wn(`${e} ${t}`,i)};return s},En=wn("[PostHog.js]"),Cn=En.createLogger;function kn(e,t){_t(e)&&e.forEach(t)}function Pn(e,t){if(!St(e))if(_t(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(const i in e)dt.call(e,i)&&t(e[i],i)}const xn=function(e,...t){for(const i of t)for(const t in i)void 0!==i[t]&&(e[t]=i[t]);return e};function Fn(e){const t=Object.keys(e);let i=t.length;const s=new Array(i);for(;i--;)s[i]=[t[i],e[t[i]]];return s}const In=function(e){return function(...t){try{return e.apply(this,t)}catch(e){En.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),En.critical(e)}}},Tn=function(e){const t={};return Pn(e,function(e,i){(mt(e)&&e.length>0||wt(e))&&(t[i]=e)}),t};function Rn(e){const t=ls({},e);for(const i of["name","message","stack","cause","errors"])try{i in e&&(t[i]=e[i])}catch(e){}return t}const $n=["herokuapp.com","vercel.app","netlify.app"];function Mn(e){const t=null==e?void 0:e.hostname;if(!mt(t))return!1;const i=t.split(".").slice(-2).join(".");for(const e of $n)if(i===e)return!1;return!0}function An(e,t,i,s){const{capture:r=!1,passive:n=!0}=null!=s?s:{};null==e||e.addEventListener(t,i,{capture:r,passive:n})}function On(e){return"ph_toolbar_internal"===e.name}const Ln=e=>{if(Ge){try{const t=e+"=",i=Ge.cookie.split(";").filter(e=>e.length);for(let e=0;i.length>e;e++){let s=i[e];for(;" "==s.charAt(0);)s=s.substring(1,s.length);if(0===s.indexOf(t))return decodeURIComponent(s.substring(t.length,s.length))}}catch(e){}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return wt(e)&&isFinite(e)&&Math.floor(e)===e});var Dn=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,s,r){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||!Number.isInteger(r)||0>t||0>i||0>s||0>r||t>0xffffffffffff||i>4095||s>1073741823||r>4294967295)throw new RangeError("invalid field value");const n=new Uint8Array(16);return n[0]=t/Math.pow(2,40),n[1]=t/Math.pow(2,32),n[2]=t/Math.pow(2,24),n[3]=t/Math.pow(2,16),n[4]=t/256,n[5]=t,n[6]=112|i>>>8,n[7]=i,n[8]=128|s>>>24,n[9]=s>>>16,n[10]=s>>>8,n[11]=s,n[12]=r>>>24,n[13]=r>>>16,n[14]=r>>>8,n[15]=r,new e(n)}toString(){let e="";for(let t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new e(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;16>t;t++){const i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}},Nn=class{generate(){const e=this.generateOrAbort();if(!ft(e))return e;{this._timestamp=0;const e=this.generateOrAbort();if(ft(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const e=(()=>{const e=Date.now();return wt(e)&&isFinite(e)?Math.min(Math.max(Math.floor(e),0),0xffffffffffff):0})();if(e>this._timestamp)this._timestamp=e,this._resetCounter();else{if(this._timestamp>=e+1e4)return;this._counter++,this._counter>4398046511103&&(this._timestamp++,this._resetCounter())}return Dn.fromFieldsV7(this._timestamp,Math.trunc(this._counter/Math.pow(2,30)),this._counter&Math.pow(2,30)-1,this._random.nextUint32())}_resetCounter(){this._counter=1024*this._random.nextUint32()+(1023&this._random.nextUint32())}constructor(){this._timestamp=0,this._counter=0,this._random=new qn}};let Bn=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};je&&!ft(je.crypto)&&crypto.getRandomValues&&(Bn=e=>crypto.getRandomValues(e));var qn=class{nextUint32(){return this._buffer.length>this._cursor||(Bn(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}};let Un;const Hn=()=>zn().toString(),zn=()=>(Un||(Un=new Nn)).generate();let jn="";const Wn=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let Vn=null;const Gn={_is_supported(){if(!bt(Vn))return Vn;if(Vn=!1,Ge)try{const e=`__ph_cookie_support_${Hn()}`;Gn._set(e,"xyz"),Vn='"xyz"'===Ln(e),Gn._remove(e)}catch(e){Vn=!1}return Vn},_error(e){En.error("cookieStore error: "+e)},_get:Ln,_parse(e){let t;try{t=JSON.parse(Gn._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Ge)return!1;try{let n="",o="";const a=function(e,t){if(t){let t=function(e,t=Ge){if(jn)return jn;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";const i=e.split(".");let s=Math.min(i.length,8);const r="dmn_chk_"+Hn();for(;!jn&&s--;){const e=i.slice(s).join("."),n=r+"=1;domain=."+e+";path=/";t.cookie=n+";max-age=3",t.cookie.includes(r)&&(t.cookie=n+";max-age=0",jn=e)}return jn}(e);if(!t){const i=(e=>{const t=e.match(Wn);return t?t[0]:""})(e);i!==t&&En.info("Warning: cookie subdomain discovery mismatch",i,t),t=i}return t?"; domain=."+t:""}return""}(Ge.location.hostname,s);if(i){const e=new Date;e.setTime(e.getTime()+864e5*i),n="; expires="+e.toUTCString()}r&&(o="; secure");const l=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return l.length>3686.4&&En.warn("cookieStore warning: large cookie, len="+l.length),Ge.cookie=l,!0}catch(e){return!1}},_remove(e,t){if((null==Ge?void 0:Ge.cookie)&&(!t||!bt(Ln(e))))try{Gn._set(e,"",-1,t)}catch(e){return}}};let Kn=null;const Qn={_is_supported(){if(!bt(Kn))return Kn;let e=!0;if(ft(je))e=!1;else try{const t="__mplssupport__";Qn._set(t,"xyz"),'"xyz"'!==Qn._get(t)&&(e=!1),Qn._remove(t)}catch(t){e=!1}return e||En.error("localStorage unsupported; falling back to cookie store"),Kn=e,e},_error(e){En.error("localStorage error: "+e)},_get(e){try{return null==je?void 0:je.localStorage.getItem(e)}catch(e){Qn._error(e)}return null},_parse(e){try{return JSON.parse(Qn._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==je||je.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Qn._error(e)}return!1},_remove(e){try{null==je||je.localStorage.removeItem(e)}catch(e){Qn._error(e)}}},Jn=[h,r,u,n,g,l,a,o,_],Yn=[S,b,K,Q,be,ye,P,pe],Zn=e=>e+"_cpm",Xn=["__proto__","constructor","prototype"],eo=e=>{if(!gt(e))return{};const t={};return Object.keys(e).forEach(i=>{-1===Xn.indexOf(i)&&(t[i]=e[i])}),t},to=(e,t=[])=>{const i={};return[...Yn,...t].forEach(t=>{const s=e[t];ft(s)||bt(s)||""===s||(i[t]=s)}),i},io=e=>{let t=5381,i=2166136261;for(let s=0;e.length>s;s++){const r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},so=(e,t)=>({p:t,f:io(JSON.stringify(e))}),ro=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const i=Gn._parse(Zn(e)),s=(null==i?void 0:i.f)===io(t)&&_t(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},no=(e,t)=>t+"|"+(Gn._get(Zn(e))||""),oo={},ao={_is_supported:()=>!0,_error(e){En.error("memoryStorage error: "+e)},_get:e=>e in oo?oo[e]:null,_parse:e=>e in oo?oo[e]:null,_set:(e,t)=>(oo[e]=t,!0),_remove(e){delete oo[e]}};let lo=null;const co={_is_supported(){if(!bt(lo))return lo;if(lo=!0,ft(je))lo=!1;else try{const e="__support__";co._set(e,"xyz"),'"xyz"'!==co._get(e)&&(lo=!1),co._remove(e)}catch(e){lo=!1}return lo},_error(e){En.error("sessionStorage error: ",e)},_get(e){try{return null==je?void 0:je.sessionStorage.getItem(e)}catch(e){co._error(e)}return null},_parse(e){try{return JSON.parse(co._get(e))||null}catch(e){}return null},_set(e,t){try{return null==je||je.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){co._error(e)}return!1},_remove(e){try{null==je||je.sessionStorage.removeItem(e)}catch(e){co._error(e)}}};var uo=class{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return"always"===this._config.cookieless_mode||this.isRejected()||-1===this.consent&&"on_reject"===this._config.cookieless_mode}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return 0===this.consent}isRejected(){return 0===this.consent||-1===this.consent&&this._config.opt_out_capturing_by_default}optInOut(e){this._storage._set(this._storageKey,e?1:0,this._config.cookie_expiration,this._config.cross_subdomain_cookie,this._config.secure_cookie)}reset(){this._storage._remove(this._storageKey,this._config.cross_subdomain_cookie)}get _storageKey(){const{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:i}=this._instance.config;return i||(t?t+e:"__ph_opt_in_out_"+e)}get _storedConsent(){const e=this._storage._get(this._storageKey);return Mt(e)?1:ot(At,e)?0:-1}get _storage(){const e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?Qn:Gn,i=t._is_supported()?t:ao;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;const t="localStorage"===e?Gn:Qn;t._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut(Mt(t._get(this._storageKey))),t._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==Ve?void 0:Ve.doNotTrack,null==Ve?void 0:Ve.msDoNotTrack,tt.doNotTrack,null==Ve?void 0:Ve.globalPrivacyControl].some(e=>Mt(e))}};function ho(e,t){var i;const s=null==e||null===(i=e.config)||void 0===i?void 0:i.get_current_url;if(!pt(s))return t;try{const e=s(t);return mt(e)&&e?e:t}catch(e){return En.error("Error in get_current_url, falling back to window.location.href",e),t}}function _o(e){var t;return e instanceof Element&&("__POSTHOG_TOOLBAR__"===e.id||!!(null===(t=e.closest)||void 0===t?void 0:t.call(e,".toolbar-global-fade-container")))}function po(e){return!!e&&1===e.nodeType}function go(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function vo(e){return!!e&&3===e.nodeType}function fo(e){return!!e&&11===e.nodeType&&po(e.host)}function mo(e){return e?at(e).split(/\s+/):[]}function yo(e,t){const i=function(e){var t;const i=null==je||null===(t=je.location)||void 0===t?void 0:t.href;return ft(i)?void 0:ho(e,i)}(t);return!!(i&&e&&e.some(e=>i.match(e)))}function bo(e){let t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return mo(t)}function So(e){return St(e)?null:at(e).split(/(\s+)/).filter(e=>Yo(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function wo(e){let t="";return Ho(e)&&!zo(e)&&e.childNodes&&e.childNodes.length&&Pn(e.childNodes,function(e){var i;vo(e)&&e.textContent&&(t+=null!==(i=So(e.textContent))&&void 0!==i?i:"")}),at(t)}function Eo(e){var t;return ft(e.target)?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null}const Co=["a","button","form","input","select","textarea","label"];function ko(e,t){const i=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!i&&i.call(e,t)}catch(e){return!1}}function Po(e,t){if(ft(t))return!0;for(const i of e)if(t.some(e=>ko(i,e)))return!0;return!1}function xo(e){const t=e.parentNode;return!(!t||!po(t))&&t}const Fo=[".ph-no-autocapture","[data-ph-no-autocapture]"],Io=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],To=[...Io,"+","-","−","–"],Ro=To.length+10,$o=["button","a","input","select","textarea","label"],Mo=["button","link","tab","menuitem","option"],Ao=(e,t)=>/[a-z0-9]/i.test(t)?ot(To,t)?new RegExp(`\\b${t}\\b`).test(e):e.includes(t):e===t,Oo=e=>ot($o,e.tagName.toLowerCase())||ot(Mo,(e.getAttribute("role")||"").toLowerCase());function Lo(e){let t="",i="";const s=e=>{po(e)&&Ho(e)&&!zo(e)&&(t+=` ${wo(e)}`,i=i||e.getAttribute("aria-label")||"",Pn(e.childNodes,s))};s(e),t=at(t.replace(/\s+/g," "));const r=(Yo(t)?t:"").toLowerCase(),n=e.getAttribute("aria-label")||(r?"":i);return{safeText:r,ariaLabel:at(n).toLowerCase()}}const Do=[".ph-no-rageclick",".ph-no-capture"],No=["","text","search","email","password","url","tel","number"];function Bo(e,t){if(!je||qo(e))return!1;let i,s,r;var n,o;if(Ct(t)?(i=!!t&&Do,s=void 0,r=!1):(i=null!==(n=null==t?void 0:t.css_selector_ignorelist)&&void 0!==n?n:Do,s=null==t?void 0:t.content_ignorelist,r=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(r&&function(e){return!(!e||!po(e))&&(!!go(e,"textarea")||(go(e,"input")?ot(No,(e.getAttribute("type")||"").toLowerCase()):function(e){var t;if(e.isContentEditable)return!0;const i=null===(t=e.getAttribute)||void 0===t?void 0:t.call(e,"contenteditable");return"true"===i||""===i}(e)))}(e))return!1;const{targetElementList:a}=Uo(e,!1);return!(s&&function(e,{safeText:t,ariaLabel:i}){let s;if(!0===e)s=Io;else{if(!_t(e))return!1;if(e.length>Ro)return En.error(`[PostHog] content_ignorelist array cannot exceed ${Ro} items. Use css_selector_ignorelist for more complex matching.`),!1;s=e.map(e=>e.toLowerCase())}return s.some(e=>Ao(t,e)||Ao(i,e))}(s,function(e,t){for(const e of t)if(Oo(e))return Lo(e);for(const e of t){try{if("pointer"!==(null==je?void 0:je.getComputedStyle(e).getPropertyValue("cursor")))break}catch(e){break}const t=Lo(e);if(t.safeText||t.ariaLabel)return t}return Lo(e)}(e,a))||Po(a,i))}const qo=e=>!e||go(e,"html")||!po(e),Uo=(e,t)=>{if(!je||qo(e))return{parentIsUsefulElement:!1,targetElementList:[]};let i=!1;const s=[e];let r=e;for(;r.parentNode&&!go(r,"body");){if(fo(r.parentNode)){s.push(r.parentNode.host),r=r.parentNode.host;continue}const e=xo(r);if(!e)break;if(t||Co.indexOf(e.tagName.toLowerCase())>-1)i=!0;else try{const t=je.getComputedStyle(e);t&&"pointer"===t.getPropertyValue("cursor")&&(i=!0)}catch(e){}s.push(e),r=e}return{parentIsUsefulElement:i,targetElementList:s}};function Ho(e){const t=new Set;let i=0;for(let s=e;s.parentNode&&!go(s,"body");s=s.parentNode){if(i++>=1e3||t.has(s))return!1;t.add(s);const e=bo(s);if(ot(e,"ph-sensitive")||ot(e,"ph-no-capture"))return!1}if(ot(bo(e),"ph-include"))return!0;const s=e.type||"";if(mt(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}const r=e.name||e.id||"";return!mt(r)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,""))}function zo(e){return!!(go(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||go(e,"select")||go(e,"textarea")||"true"===e.getAttribute("contenteditable"))}const jo=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),Wo=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vo=[16,15,14,13],Go=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Ko=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Qo=/[0-9A-Za-z_]/;function Jo(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let r=e.charCodeAt(s)-48;i&&(r*=2,r>9&&(r-=9)),t+=r,i=!i}return t%10==0}function Yo(e,t=!0){if(St(e))return!1;if(mt(e)){if(e=at(e),t?jo.test((e||"").replace(/[- ]/g,"")):function(e){let t;for(Wo.lastIndex=0;t=Wo.exec(e);){const e=t[2];if(!e)continue;const i=e.replace(/[- ]/g,"");for(let e=0;i.length>e;e++)for(const t of Vo){const s=e+t;if(i.length>=s){const t=i.slice(e,s);if(jo.test(t)&&Jo(t))return!0}}}return!1}(e))return!1;if(t?Go.test(e):function(e){let t;for(Ko.lastIndex=0;t=Ko.exec(e);){const e=t[1],i=t[3];if(!(e&&i&&Qo.test(e)&&Qo.test(i)))return!0}return!1}(e))return!1}return!0}function Zo(e){let t=wo(e);return t=`${t} ${Xo(e)}`.trim(),Yo(t)?t:""}function Xo(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Pn(e.childNodes,function(e){var i;if(e&&"span"===(null===(i=e.tagName)||void 0===i?void 0:i.toLowerCase()))try{const i=wo(e);t=`${t} ${i}`.trim(),e.childNodes&&e.childNodes.length&&(t=`${t} ${Xo(e)}`.trim())}catch(e){En.error("[AutoCapture]",e)}}),t}function ea(e){return e.replace(/"|\\"/g,'\\"')}function ta(e){const t=e.attr__class;if(t)return _t(t)?t:mo(t)}const ia=Cn("[Dead Clicks]"),sa=()=>!0,ra=e=>{var t;const i=!!(null===(t=e.instance.persistence)||void 0===t?void 0:t.get_property(D)),s=e.instance.config.capture_dead_clicks;return Ct(s)?s:!!gt(s)||i};var na=class{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[D]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript(()=>{this._start()}):this.stop()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.initDeadClicksAutocapture)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this.instance,"dead-clicks-autocapture",t=>{t?ia.error("failed to load script",t):e()})}_start(){var e;if(Ge){if(!this._lazyLoadedDeadClicksAutocapture&&(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.initDeadClicksAutocapture)){const e=gt(this.instance.config.capture_dead_clicks)?ls({},this.instance.config.capture_dead_clicks):{};e.__onCapture=this.onCapture,this.onCapture&&(e.capture_dead_swipes=!1),this._lazyLoadedDeadClicksAutocapture=tt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,e),this._lazyLoadedDeadClicksAutocapture.start(Ge),ia.info("starting...")}}else ia.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,ia.info("stopping..."))}};const oa=Cn("[SegmentIntegration]");function aa(e,t,i=!0){const s=e.config.segment;if(!s)return t();const{analytics:r,filterProperties:n}=(e=>pt(e.register))(o=s)?{analytics:o}:o;var o;!function(e,t,i,s){const r=t=>{const r=()=>t.anonymousId()||Hn();e.config.get_device_id=r,s&&t.id()&&(e.register({distinct_id:t.id(),$device_id:r()}),e.persistence.set_property(pe,De)),i(s?void 0:t.anonymousId()||void 0)},n=t.user();"then"in n&&pt(n.then)?n.then(r):r(n)}(e,r,i=>{r.register(((e,t,{filterProperties:i}={})=>{"undefined"!=typeof Promise&&Promise.resolve||oa.warn("This browser does not have Promise support, and can not use the segment integration");const s=(s,r)=>{if(!r)return s;const n=!!t&&s.event.anonymousId===t&&!s.event.userId;n||s.event.userId||s.event.anonymousId===e.get_distinct_id()||(oa.info("No userId set, resetting PostHog"),e.reset()),n||(t=void 0),s.event.userId&&s.event.userId!==e.get_distinct_id()&&(oa.info("UserId set, identifying with PostHog"),e.identify(s.event.userId));let o=e.calculateEventProperties(r,s.event.properties);if(!St(i)){const e=s.event.properties||{},t={};for(const i of Object.keys(o))dt.call(e,i)||(t[i]=o[i]);const r=((e,t)=>{const i=_t(e)?e:[e];let s=ls({},t);for(const e of i)try{if(s=e(s),St(s))return null}catch(e){return oa.error("Error in Segment filterProperties:",e),null}return s})(i,t);if(St(r))return s;o=r}return s.event.properties=Object.assign({},o,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(e){return s(e,e.event.event)},page(e){return s(e,qe)},identify(e){return s(e,He)},screen(e){return s(e,"$screen")}}})(e,i,{filterProperties:n})).then(()=>{t()},e=>{oa.error("Failed to register the Segment integration",e),t()})},i)}const la="posthog-js";function ca(e,{organization:t,projectId:i,prefix:s,severityAllowList:r=["error"],sendExceptionsToPostHog:n=!0}={}){return o=>{var a,l,c,u,d;if("*"!==r&&!r.includes(o.level)||!e.__loaded)return o;o.tags||(o.tags={});const h=e.requestRouter.endpointFor("ui",`/project/${e.config.token}/person/${e.get_distinct_id()}`);o.tags["PostHog Person URL"]=h,e.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));const _=(null===(a=o.exception)||void 0===a?void 0:a.values)||[],p=_.map(e=>ls(ls({},e),{},{stacktrace:e.stacktrace?ls(ls({},e.stacktrace),{},{type:"raw",frames:(e.stacktrace.frames||[]).map(e=>ls(ls({},e),{},{platform:"web:javascript"}))}):void 0})),g={$exception_message:(null===(l=_[0])||void 0===l?void 0:l.value)||o.message,$exception_type:null===(c=_[0])||void 0===c?void 0:c.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:(null===(u=_[0])||void 0===u?void 0:u.value)||o.message,$sentry_exception_type:null===(d=_[0])||void 0===d?void 0:d.type,$sentry_tags:o.tags};var v;return t&&i&&(g.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+o.event_id),n&&(null===(v=e.exceptions)||void 0===v||v.sendExceptionEvent(g)),o}}var ua=class{constructor(e,t,i,s,r,n){this.name=la,this.setupOnce=function(o){o(ca(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}},da=class{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(En.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this._currentPageview=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this._setupSessionRotationHandler()}_setupSessionRotationHandler(){var e;this._unsubscribeSessionId=null===(e=this._instance.sessionManager)||void 0===e?void 0:e.onSessionId(this._onSessionIdChange)}destroy(){var e;null===(e=this._unsubscribeSessionId)||void 0===e||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i;const s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==je?void 0:je.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null===(t=this._currentPageview)||void 0===t?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null===(e=this._currentPageview)||void 0===e?void 0:e.pageViewId}}_previousPageViewProperties(e,t){const i=this._currentPageview;if(!i)return{$pageview_id:t};let s={$pageview_id:t,$prev_pageview_id:i.pageViewId};const r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:e,lastScrollY:t,maxScrollY:i,maxContentHeight:n,lastContentY:o,maxContentY:a}=r;if(!(ft(e)||ft(t)||ft(i)||ft(n)||ft(o)||ft(a))){e=Math.ceil(e),t=Math.ceil(t),i=Math.ceil(i),n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a);const r=e>1?qt(t/e,0,1,En):1,l=e>1?qt(i/e,0,1,En):1,c=n>1?qt(o/n,0,1,En):1,u=n>1?qt(a/n,0,1,En):1;s=xn(s,{$prev_pageview_last_scroll:t,$prev_pageview_last_scroll_percentage:r,$prev_pageview_max_scroll:i,$prev_pageview_max_scroll_percentage:l,$prev_pageview_last_content:o,$prev_pageview_last_content_percentage:c,$prev_pageview_max_content:a,$prev_pageview_max_content_percentage:u})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}};const ha=["flags","surveys"],_a={[y]:{exposure:"hidden"},[E]:{exposure:"hidden"},[C]:{exposure:"hidden"},[I]:{exposure:"hidden"},[P]:{exposure:"hidden"},[F]:{exposure:"hidden"},[T]:{exposure:"event"},[R]:{exposure:"hidden"},[B]:{exposure:"hidden"},[M]:{exposure:"event"},[A]:{exposure:"hidden"},[O]:{exposure:"event"},[L]:{exposure:"event"},[D]:{exposure:"event"},[N]:{exposure:"hidden"},[q]:{exposure:"event"},[U]:{exposure:"hidden"},[H]:{exposure:"hidden"},[K]:{exposure:"hidden"},[Q]:{exposure:"event"},[z]:{exposure:"event",shouldSkipFromEventProperties:e=>bt(e)},[J]:{exposure:"event"},[Y]:{exposure:"event"},[Z]:{exposure:"event"},[X]:{exposure:"event"},[ee]:{exposure:"hidden"},[u]:{exposure:"hidden",storageGroup:"flags"},[r]:{exposure:"hidden",storageGroup:"flags"},[s]:{exposure:"hidden"},[n]:{exposure:"hidden",storageGroup:"flags"},[g]:{exposure:"hidden",storageGroup:"flags"},[l]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[c]:{exposure:"hidden",storageGroup:"flags"},[v]:{exposure:"hidden"},[f]:{exposure:"hidden"},[h]:{exposure:"hidden"},[d]:{exposure:"hidden"},[ie]:{exposure:"hidden",storageGroup:"surveys"},[se]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[re]:{exposure:"event"},[ne]:{exposure:"hidden"},[oe]:{exposure:"hidden"},[ae]:{exposure:"hidden"},[le]:{exposure:"hidden"},[ce]:{exposure:"hidden"},[ue]:{exposure:"event"},[de]:{exposure:"event"},[he]:{exposure:"event"},[_e]:{exposure:"event"},[_]:{exposure:"hidden"},[p]:{exposure:"hidden"},[te]:{exposure:"event"},[o]:{exposure:"hidden"},[a]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[pe]:{exposure:"hidden"},[ge]:{exposure:"hidden"},[ve]:{exposure:"hidden"},[fe]:{exposure:"hidden"},[me]:{exposure:"hidden"},[ye]:{exposure:"hidden"},[be]:{exposure:"hidden"},[j]:{exposure:"event"},[W]:{exposure:"event"},[V]:{exposure:"event"},[G]:{exposure:"event"},[Ee]:{exposure:"event"},[Ce]:{exposure:"event"},[ke]:{exposure:"hidden"},[Pe]:{exposure:"hidden"},[xe]:{exposure:"hidden"},[Fe]:{exposure:"hidden"},[Ie]:{exposure:"hidden"},[Te]:{exposure:"hidden"},[Re]:{exposure:"hidden"},[$e]:{exposure:"hidden"},[Me]:{exposure:"hidden"},[Ae]:{exposure:"event"}},pa=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ga=e=>{const t=_a[e];if(t)return t;for(const[t,i]of pa)if(0===e.indexOf(t))return i};function va(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}const fa=()=>{try{return"u">typeof window&&!1!==window.navigator.onLine}catch(e){return!1}},ma=(e,t)=>e>=t&&fa(),ya=(e,t,i,s)=>{if(0===e){if(fa()){const e=t+1;return e===i&&s(),e}return t}return 0},ba=(e,t)=>{try{let i;return JSON.stringify(e,(e,t)=>{var s;return It(t)?(null!==(s=i)&&void 0!==s||(i=new WeakMap),i.has(t)||i.set(t,Rn(t)),i.get(t)):"bigint"==typeof t?t.toString():t},t)}catch(t){return ct(e)}},Sa=e=>{const t=null==Ge?void 0:Ge.createElement("a");return ft(t)?null:(t.href=e,t)},wa=function(e,t){const i=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let s;for(let e=0;i.length>e;e++){const r=i[e].split("=");if(r[0]===t){s=r;break}}if(!_t(s)||2>s.length)return"";{let e=s[1];try{e=decodeURIComponent(e)}catch(t){En.error("Skipping decoding for malformed query param: "+e)}return e.replace(/\+/g," ")}},Ea=function(e,t,i){if(!e||!t||!t.length)return e;const s=e.split("#"),r=s[1],n=(s[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),c=[];for(let e=0;l.length>e;e++){const s=l[e].split("=");_t(s)&&(t.includes(s[0])?c.push(s[0]+"="+i):c.push(l[e]))}let u=a;return null!=o&&(u+="?"+c.join("&")),null!=r&&(u+="#"+r),u},Ca=function(e,t){const i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},ka=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Pa=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ka],xa="<masked>",Fa=["li_fat_id"];function Ia(e,t,i){if(!Ge)return{};const s=t?[...ka,...i||[]]:[],r=Ta(Ea(Ge.URL,s,xa),e),n=function(){const e={};return Pn(Fa,function(t){const i=Ln(t);e[t]=i||null}),e}();return xn(n,r)}function Ta(e,t){const i=Pa.concat(t||[]),s={};return Pn(i,function(t){const i=wa(e,t);s[t]=i||null}),s}function Ra(e){const t=function(e){return e?0===e.search("https?://(.*)google.([^/?]*)")?"google":0===e.search("https?://(.*)bing.com")?"bing":0===e.search("https?://(.*)yahoo.com")?"yahoo":0===e.search("https?://(.*)duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!bt(t)){s.$search_engine=t;const e=Ge?wa(Ge.referrer,i):"";e.length&&(s.ph_keyword=e)}return s}function $a(){return navigator.language||navigator.userLanguage}function Ma(){const e=$a();return"string"==typeof e?e.split("-")[0]:void 0}const Aa="$direct";function Oa(){return(null==Ge?void 0:Ge.referrer)||Aa}function La(e,t,i=!1){const s=e?[...ka,...t||[]]:[],r=i?es(null==Ke?void 0:Ke.href):null==Ke?void 0:Ke.href,n=null==r?void 0:r.substring(0,1e3);return{r:Oa().substring(0,1e3),u:n?Ea(n,s,xa):void 0}}function Da(e,t=!1){var i;const{r:s,u:r}=e,n=t?es(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==Aa?Aa:null===(i=Sa(s))||void 0===i?void 0:i.host};if(n){o.$current_url=n;const e=Sa(n);o.$host=null==e?void 0:e.host,o.$pathname=null==e?void 0:e.pathname;const t=Ta(n);xn(o,t)}if(s){const e=Ra(s);xn(o,e)}return o}function Na(){try{return(new Date).getTimezoneOffset()}catch(e){return}}const Ba={flags:a,surveys:se},qa=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Ua=e=>`${e}_cookie_identity_change_pending`,Ha=e=>{let t="",i=0;for(const s of e){const e=encodeURIComponent(JSON.stringify(s).slice(1,-1)).length;if(i+e>1e3)break;t+=s,i+=e}return t},za="main",ja=[u,r,n,g,l,a,c,h],Wa=e=>-1!==ja.indexOf(e),Va=[P,F],Ga=e=>-1!==Va.indexOf(e),Ka=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},Qa=e=>{if(!e)return{};const t=JSON.parse(e);return gt(t)?t:{}},Ja=(e,t)=>{Pn(e,(i,s)=>{const r=ga(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]})};var Ya=class{constructor(e,t,i=!0,s=!e.cookieless_mode){if(this._slotState={},this._splitStorageEligible=!1,this._storesIdentityInCookie=!1,this._splitStorage=!1,this._cookieIdentityChangePending=!1,this._cookieSyncSuppressed=!1,this._pendingCrossTabFeatureFlagChanges=new Map,this._storageMigrationInProgress=!1,this._localIdentityChangePending=!1,this._crossTabFeatureFlagIdentityMismatch=!1,this._metaIdentifierChangePending=new Set,this._crossTabFeatureFlagHandlers=new Set,this._config=e,this._ownsSplitStorage=i,this.props={},this._campaign_params_url=void 0,this._name=(e=>{let t="";return e.token&&(t=e.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),e.persistence_name?"ph_"+e.persistence_name:"ph_"+t+"_posthog"})(e),this._disabled=e.disable_persistence||!!t,this._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(s),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&En.info("Persistence loaded",e.persistence,ls({},this.props)),this.update_config(e,e,t),this.save(),je){const e=()=>this.flush();An(je,"beforeunload",e,{capture:!1}),An(je,"pagehide",e,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==je?void 0:je.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){const t=ha.find(t=>e.key===this._groupEntryName(t));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,za)},An(je,"storage",this._onStorage)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([e,t])=>{const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!Wa(e)||!0===i)return;if(!0===t)return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(i||[]);t.forEach(e=>s.add(e)),s.size&&this._setCrossTabFeatureFlagChangesPending(e,s)})}onCrossTabFeatureFlagChange(e){return this._crossTabFeatureFlagHandlers.add(e),()=>this._crossTabFeatureFlagHandlers.delete(e)}destroy(){this._onStorage&&je&&(je.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i=!0){if(this._disabled)return!1;let s,r;try{if(r=Qn._get(e),bt(r)){const e=this._slotWriteState(t);return e.storageValue=null,t!==za&&(e.persisted=!1),!1}s=Qa(r)}catch(e){return!1}const n=t===za?s:Qn._parse(this._name);if(n&&this._hasCrossTabFeatureFlagIdentityMismatch(n))return!1;const o=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===za&&this._splitStorage&&!Ka(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,r),o}_hasCrossTabFeatureFlagIdentityMismatch(e){const t=this.props[b],i=e[b];return!ft(t)&&!ft(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){const r=this._slotWriteState(t);r.storageValue=s,t!==za&&(r.persisted=i);try{r.fingerprint=this._entryFingerprint(e,t)}catch(e){r.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){let s=!1;return ja.forEach(i=>{var r;const n=null===(r=ga(i))||void 0===r?void 0:r.storageGroup;if(t===za&&this._splitStorage&&n||t!==za&&n!==t)return;const o=i in e,a=this._mergePendingCrossTabFeatureFlagChanges(i,o?e[i]:void 0),l=this._pendingCrossTabFeatureFlagChanges.has(i)?i in this.props:o;l===i in this.props&&Ka(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}),s&&i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()),s}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;const e=Qn._get(this._name),t=this._slotWriteState(za);let i,s=!1,r=!1;if(e!==t.storageValue)if(bt(e))t.storageValue=null;else{if(i=Qa(e),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(i),this._crossTabFeatureFlagIdentityMismatch)return!1;r=this._mergeCrossTabFeatureFlagProperties(i,za,!1),!this._splitStorage||Ka(this._partitionProps().main,i)?this._rememberCrossTabStorageFingerprint(i,za,!0,e):t.storageValue=e,s=!0}return this._splitStorage&&ha.forEach(e=>{const t=Qn._get(this._groupEntryName(e)),n=this._slotWriteState(e),o=i||{},a=s&&ja.some(t=>{var i;return(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e&&t in o});if(t===n.storageValue&&!a)return;if(bt(t))return n.storageValue=null,n.persisted=!1,void(a&&(r=this._mergeCrossTabFeatureFlagProperties(o,e,!1)||r));const l=Qa(t);r=this._mergeCrossTabFeatureFlagProperties(l,e,!1)||r,this._rememberCrossTabStorageFingerprint(l,e,!0,t)}),r}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);const i=ga(e);(null==i?void 0:i.volatile)||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||za).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){ja.forEach(e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{const e=Qn._get(this._name),t=Qa(e);this._slotWriteState(za).storageValue=e,ja.forEach(e=>{var i;const s=this._splitStorage?null===(i=ga(e))||void 0===i?void 0:i.storageGroup:void 0,r=s?Qn._get(this._groupEntryName(s)):null;if(s){const e=this._slotWriteState(s);e.storageValue=r,e.persisted=!bt(r)}const n=s&&!bt(r)?Qa(r):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,n[e],this.props[e]):e in n&&this._setCrossTabFeatureFlagChangesPending(e,!0)})}catch(e){}}_mergePendingCrossTabFeatureFlagChanges(e,t){const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!i)return t;if(!0===i)return this.props[e];if("$active_feature_flags"===e){const s=new Set(_t(t)?t:[]),r=new Set(_t(this.props[e])?this.props[e]:[]);return i.forEach(e=>r.has(e)?s.add(e):s.delete(e)),Array.from(s)}const s=gt(t)?ls({},t):{},r=gt(this.props[e])?this.props[e]:{};return i.forEach(e=>{e in r?s[e]=r[e]:delete s[e]}),s}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(!Wa(e))return;const s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0===s)return;let r=t;if(this._splitStorageEligible)try{var n;const t=this._splitStorage?null===(n=ga(e))||void 0===n?void 0:n.storageGroup:void 0,i=t?this._groupEntryName(t):this._name;r=Qa(Qn._get(i))[e]}catch(e){}const o=new Set(s||[]);if("$active_feature_flags"===e){if(!ft(t)&&!_t(t)||!ft(r)&&!_t(r)||!_t(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(t||[]),n=new Set(r||[]),a=new Set(i);new Set([...s,...a]).forEach(e=>{s.has(e)!==a.has(e)&&o.add(e)}),o.forEach(e=>{n.has(e)===a.has(e)&&o.delete(e)})}else{if(!gt(i))return void(Ka(r,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));{if(!ft(t)&&!gt(t)||ft(t)&&vt(i)&&ft(r))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=gt(t)?t:{},n=gt(r)?r:{};new Set([...Object.keys(s),...Object.keys(i)]).forEach(e=>{e in s==e in i&&Ka(s[e],i[e])||o.add(e)}),o.forEach(e=>{e in n==e in i&&Ka(n[e],i[e])&&o.delete(e)})}}o.size?this._setCrossTabFeatureFlagChangesPending(e,o):this._pendingCrossTabFeatureFlagChanges.delete(e)}_saveDebounceMs(){var e;const t=null===(e=this._config)||void 0===e?void 0:e.persistence_save_debounce_ms;return wt(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{const t=to(e,this._config.cookie_persisted_properties||[]),i=so(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=Gn._get(this._name)||void 0;r&&no(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{const e=Gn._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=e?no(this._name,e):void 0,this._lastSeenMainCookieValue=e}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t=!1){if(this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;let i;try{i=Gn._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;const s=no(this._name,i);let c;try{c=eo(JSON.parse(i))}catch(e){return!1}if((Gn._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=i;const p=ro(this._name,i),v=[...Yn,...p.properties],f={};if(Object.keys(c).forEach(e=>{const t=c[e];(ft(t)||bt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t)&&(f[e]=!0,delete c[e])}),vt(c))return!1;const m="distinct_id"in c||"anonymous"===c.$user_state||"identified"===c.$user_state,y=this.props,S=y[b],w=y[pe],C=xn({},y);[...Yn,...e.cookie_persisted_properties||[]].forEach(e=>{if(-1!==v.indexOf(e)&&!(e in c)&&!f[e]&&(m||"distinct_id"!==e&&"$user_state"!==e)){const t=C[e];(p.isValid||-1===Yn.indexOf(e)||!1!==t&&0!==t)&&delete C[e]}}),this.props=xn(C,c),ja.forEach(e=>{const t=e in this.props;e in y===t&&Ka(y[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,y[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))}),!m||"$user_state"in c||"$user_state"in this.props||this._setProp(pe,Le);const k=this.props[b],P=this.props[pe];return!m||k===S&&P===w||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,co._set(Ua(this._name),!0),this._deleteProp(h),this._deleteProp(r),this._deleteProp(u),this._deleteProp(n),this._deleteProp(g),this._deleteProp(l),this._deleteProp(a),this._deleteProp(o),this._deleteProp(_),"anonymous"!==P||"identified"!==w&&"anonymous"!==c.$user_state&&(ft(S)||k===S)||(Ja(this.props,c),this._deleteProp(d)),"identified"===P?this.props.$user_id=k:delete this.props.$user_id,this._deleteProp(E)),!0}consumeCookieIdentityChange(){const e=Ua(this._name),t=this._cookieIdentityChangePending||!!co._get(e);return this._cookieIdentityChangePending=!1,t&&co._remove(e),t}_beginCookieSyncSuppression(e=!1){return!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[za],this._writeNow(!0))}_endCookieSyncSuppression(e=!0){if(this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===qa.indexOf(e.persistence.toLowerCase())&&(En.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((e=[],t=!1,i=()=>!1)=>{const s=[...Yn,...e];return ls(ls({},Qn),{},{_parse(e){try{let n,o={};try{n=Gn._get(e)||void 0,o=n?eo(JSON.parse(n)):{}}catch(e){}const a=JSON.parse(Qn._get(e)||"{}");let l;if(t){const t=ro(e,n),i=[...Yn,...t.properties],c={};Object.keys(o).forEach(e=>{const t=o[e];bt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t||(c[e]=t)});const u="distinct_id"in c||"anonymous"===c.$user_state||"identified"===c.$user_state;if(Object.keys(c).length>0){var r;const e=a[b],n=null!==(r=a.$user_state)&&void 0!==r?r:Le;s.forEach(e=>{if(-1!==i.indexOf(e)&&!(e in o)&&(u||"distinct_id"!==e&&"$user_state"!==e)){const i=a[e];(t.isValid||-1===Yn.indexOf(e)||!1!==i&&0!==i)&&delete a[e]}}),!u||"$user_state"in o||"$user_state"in a||(a[pe]=Le),!u||("distinct_id"in c?c[b]:a[b])===e&&("$user_state"in c?c[pe]:a[pe])===n||(Jn.forEach(e=>delete a[e]),"identified"===c.$user_state&&"distinct_id"in c?a.$user_id=c[b]:delete a.$user_id,"identified"!==c.$user_state&&(delete a[te],delete a[d]),delete a.__alias)}l=xn(a,c)}else l=xn(o,a);return i()||Qn._set(e,l),l}catch(e){}return null},_set(i,s,r,n,o,a){const l=Qn._set(i,s,void 0,void 0,a);try{const c=to(s,e);if(Object.keys(c).length){if(t){const t=Zn(i),u=so(c,e);if(Gn._set(t,u,r,n,o,a),Gn._get(t)!==JSON.stringify(u)){Gn._remove(t,n);const e=to(s);return Gn._set(i,e,r,n,o,a),l}}Gn._set(i,c,r,n,o,a)}}catch(e){Qn._error(e)}return l},_remove(e,t){try{null==je||je.localStorage.removeItem(e),Gn._remove(e,t),Gn._remove(Zn(e),t)}catch(e){Qn._error(e)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this._disabled);let i,s=!1,r=!1;const n=e.persistence.toLowerCase();return"localstorage"===n&&Qn._is_supported()?(i=Qn,r=!0):"localstorage+cookie"===n&&t._is_supported()?(i=t,r=!0,s=!0):"sessionstorage"===n&&co._is_supported()?i=co:"memory"===n?i=ao:"cookie"===n&&Gn._is_supported()?(i=Gn,s=!0):t._is_supported()?(i=t,r=!0,s=!0):Gn._is_supported()?(i=Gn,s=!0):i=ao,this._splitStorageEligible=r,this._storesIdentityInCookie=s,i}_groupEntryName(e){return`${this._name}__${e}`}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){const e={};return Pn(this.props,(t,i)=>{const s=ga(i);if(!s||"event"===s.exposure){var r;if(null==s||null===(r=s.shouldSkipFromEventProperties)||void 0===r?void 0:r.call(s,t))return;e[i]=t}}),e}load(e=!1){if(this._disabled&&!e)return;const t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?Qn._parse(this._name):null;let s={};if(t)try{s=eo(Gn._parse(this._name)),Pn(s,(e,t)=>{(ft(e)||bt(e)||""===e)&&delete s[t]})}catch(e){}const r=this._storage._parse(this._name);if(r&&(this.props=xn({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,o;const e=null==i?void 0:i[b],t=null!==(n=null==i?void 0:i.$user_state)&&void 0!==n?n:Le,a=r[b],l=null!==(o=r.$user_state)&&void 0!==o?o:Le;if(a!==e||l!==t){this._cookieIdentityChangePending=!0,this._disabled||co._set(Ua(this._name),!0);const i=xn({},this.props);Jn.forEach(e=>delete i[e]),"anonymous"!==l||"identified"!==t&&"anonymous"!==s.$user_state&&(ft(e)||a===e)||(Ja(i,s),delete i[d]),this.props=i;const r=new Set;Jn.forEach(e=>{var t;const i=null===(t=ga(e))||void 0===t?void 0:t.storageGroup;i&&r.add(i)}),r.forEach(e=>{if(this._disabled)return;const t={};Pn(this.props,(i,s)=>{var r;(null===(r=ga(s))||void 0===r?void 0:r.storageGroup)===e&&(t[s]=i)}),vt(t)?(Qn._remove(this._groupEntryName(e)),this._slotState[e]={}):Qn._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})})}}co._get(Ua(this._name))&&(this._cookieIdentityChangePending=!0)}_loadGroupEntries(){for(const e of ha){const t=Qn._parse(this._groupEntryName(e));if(t&&!vt(t)){const i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||xn(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some(t=>{var i;return(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e})}_groupEntryIsStale(e,t){const i=Ba[e];if(!i)return!1;const s=t[i],r=this.props[i];return wt(s)&&wt(r)&&r>s}refreshKey(e){var t;if(this._disabled)return;if(this._metaIdentifierChangePending.has(e))return;const i=this._splitStorage?null===(t=ga(e))||void 0===t?void 0:t.storageGroup:void 0,s=i?Qn._parse(this._groupEntryName(i)):this._storage._parse(this._name);if(s&&e in s)this._setProp(e,s[e],!1);else{if(i){const t=this._storage._parse(this._name);if(t&&e in t)return void this._setProp(e,t[e],!1)}this._deleteProp(e,!1)}}save(){if(this._disabled)return;const e=this._saveDebounceMs();e>0?ft(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout(()=>{this._pendingSaveTimer=void 0,this._writeNow()},e)):this._writeNow()}flush(){ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e=!1){if(this._disabled||this._cookieSyncSuppressed&&!e)return;e||(this.syncCookieProperties(),this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase()||Va.forEach(e=>this.refreshKey(e)));const t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);const i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)return void(this._config.debug&&En.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()));const s=this._writeEntry(this._storage,this._name,this.props,za);"written"===s&&this._rememberCurrentCookieProperties(this.props),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear()),i&&this._crossTabFeatureFlagHandlers.forEach(e=>e())}_writeNowSplit(){const{main:e,groups:t}=this._partitionProps(),i=this._writeEntry(this._storage,this._name,e,za);"written"===i&&this._rememberCurrentCookieProperties(e),"failed"!==i&&(this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear(),ja.forEach(e=>{var t;(null===(t=ga(e))||void 0===t?void 0:t.storageGroup)||this._pendingCrossTabFeatureFlagChanges.delete(e)}));for(const e of ha){var s;const i=t[e];if(vt(i)&&!(null===(s=this._slotState[e])||void 0===s?void 0:s.persisted)){ja.forEach(t=>{var i;(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e&&this._pendingCrossTabFeatureFlagChanges.delete(t)});continue}const r=this._writeEntry(Qn,this._groupEntryName(e),i,e);"failed"!==r&&ja.forEach(t=>{const i=ga(t);(null==i?void 0:i.storageGroup)!==e||"written"!==r&&i.volatile||this._pendingCrossTabFeatureFlagChanges.delete(t)})}}_partitionProps(){const e={},t={flags:{},surveys:{}};return Pn(this.props,(i,s)=>{var r;const n=null===(r=ga(s))||void 0===r?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i}),{main:e,groups:t}}_entryFingerprint(e,t){if(t===za)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;const i={};return Pn(e,(e,t)=>{var s;i[t]=(null===(s=ga(t))||void 0===s?void 0:s.volatile)?"__volatile__":e}),JSON.stringify(i)}_writeEntry(e,t,i,s){const r=this._slotWriteState(s);if(s!==za&&!r.dirty&&!ft(r.fingerprint))return"skipped";let n;try{if(n=this._entryFingerprint(i,s),n===r.fingerprint)return r.dirty=!1,"skipped"}catch(e){n=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(r.dirty=!1,s!==za&&(r.persisted=!0),ft(n)||(r.fingerprint=n),this._splitStorageEligible&&(r.storageValue=Qn._get(t)),"written"):(this._config.debug&&En.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this._markAllCrossTabFeatureFlagChangesPending(),ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!e&&this._ownsSplitStorage)for(const e of ha)Qn._remove(this._groupEntryName(e));e?delete this._slotState[za]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(gt(e)){this.syncCookieProperties(),ft(t)&&(t="None"),this._expire_days=ft(i)?this._default_expiry:i;let s=!1;if(Pn(e,(e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this._setProp(i,e),s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(gt(e)){this.syncCookieProperties(),this._expire_days=ft(t)?this._default_expiry:t;let i=!1;if(Pn(e,(t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||gt(t)||_t(t))&&(this._setProp(s,t),i=!0)}),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t="string"==typeof e?[e]:e;let i=!1;for(const e of t)e in this.props&&(this._deleteProp(e),i=!0);i&&this.save()}update_campaign_params(){const e=null==Ge?void 0:Ge.URL;if(e===this._campaign_params_url)return;const t=Ia(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!vt(Tn(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}update_search_keyword(){this.register(function(){const e=null==Ge?void 0:Ge.referrer;return e?Ra(e):{}}())}update_referrer_info(){var e;this.register_once({$referrer:Oa(),$referring_domain:(null==Ge?void 0:Ge.referrer)&&(null===(e=Sa(Ge.referrer))||void 0===e?void 0:e.host)||Aa},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=La(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[ye]:this._storesIdentityInCookie?{r:Ha(e.r),u:e.u?Ha(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Pn([me,fe],t=>{const i=this.props[t];i&&Pn(i,function(t,i){e["$initial_"+lt(i)]=t})});const t=this.props[ye];if(t){const i=function(e,t=!1){const i=Da(e,t),s={};return Pn(i,function(e,t){s[`$initial_${lt(t)}`]=e}),s}(t,this._config.disable_capture_url_hashes);xn(e,i)}return e}safe_merge(e){return Pn(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,i){const s=e.persistence!==t.persistence,r=!((e,t)=>{if(e.length!==t.length)return!1;const i=[...e].sort(),s=[...t].sort();return i.every((e,t)=>e===s[t])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),n=s||r,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!i,l=!!this._disabled&&!a;a||this._syncCookieProperties(t,l),this._config=e,!a&&(s||r||o)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._syncCookieProperties(ls(ls({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),l));const c=n||o?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();const u=this._resolveSplitStorage(e),d=n||u!==this._splitStorage,h=!a&&(d||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(l);this._storageMigrationInProgress=d;try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),d){const e=this.props;this.clear(),this._storage=c,this._splitStorage=u,this.props=e,this.save()}else o&&(this._storage=c,a||(delete this._slotState[za],this._writeNow()))}finally{this._storageMigrationInProgress=!1,h&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){const e=this.props[ye];if(!this._storesIdentityInCookie||!gt(e)||"string"!=typeof e.r)return;const t=Ha(e.r),i="string"==typeof e.u?Ha(e.u):e.u;t===e.r&&i===e.u||this._setProp(ye,ls(ls({},e),{},{r:t,u:i}))}set_disabled(e){this._disabled=e,this._disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this._cross_subdomain&&(this._cross_subdomain=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this._secure&&(this._secure=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){const i=this.props.__timers||{};i[e]=t,this._setProp(I,i),this.save()}remove_event_timer(e){const t=this.props.__timers||{},i=t[e];return ft(i)||(delete t[e],this._setProp(I,t),this.save()),i}get_property(e){return this.props[e]}set_property(e,t){this._setProp(e,t),this.save()}_setProp(e,t,i=!0){var s;const r=this.props[e];this.props[e]=t,i&&("distinct_id"!==e&&"$user_state"!==e||r===t||(this._localIdentityChangePending=!0),Ga(e)&&!Ka(r,t)&&this._metaIdentifierChangePending.add(e),this._markPendingCrossTabFeatureFlagChanges(e,r,t),(null===(s=ga(e))||void 0===s?void 0:s.volatile)||this._markGroupDirty(e))}_deleteProp(e,t=!0){delete this.props[e],t&&(Wa(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),Ga(e)&&this._metaIdentifierChangePending.add(e),this._markGroupDirty(e))}_markGroupDirty(e){var t;const i=null===(t=ga(e))||void 0===t?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}};const Za={GZipJS:"gzip-js",Base64:"base64"},Xa={Activation:"events",Cancellation:"cancelEvents"},el={Button:"button",Tab:"tab",Selector:"selector"},tl={TopLeft:"top_left",TopRight:"top_right",TopCenter:"top_center",MiddleLeft:"middle_left",MiddleRight:"middle_right",MiddleCenter:"middle_center",Left:"left",Center:"center",Right:"right",NextToTrigger:"next_to_trigger"},il={Top:"top",Left:"left",Right:"right",Bottom:"bottom"},sl={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},rl={Open:"open",MultipleChoice:"multiple_choice",SingleChoice:"single_choice",Rating:"rating",Link:"link"},nl={NextQuestion:"next_question",End:"end",ResponseBased:"response_based",SpecificQuestion:"specific_question"},ol={Once:"once",Recurring:"recurring",Always:"always"},al={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},ll={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},cl={Popover:"popover",Inline:"inline"};function ul(e){let t=!0;return{dispose(){if(t){t=!1;const i=e();i&&pt(i.then)&&i.then(void 0,()=>{})}}}}const dl={backgroundColor:"#ffffff",textColor:"#1d1f27",buttonColor:"#1d1f27",borderRadius:8,buttonBorderRadius:6,borderColor:"#e5e7eb",fontFamily:"system-ui",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",showOverlay:!0,whiteLabel:!1,dismissOnClickOutside:!0,zIndex:2147483646},hl={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},_l={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},pl=Cn("[RateLimiter]");var gl=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{const t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach(e=>{pl.info(`${e||"events"} is quota limited.`),this.serverLimits[e]=(new Date).getTime()+6e4})}catch(e){return void pl.warn(`could not rate limit - continuing. Error: "${null==e?void 0:e.message}"`,{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null===(e=this.instance.config.rate_limiting)||void 0===e?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null===(e=this.instance.config.rate_limiting)||void 0===e?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var t,i,s;const{captureEventsBurstLimit:r,captureEventsPerSecond:n}=this,o=(new Date).getTime(),a=null!==(t=null===(i=this.instance.persistence)||void 0===i?void 0:i.get_property("$capture_rate_limit"))&&void 0!==t?t:{tokens:r,last:o};a.tokens+=(o-a.last)/1e3*n,a.last=o,a.tokens>r&&(a.tokens=r);const l=1>a.tokens;if(l||e||(a.tokens=Math.max(0,a.tokens-1)),l&&!e){const e=(wt(a.dropped)?a.dropped:0)+1;a.dropped=e,!this.lastEventRateLimited&&this._captureWarning(e)&&(a.dropped=0)}return this.lastEventRateLimited=l,null===(s=this.instance.persistence)||void 0===s||s.set_property("$capture_rate_limit",a),{isRateLimited:l,remainingTokens:a.tokens}}_isPropertyAllowed(e){const t=this.instance.config.property_denylist;return!_t(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&(null==Ke?void 0:Ke.pathname))return`${null!==(e=Ke.origin)&&void 0!==e?e:""}${Ke.pathname}`}_captureWarning(e){var t,i;const{captureEventsBurstLimit:s,captureEventsPerSecond:r}=this,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null===(t=(i=this.instance).get_session_id)||void 0===t?void 0:t.call(i):void 0,a=[`${e} event(s) dropped since the last warning`,n?`triggered on ${n}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${r} events per second and ${s} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()<t}};const vl=Cn("[RemoteConfig]");var fl=class{constructor(e){this._instance=e}get remoteConfig(){var e;return null===(e=tt._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.config}_loadRemoteConfigJs(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.loadExternalDependency)?null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return vl.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void vl.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs(e=>{if(!e)return vl.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON(e=>{this._onRemoteConfig(e.json,e)});this._onRemoteConfig(e)})}catch(e){vl.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||vl.warn("Failed to fetch remote config from PostHog."):vl.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){vl.error("Error applying remote config",e)}if(!1!==(null==e?void 0:e.hasFeatureFlags)&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;null===(i=this._instance.featureFlags)||void 0===i||i.ensureFlagsLoaded()}catch(e){vl.error("Error loading feature flags",e)}}};const ml=["fatal","error","warning","log","info","debug"];var yl=Uint8Array,bl=Uint16Array,Sl=Uint32Array,wl=new yl([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),El=new yl([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Cl=new yl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),kl=function(e,t){for(var i=new bl(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var r=new Sl(i[30]);for(s=1;30>s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},Pl=kl(wl,2),xl=Pl[1];Pl[0][28]=258,xl[258]=28;for(var Fl=kl(El,0)[1],Il=new bl(32768),Tl=0;32768>Tl;++Tl){var Rl=(43690&Tl)>>>1|(21845&Tl)<<1;Il[Tl]=((65280&(Rl=(61680&(Rl=(52428&Rl)>>>2|(13107&Rl)<<2))>>>4|(3855&Rl)<<4))>>>8|(255&Rl)<<8)>>>1}var $l=function(e,t,i){for(var s=e.length,r=0,n=new bl(t);s>r;++r)++n[e[r]-1];var o,a=new bl(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new bl(1<<t);var l=15-t;for(r=0;s>r;++r)if(e[r])for(var c=r<<4|e[r],u=t-e[r],d=a[e[r]-1]++<<u,h=d|(1<<u)-1;h>=d;++d)o[Il[d]>>>l]=c}else for(o=new bl(s),r=0;s>r;++r)o[r]=Il[a[e[r]-1]++]>>>15-e[r];return o},Ml=new yl(288);for(Tl=0;144>Tl;++Tl)Ml[Tl]=8;for(Tl=144;256>Tl;++Tl)Ml[Tl]=9;for(Tl=256;280>Tl;++Tl)Ml[Tl]=7;for(Tl=280;288>Tl;++Tl)Ml[Tl]=8;var Al=new yl(32);for(Tl=0;32>Tl;++Tl)Al[Tl]=5;var Ol=$l(Ml,9,0),Ll=$l(Al,5,0),Dl=function(e){return(e/8|0)+(7&e&&1)},Nl=function(e,t,i){(null==t||0>t)&&(t=0),(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof bl?bl:e instanceof Sl?Sl:yl)(i-t);return s.set(e.subarray(t,i)),s},Bl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},ql=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},Ul=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new yl(0),0];if(1==r){var o=new yl(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort(function(e,t){return e.f-t.f}),i.push({s:-1,f:25001});var a=i[0],l=i[1],c=0,u=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=i[i[d].f>i[c].f?c++:d++],l=i[c!=u&&i[d].f>i[c].f?c++:d++],i[u++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(s=1;r>s;++s)n[s].s>h&&(h=n[s].s);var _=new bl(h+1),p=Hl(i[u-1],_,0);if(p>t){s=0;var g=0,v=p-t,f=1<<v;for(n.sort(function(e,t){return _[t.s]-_[e.s]||e.f-t.f});r>s;++s){var m=n[s].s;if(t>=_[m])break;g+=f-(1<<p-_[m]),_[m]=t}for(g>>>=v;g>0;){var y=n[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=n[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new yl(_),p]},Hl=function(e,t,i){return-1==e.s?Math.max(Hl(e.l,t,i+1),Hl(e.r,t,i+1)):t[e.s]=i},zl=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new bl(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},jl=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},Wl=function(e,t,i){var s=i.length,r=Dl(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},Vl=function(e,t,i,s,r,n,o,a,l,c,u){Bl(t,u++,i),++r[256];for(var d=Ul(r,15),h=d[0],_=d[1],p=Ul(n,15),g=p[0],v=p[1],f=zl(h),m=f[0],y=f[1],b=zl(g),S=b[0],w=b[1],E=new bl(19),C=0;m.length>C;++C)E[31&m[C]]++;for(C=0;S.length>C;++C)E[31&S[C]]++;for(var k=Ul(E,7),P=k[0],x=k[1],F=19;F>4&&!P[Cl[F-1]];--F);var I,T,R,M,A=c+5<<3,O=jl(r,Ml)+jl(n,Al)+o,L=jl(r,h)+jl(n,g)+o+14+3*F+jl(E,P)+(2*E[16]+3*E[17]+7*E[18]);if(O>=A&&L>=A)return Wl(t,u,e.subarray(l,l+c));if(Bl(t,u,1+(O>L)),u+=2,O>L){I=$l(h,_,0),T=h,R=$l(g,v,0),M=g;var D=$l(P,x,0);for(Bl(t,u,y-257),Bl(t,u+5,w-1),Bl(t,u+10,F-4),u+=14,C=0;F>C;++C)Bl(t,u+3*C,P[Cl[C]]);u+=3*F;for(var N=[m,S],B=0;2>B;++B){var q=N[B];for(C=0;q.length>C;++C)Bl(t,u,D[U=31&q[C]]),u+=P[U],U>15&&(Bl(t,u,q[C]>>>5&127),u+=q[C]>>>12)}}else I=Ol,T=Ml,R=Ll,M=Al;for(C=0;a>C;++C)if(s[C]>255){var U;ql(t,u,I[257+(U=s[C]>>>18&31)]),u+=T[U+257],U>7&&(Bl(t,u,s[C]>>>23&31),u+=wl[U]);var H=31&s[C];ql(t,u,R[H]),u+=M[H],H>3&&(ql(t,u,s[C]>>>5&8191),u+=El[H])}else ql(t,u,I[s[C]]),u+=T[s[C]];return ql(t,u,I[256]),u+T[256]},Gl=new Sl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Kl=new yl(0),Ql=function(){for(var e=new Sl(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),Jl=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function Yl(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p(t){for(var i=e,s=0;t.length>s;++s)i=Ql[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,c,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new yl(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),c=0;if(!t||8>o)for(var u=0;o>=u;u+=65535){var d=u+65535;o>d?c=Wl(l,c,e.subarray(u,d)):(l[u]=n,c=Wl(l,c,e.subarray(u,o)))}else{for(var h=Gl[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,v=new bl(32768),f=new bl(g+1),m=Math.ceil(i/3),y=2*m,b=function(t){return(e[t]^e[t+1]<<m^e[t+2]<<y)&g},S=new Sl(25e3),w=new bl(288),E=new bl(32),C=0,k=0,P=(u=0,0),x=0,F=0;o>u;++u){var I=b(u),T=32767&u,R=f[I];if(v[T]=R,f[I]=T,u>=x){var M=o-u;if((C>7e3||P>24576)&&M>423){c=Vl(e,l,0,S,w,E,k,P,F,u-F,c),P=C=k=0,F=u;for(var A=0;286>A;++A)w[A]=0;for(A=0;30>A;++A)E[A]=0}var O=2,L=0,D=p,N=T-R&32767;if(M>2&&I==b(u-N))for(var B=Math.min(_,M)-1,q=Math.min(32767,u),U=Math.min(258,M);q>=N&&--D&&T!=R;){if(e[u+O]==e[u+O-N]){for(var H=0;U>H&&e[u+H]==e[u+H-N];++H);if(H>O){if(O=H,L=N,H>B)break;var z=Math.min(N,H-2),j=0;for(A=0;z>A;++A){var W=u-N+A+32768&32767,V=W-v[W]+32768&32767;V>j&&(j=V,R=W)}}}N+=(T=R)-(R=v[T])+32768&32767}if(L){S[P++]=268435456|xl[O]<<18|Fl[L];var G=31&xl[O],K=31&Fl[L];k+=wl[G]+El[K],++w[257+G],++E[K],x=u+O,++C}else S[P++]=e[u],++w[e[u]]}}c=Vl(e,l,n,S,w,E,k,P,F,u-F,c),n||(c=Wl(l,c,Kl))}return Nl(a,0,s+Dl(c)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l,!c)),d=u.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=2>t.level?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&Jl(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var s=0;i.length>=s;++s)e[s+10]=i.charCodeAt(s)}}(u,t),Jl(u,d-8,i.d()),Jl(u,d-4,s),u}const Zl=!!Je||!!Qe,Xl=new WeakMap,ec="text/plain";let tc=0,ic=!1;const sc=(e,t)=>{const[i,s]=e.split("#"),[r,n]=i.split("?");if(!n)return e;const o=n.split("&").filter(e=>e.split("=")[0]!==t).join("&");return`${r}${o?`?${o}`:""}${s?`#${s}`:""}`},rc=(e,t,i=!0)=>{var s;const[r,n]=e.split("?"),o=ls({},t),a=null!==(s=null==n?void 0:n.split("&").map(e=>{var t;const[s,r]=e.split("="),n=i&&null!==(t=o[s])&&void 0!==t?t:r;return delete o[s],`${s}=${n}`}))&&void 0!==s?s:[],l=function(e,t="&"){let i,s;const r=[];return Pn(e,function(e,t){ft(e)||ft(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)}),r.join(t)}(o);return l&&a.push(l),a.length>0?`${r}?${a.join("&")}`:r},nc=e=>{if(e._encodedBody)return e._encodedBody;const{data:t,compression:i}=e;if(!t)return;if(i===Za.GZipJS){const e=Yl(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new yl(e.length+(e.length>>>1)),s=0,r=function(e){i[s++]=e},n=0;t>n;++n){if(s+5>i.length){var o=new yl(s+8+(t-n<<1));o.set(i),i=o}var a=e.charCodeAt(n);128>a?r(a):2048>a?(r(192|a>>>6),r(128|63&a)):a>55295&&57344>a?(r(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++n))>>>18),r(128|a>>>12&63),r(128|a>>>6&63),r(128|63&a)):(r(224|a>>>12),r(128|a>>>6&63),r(128|63&a))}return Nl(i,0,s)}(ba(t)),{mtime:0});return{contentType:ec,body:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),estimatedSize:e.byteLength}}if(i===Za.Base64){const e=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))):e}(ba(t)),i=(e=>"data="+encodeURIComponent("string"==typeof e?e:ba(e)))(e);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const s=ba(t);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}},oc=e=>{const t=()=>"sendBeacon"===e.transport?{url:rc(e.url,{compression:Za.Base64}),encodedBody:nc(ls(ls({},e),{},{compression:Za.Base64,_encodedBody:void 0}))}:{url:sc(e.url,"compression"),encodedBody:nc(ls(ls({},e),{},{compression:void 0,_encodedBody:void 0}))};let i;try{i=nc(e)}catch(i){if(or(e.compression,wa(e.url,"compression")))return En.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return i&&or(e.compression,wa(e.url,"compression"))&&!((s=i.body)instanceof ArrayBuffer?nr(new Uint8Array(s)):ArrayBuffer.isView(s)&&nr(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(ic=!0,t()):{url:e.url,encodedBody:i};var s},ac=e=>{try{return oc(e)}catch(i){var t;return En.error(i),void(null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0,error:i}))}},lc=function(){var e=Lt(function*(e){const t=yield function(e){return hr.apply(this,arguments)}(ba(e.data),i.DEBUG,{rethrow:!0});if(!t)return e;const s=yield t.arrayBuffer();return ls(ls({},e),{},{_encodedBody:{contentType:ec,body:s,estimatedSize:s.byteLength}})});return function(t){return e.apply(this,arguments)}}(),cc=/Failed to fetch|NetworkError|Load failed/i,uc=e=>"TypeError"===(null==e?void 0:e.name)&&cc.test((null==e?void 0:e.message)||""),dc=e=>{try{const t=function(e,t=Date.now()){if("string"!=typeof e||!e)return;const i=e.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){const e=1e3*Math.min(Number(s),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;const r=/^\w{3} \w{3} /.test(s)?s+" GMT":s,n=Date.parse(r)-t;return Number.isFinite(n)&&n>0?Math.min(n,Qi):void 0}(e());return ft(t)?void 0:Math.min(t,3e4)}catch(e){return}},hc=e=>{const t=ac(e);if(!t)return;const i=new Je;Xl.set(i,!0);const{url:s,encodedBody:r}=t;i.open(e.method||"GET",s,!0);const{contentType:n,body:o}=null!=r?r:{};Pn(e.headers,function(e,t){i.setRequestHeader(t,e)}),n&&i.setRequestHeader("Content-Type",n),e.timeout&&(i.timeout=e.timeout),i.onreadystatechange=()=>{if(4===i.readyState){var t;const s={statusCode:i.status,text:i.responseText};if(200===i.status)try{s.json=JSON.parse(i.responseText)}catch(e){}null===(t=e.callback)||void 0===t||t.call(e,s,dc(()=>i.getResponseHeader("Retry-After")))}},i.send(o)},_c=e=>{const t=ac(e);if(!t)return;const{url:i,encodedBody:s}=t,{contentType:r,body:n,estimatedSize:o}=null!=s?s:{},a=new Headers;Pn(e.headers,function(e,t){a.append(t,e)}),r&&a.append("Content-Type",r);let l=null,c=!1;if(Ye){const t=new Ye;l={signal:t.signal,timeout:setTimeout(()=>{c=!0;try{t.abort(Xi("AbortError","PostHog request timed out"+((i=e.timeout)?` after ${i}ms`:"")))}catch(e){d(e)}var i},e.timeout)}}let u=!1;const d=t=>{var i;u||(u=!0,c&&"AbortError"===(null==t?void 0:t.name)||uc(t)?En.warn(t):En.error(t),null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))};let h=0;const _=()=>{tc-=h,h=0,l&&clearTimeout(l.timeout)};try{const t=ls({method:(null==e?void 0:e.method)||"GET",headers:a,referrerPolicy:"strict-origin",body:n,signal:null==l?void 0:l.signal},e.fetchOptions),s=null!=o?o:ft(n)?0:void 0;t.keepalive="POST"===t.method&&!e._keepaliveDisabled&&!1!==t.keepalive&&t.body===n&&!ft(s)&&s>=0&&52428.8>tc+s,t.keepalive&&(h=s,tc+=h),Qe(i,t).then(t=>t.text().then(i=>{var s;if(u)return;const r={statusCode:t.status,text:i};if(200===t.status)try{r.json=JSON.parse(i)}catch(e){En.error(e)}u=!0,_(),null===(s=e.callback)||void 0===s||s.call(e,r,dc(()=>t.headers.get("Retry-After")))})).catch(e=>{_(),d(e)}).finally(_)}catch(e){_(),d(e)}},pc=e=>{try{var t;const{url:i,encodedBody:s}=oc(e),{contentType:r,body:n,estimatedSize:o}=null!=s?s:{};if(!n)return;const a=n instanceof Blob?n:new Blob([n],{type:r});if(Ve.sendBeacon(i,a))return;const l=_t(e.data)?e.data:null===(t=e.data)||void 0===t?void 0:t.batch;if(_t(l)&&l.length>1&&(null!=o?o:0)>16384){const t=Math.ceil(l.length/2),i=t=>_t(e.data)?t:ls(ls({},e.data),{},{batch:t});return pc(ls(ls({},e),{},{data:i(l.slice(0,t))})),void pc(ls(ls({},e),{},{data:i(l.slice(t))}))}En.warn(`Beacon of ~${null!=o?o:0} bytes was rejected by the browser, falling back to ${Qe?"fetch":"XHR"}`),Qe?_c(ls(ls({},e),{},{_keepaliveDisabled:!0})):hc(e)}catch(e){En.warn("Beacon send failed",e)}},gc=(e,t,i,s)=>{const r="query"===s?"POST"===t?"sent_at":"_":void 0;return rc(i===Za.GZipJS?sc(e,"compression"):e,ls(ls({},r?{[r]:Date.now().toString()}:{}),i===Za.GZipJS?{}:{compression:i}))},vc=(()=>{const e=[];return Qe&&e.push({transport:"fetch",method:_c}),Je&&e.push({transport:"XHR",method:hc}),(null==Ve?void 0:Ve.sendBeacon)&&e.push({transport:"sendBeacon",method:pc}),e})();let fc=!Zl&&-1===(null==Xe?void 0:Xe.indexOf("MSIE"))&&-1===(null==Xe?void 0:Xe.indexOf("Mozilla"));function mc(e,t,i){var s,r,n;i&&(t=ls(ls({},t),{},{callback:e=>i(e)})),e.__loaded?fc?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&(null===(r=t.callback)||void 0===r||r.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=ls(ls({},e.config.request_headers),t.headers),t.compression="best-available"===t.compression?null!==(s=e.compression)&&void 0!==s?s:t.compressionFallback:t.compression,(ft(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((e,t)=>{var i,s,r;const n=ls(ls({},e),{},{callback:null!=t?t:t=>{var i;return null===(i=e.callback)||void 0===i?void 0:i.call(e,t)}});n.timeout=n.timeout||6e4;const o=null!==(i=n.transport)&&void 0!==i?i:"fetch";"sendBeacon"===o&&ft(n.compression)&&n.data&&(n.compression=Za.Base64),"POST"===n.method&&n.data&&("capture-body"===n.timestampMode?n.data=(e=>{var t,i;const s=(_t(e)?e:[e]).map(e=>ls(ls({},e),e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{})),r=s[0];return{api_key:null!==(t=null==r||null===(i=r.properties)||void 0===i?void 0:i.token)&&void 0!==t?t:null==r?void 0:r.token,batch:s,sent_at:(new Date).toISOString()}})(n.data):"body"===n.timestampMode&&(n.data=((e,t=(new Date).toISOString())=>_t(e)?e.map(e=>ls(ls({},e),{},{sent_at:t})):ls(ls({},e),{},{sent_at:t}))(n.data))),n.url=gc(n.url,n.method,n.compression,n.timestampMode);const a=vc.filter(e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport)),l=null!==(s=null===(r=function(e,t){for(let i=0;e.length>i;i++)if(t(e[i]))return e[i]}(a,e=>e.transport===o))||void 0===r?void 0:r.method)&&void 0!==s?s:a[0].method;if(!l)throw new Error("No available transport method");const c=e=>{try{l(e)}catch(e){var t;uc(e)?En.warn(e):En.error(e),null===(t=n.callback)||void 0===t||t.call(n,{statusCode:0,error:e})}};"sendBeacon"!==o&&!n.preferSyncCompression&&n.data&&n.compression===Za.GZipJS&&Ze&&"undefined"!=typeof Promise&&!ic?lc(n).then(e=>{c(e)}).catch(t=>{if(ar(t))return ic=!0,void c(ls(ls({},n),{},{compression:void 0,url:gc(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;const t="name"in e?String(e.name):"";return ar(e)||t===rr})(t)&&(ic=!0),c(n)}):c(n)})(t,(s,r)=>{var n,o,a;e.rateLimiter.checkForLimiting(s),400>s.statusCode||null===(n=(o=e.config).on_request_error)||void 0===n||n.call(o,s),i?i(s,r):null===(a=t.callback)||void 0===a||a.call(t,s)})):t.fireCallbackOnDrop&&(null===(n=t.callback)||void 0===n||n.call(t,{statusCode:0}))}var yc=class{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=qt((null==t?void 0:t.flush_interval_ms)||3e3,250,5e3,En.createLogger("flush interval"),3e3),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();const e=this._queue.length>0?this._formatQueue():{},t=Object.values(e);[...t.filter(e=>0===e.url.indexOf("/e")),...t.filter(e=>0!==e.url.indexOf("/e"))].map(e=>{this._sendRequestSafely(ls(ls({},e),{},{callback:void 0}),"sendBeacon")})}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){this._isPaused||(this._flushTimeout=setTimeout(()=>{this._clearFlushTimeout(),this._flush()},this._flushTimeoutMs))}_flush(){if(this._queue.length>0){const e=this._formatQueue();for(const t in e)this._sendRequestSafely(e[t])}}_sendRequestSafely(e,t){try{this._sendRequest(e,t)}catch(e){En.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){const e={},t={};Pn(this._queue,i=>{var s;const r=i,n=((r?r.batchKey:null)||r.url)+(r.batchGroup?`:${r.batchGroup}`:"");ft(e[n])&&(e[n]=ls(ls({},r),{},{data:[],callback:void 0,fireCallbackOnDrop:void 0}),t[n]=[]),null===(s=e[n].data)||void 0===s||s.push(r.data),r.callback&&t[n].push(r.callback)});for(const i in t){const s=t[i];s.length&&(e[i].callback=e=>{for(const t of s)t(e)})}return this._queue=[],e}};const bc=["retriesPerformedSoFar"];var Sc=class{constructor(e){this._instance=e,this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._queue=[],this._areWeOnline=!0,this.resume()}resume(){if(!ft(je)&&"onLine"in je.navigator){if(this._areWeOnline=je.navigator.onLine,this._onlineListener)return;this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},An(je,"online",this._onlineListener),An(je,"offline",this._offlineListener)}}get length(){return this._queue.length}retriableRequest(e,t){let{retriesPerformedSoFar:i}=e,s=_r(e,bc);Et(i)&&(s.url=rc(s.url,{retry_count:i})),mc(this._instance,t?ls(ls({},s),{},{transport:t}):s,(e,t)=>{var r;if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=i?i:0))return void this._enqueue(ls({retriesPerformedSoFar:i},s),t);0===e.statusCode&&En.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${null!=i?i:0} retries.`)}null===(r=s.callback)||void 0===r||r.call(s,e)})}_enqueue(e,t){const i=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=i+1;const s=Math.max(function(e){const t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=(Math.random()-.5)*(s-i);return Math.ceil(s+r)}(i),null!=t?t:0),r=Date.now()+s;this._queue.push({retryAt:r,requestOptions:e});let n=`Enqueued failed request for retry in ${s}`;navigator.onLine||(n+=" (Browser is offline)"),En.warn(n),this._isPolling||(this._isPolling=!0,this._poll())}_poll(){if(this._poller&&clearTimeout(this._poller),0===this._queue.length)return this._isPolling=!1,void(this._poller=void 0);this._poller=setTimeout(()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._poll()},this._pollIntervalMs)}_flush(){const e=Date.now(),t=[],i=this._queue.filter(i=>e>i.retryAt||(t.push(i),!1));if(this._queue=t,i.length>0)for(const{requestOptions:e}of i)this.retriableRequest(e)}unload(){this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,ft(je)||(this._onlineListener&&(je.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(je.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0));for(const{requestOptions:e}of this._queue)try{this._instance._send_request(ls(ls({},e),{},{callback:_t(e.data)?void 0:e.callback,transport:"sendBeacon"}))}catch(e){En.error(e)}this._queue=[]}},wc=class{constructor(e){this._instance=e,this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});const r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)}}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){const e=this._context;return this._context=void 0,setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){An(je,"scroll",this._updateScrollData,{capture:!0}),An(je,"scrollend",this._updateScrollData,{capture:!0}),An(je,"resize",this._updateScrollData)}scrollElement(){if(this._scrollRoot){const t=_t(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(const i of t){var e;const t=null==je||null===(e=je.document)||void 0===e?void 0:e.querySelector(i);if(t)return t}return}var t;return null==je||null===(t=je.document)||void 0===t?void 0:t.documentElement}_scrollPosition(e){var t,i;const s="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){const e=this.scrollElement();return e&&e[s]||0}return je?"y"===e?je.scrollY||je.pageYOffset||(null===(t=je.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.scrollTop)||0:je.scrollX||je.pageXOffset||(null===(i=je.document)||void 0===i||null===(i=i.documentElement)||void 0===i?void 0:i.scrollLeft)||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}};const Ec=e=>La(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties,null==e?void 0:e.config.disable_capture_url_hashes);var Cc=class{constructor(e,t,i,s){this._onSessionIdCallback=e=>{const t=this._getStored();if(t&&t.sessionId===e)return;const i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[ge]:i})},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Ec,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[ge]}getSetOnceProps(){var e;const t=null===(e=this._getStored())||void 0===e?void 0:e.props;return t?"r"in t?Da(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return Pn(Tn(this.getSetOnceProps()),(t,i)=>{"$current_url"===i&&(i="url"),e[`$session_entry_${lt(i)}`]=t}),e}},kc=class{on(e,t){return this._events[e]||(this._events[e]=[]),this._events[e].push(t),()=>{this._events[e]=this._events[e].filter(e=>e!==t)}}emit(e,t){for(const i of this._events[e]||[])i(t);for(const i of this._events["*"]||[])i(e,t)}constructor(){this._events={}}};const Pc=Cn("[SessionId]"),xc=864e5;var Fc=class{on(e,t){return this._eventEmitter.on(e,t)}constructor(e,t,i){var s;if(this._lastPersistedActivityTimestamp=null,this._lastCookieSyncTimestamp=null,this._sessionIdChangedHandlers=[],this._beforeUnloadListener=void 0,this._destroyed=!1,this._eventEmitter=new kc,this._sessionHasBeenIdleTooLong=(e,t)=>!(!Et(e)||!Et(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if("always"===e.config.cookieless_mode)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this._config=e.config,this._persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._pendingBootstrapSession=void 0,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||Hn,this._windowIdGenerator=i||Hn;const r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*qt(this._config.session_idle_timeout_seconds||1800,60,36e3,Pc.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){const e=co._parse(this._window_id_storage_key),t=co._parse(this._primary_window_exists_storage_key);e&&!t?this._windowId=e:co._remove(this._window_id_storage_key),co._set(this._primary_window_exists_storage_key,!0)}(null===(s=this._config.bootstrap)||void 0===s?void 0:s.sessionID)&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return ft(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter(t=>t!==e)}}_canUseSessionStorage(){return"memory"!==this._config.persistence&&!this._persistence._disabled&&co._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&co._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?co._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){const t=this._lastPersistedActivityTimestamp;return!bt(t)&&!bt(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){const s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[K]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e;const t=null===(e=this._config)||void 0===e?void 0:e.persistence_save_debounce_ms;return Et(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(K):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(bt(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this._lastPersistedActivityTimestamp)return;this._refreshSessionIdFromStorage();const[,t,i]=this._getSessionId();t===this._sessionId&&i===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[K]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}_freshestActivityTimestamp(){const[e]=this._getSessionId(),t=Et(e)?e:0,i=Et(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){const e=this._persistence.props[K];return _t(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._lastPersistedActivityTimestamp=null,this._pendingBootstrapSession=void 0,clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._setSessionId(null,null,null)}setBootstrapSessionId(e,t=!1){const i=((e,t=(new Date).getTime())=>{try{const i=(e=>{const t=e.replace(/-/g,"");if(32!==t.length)throw new Error("Not a valid UUID");if("7"!==t[12])throw new Error("Not a UUIDv7");return parseInt(t.substring(0,12),16)})(e);return i>t+6e4?void Pc.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void Pc.error("Invalid sessionID in bootstrap",e)}})(e);return!ft(i)&&(t?this._pendingBootstrapSession={sessionId:e,sessionStartTimestamp:i}:this._setSessionId(e,(new Date).getTime(),i),!0)}destroy(){this._destroyed=!0,this._flushPendingActivityTimestamp(),clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._beforeUnloadListener&&je&&(je.removeEventListener(Be,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&co._remove(this._primary_window_exists_storage_key)},An(je,Be,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,t=null,i=!1){if("always"===this._config.cookieless_mode)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(bt(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null===(n=(o=this._persistence).syncCookieProperties)||void 0===n||n.call(o),this._lastCookieSyncTimestamp=s}let[,a,l]=this._getSessionId();const c=!ft(r)&&a!==r,u=this._freshestActivityTimestamp();let d=this._getWindowId();const h=this._pendingBootstrapSession,_=!!h&&(h.sessionStartTimestamp>s+6e4||s-h.sessionStartTimestamp>xc),p=h?_:Et(l)&&Math.abs(s-l)>xc;let g=!1,v=c,f=!a||!!h;const m=a;let y=!f&&!e&&this._sessionHasBeenIdleTooLong(s,u);if(y&&(y=this._isSessionIdleAfterCrossTabRefresh(s),y||Pc.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,l]=this._getSessionId(),y||(f=!a||!!h)),f||y||p){v=!1;const e=h&&!_;a=e?h.sessionId:this._sessionIdGenerator(),d=this._windowIdGenerator(),Pc.info("new session ID assigned",{sessionId:a,windowId:d,bootstrapped:!!e,changeReason:{noSessionId:f,activityTimeout:y,sessionPastMaximumLength:p}}),l=e?h.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,g=!0}else d||(d=this._windowIdGenerator(),g=!0),v=v||a!==m,v&&(Pc.info("adopted cross-tab session id",{sessionId:a,windowId:d}),g=!0);const b=Et(u)&&e&&!p?u:s,S=Et(l)?l:(new Date).getTime();this._setWindowId(d),this._setSessionId(a,b,S),e||this._resetIdleTimer();const w={noSessionId:f,activityTimeout:y,sessionPastMaximumLength:p,crossTabAdoption:v};return g&&this._sessionIdChangedHandlers.forEach(e=>e(a,d,w)),{sessionId:a,windowId:d,sessionStartTimestamp:S,changeReason:g?w:void 0,lastActivityTimestamp:u}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout(()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){const e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()},1.1*this.sessionTimeoutMs))}};const Ic=function(e,t){if(!e)return!1;const i=e.userAgent;if(i&&Bt(i,t))return!0;try{const i=null==e?void 0:e.userAgentData;if((null==i?void 0:i.brands)&&i.brands.some(e=>Bt(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver};function Tc(){return(Tc=Lt(function*(){const e=null==Ve?void 0:Ve.userAgentData;if(null==e?void 0:e.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return mt(i)&&i.length>0?i:void 0}catch(e){return void En.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function Rc(e,t){let i=`$survey_${t}/${e.id}`;return e.current_iteration&&e.current_iteration>0&&(i=`$survey_${t}/${e.id}/${e.current_iteration}`),i}function $c(e){var t;return!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length)}const Mc=(e,t)=>{if(!(e=>{try{new RegExp(e)}catch(e){return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch(e){return!1}},Ac=e=>e.toLowerCase(),Oc={exact:(e,t)=>t.some(t=>e.some(e=>t===e)),is_not:(e,t)=>t.every(t=>e.every(e=>t!==e)),regex:(e,t)=>t.some(t=>e.some(e=>Mc(t,e))),not_regex:(e,t)=>t.every(t=>e.every(e=>!Mc(t,e))),icontains:(e,t)=>t.map(Ac).some(t=>e.map(Ac).some(e=>t.includes(e))),not_icontains:(e,t)=>t.map(Ac).every(t=>e.map(Ac).every(e=>!t.includes(e))),gt:(e,t)=>t.some(t=>{const i=parseFloat(t);return!isNaN(i)&&e.some(e=>i>parseFloat(e))}),lt:(e,t)=>t.some(t=>{const i=parseFloat(t);return!isNaN(i)&&e.some(e=>i<parseFloat(e))})};function Lc(e,t){return!e||Object.entries(e).every(([e,i])=>{const s=null==t?void 0:t[e];if(null==s)return!1;const r=Oc[i.operator];return!!r&&r(i.values.map(String),[String(s)])})}function Dc(e,t,i){return ba({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}const Nc="custom",Bc="i.posthog.com",qc=/^\/static\//,Uc=["/s/","/e/","/i/"];var Hc=class{constructor(e){this._regionCache={},this.instance=e}get apiHost(){const e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){const e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e;let t=null===(e=this.instance.config.ui_host)||void 0===e?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace(`.${Bc}`,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this._regionCache[this.apiHost]||(this._regionCache[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Nc),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(!qc.test(e))return;const t=this.instance.config.asset_host;return"string"==typeof t&&t.trim().replace(/\/$/,"")||void 0}_urlKey(e){const t=Sa(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;let s=i;const r=this.instance.config.rewriteRequestPath;if(r){var n;const e=(null===(n=Sa(i))||void 0===n?void 0:n.href)||i;s=r(new URL(e)).toString()}if(r&&"api"===e&&Uc.some(e=>0===t.indexOf(e))){const e=this._urlKey(s);if(e){const t=this.apiHost;let i=this._ingestionEndpoints;(null==i?void 0:i.apiHost)===t&&i.rewriteRequestPath===r||(i={apiHost:t,rewriteRequestPath:r,urls:new Set},this._ingestionEndpoints=i),i.urls.add(e)}}return s}isIngestionEndpoint(e){const t=this._ingestionEndpoints,i=this._urlKey(e);return(null==t?void 0:t.apiHost)===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!i&&t.urls.has(i)}endpointFor(e,t=""){if(t&&(t="/"===t[0]?t:`/${t}`),"ui"===e)return this._prepareEndpoint(e,t,this.uiHost+t);if("flags"===e)return this._prepareEndpoint(e,t,this.flagsApiHost+t);if("assets"===e){const i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,`${i}${t}`)}if(this.region===Nc)return this._prepareEndpoint(e,t,this.apiHost+t);const i=Bc+t;switch(e){case"assets":return this._prepareEndpoint(e,t,`https://${this.region}-assets.${i}`);case"api":return this._prepareEndpoint(e,t,`https://${this.region}.${i}`)}}};const zc=Cn("[Surveys]"),jc=e=>{try{const t=(e=>((e,t)=>`seenSurvey_${function(e){return e.current_iteration&&e.current_iteration>0?`${e.id}_${e.current_iteration}`:e.id}(t)}`)(0,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){zc.error("Failed to persist survey seen state",e)}},Wc=[sl.Popover,sl.Widget,sl.API],Vc={ignoreConditions:!1,ignoreDelay:!1,displayType:cl.Popover},Gc=Cn("[PostHog ExternalIntegrations]"),Kc={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var Qc=class{constructor(e){this._instance=e}_loadScript(e,t){var i,s;null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,e,e=>{if(e)return Gc.error("failed to load script",e);t()})}startIfEnabledOrStop(){var e;for(const[r,n]of Object.entries(null!==(e=this._instance.config.integrations)&&void 0!==e?e:{})){var t,i,s;n&&!(null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.integrations)||void 0===t?void 0:t[r])&&this._loadScript(Kc[r],()=>{var e;null===(e=tt.__PosthogExtensions__)||void 0===e||null===(e=e.integrations)||void 0===e||null===(e=e[r])||void 0===e||e.start(this._instance)}),!n&&(null===(i=tt.__PosthogExtensions__)||void 0===i||null===(i=i.integrations)||void 0===i?void 0:i[r])&&(null===(s=tt.__PosthogExtensions__)||void 0===s||null===(s=s.integrations)||void 0===s||null===(s=s[r])||void 0===s||s.stop())}}};const Jc="autocapture",Yc="featureFlags",Zc="logs",Xc="surveys";var eu=class{constructor(e){this._instance=e}initialize(){}get(e){const t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);const i={};for(const s of e){const e=null==t?void 0:t.get_property(s);ft(e)||(i[s]=e)}return i}set(e,t){var i;null===(i=this._instance.persistence)||void 0===i||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null===(t=this._instance.persistence)||void 0===t||t.unregister(e)}},tu=class{constructor(e){this.instance=e,this._logger=En,this.kv=new eu(e),this.onEvent=e=>ul(this.instance._addCaptureHook((t,i)=>{if(i)try{e({event:t,properties:i.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}})),this.onRemoteConfig=e=>{const t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on("extensionsRemoteConfig",t);return this.instance._lastRemoteConfig&&t(this.instance._lastRemoteConfig),ul(i)}}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property("$device_id"))&&void 0!==e?e:this.distinctId}get deviceId(){const e=this.instance.get_property(S);return"string"==typeof e?e:void 0}get library(){return{name:i.LIB_NAME,version:i.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null===(t=this.instance.persistence)||void 0===t?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r;const n=null===(e=this.instance.sessionManager)||void 0===e?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==n?void 0:n.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==n?void 0:n.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==n?void 0:n.sessionStartTimestamp)&&void 0!==s?s:0,lastActivityTimestamp:null!==(r=null==n?void 0:n.lastActivityTimestamp)&&void 0!==r?r:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return pt(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get projectToken(){return this.instance.config.token}getExtension(e){let t;switch(e){case Yc:case"featureFlagsCommon":t=this.instance.featureFlags;break;case Zc:t=this.instance.logs;break;case Xc:t=this.instance.surveys;break;case Jc:t=this.instance.autocapture}return t}capture(e,t,i){i?this.instance.capture(e,t,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):this.instance.capture(e,t)}registerDynamicEventProperties(e){return ul(this.instance._registerExtensionEventProperties(e))}sendRequest(e){var t=this;return Lt(function*(e,i={}){var s;const r=null!==(s=i.target)&&void 0!==s?s:"api",n=t.instance.requestRouter.endpointFor(r,e),o="api"===r&&"/i/v1/logs"===e,a={method:i.method,url:i.query?rc(n,i.query):n,data:i.body,headers:i.headers,timeout:i.timeoutMs,fireCallbackOnDrop:!0,transport:i.transport,compression:i.compression,compressionFallback:"flags"===i.target&&"best-available"===i.compression?st.Base64:void 0,timestampMode:i.sentAt};return o&&(a.batchKey="logs"),"sendBeacon"===i.transport?(t.instance._send_request(a),{statusCode:202}):new Promise(e=>{a.callback=e,t.instance._send_request(a)})}).apply(this,arguments)}};const iu={};let su=0;const ru=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',ou="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",lu="Invalid value for property_denylist config: ",cu=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],uu=["$feature_flag_called","$$heatmap","$snapshot"],du=e=>"$"===e.charAt(0)&&!ot(uu,e),hu=/^[A-Za-z0-9_-]{1,400}$/,_u=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,pu=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,gu=["token","distinct_id",we],vu="posthog",fu=e=>{const t={};return e&&"unset"!==e?("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0),t):t},mu=e=>{var t;return ls({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mn(null==Ge?void 0:Ge.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ru,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,__preview_replay_sync_fetch:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:Ke&&mt(null==Ke?void 0:Ke.search)&&-1!==Ke.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:"https:"===(null==je||null===(t=je.location)||void 0===t?void 0:t.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(e){En.error("Bad HTTP status: "+e.statusCode+" "+e.text)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Ne,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:ru},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:To,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:fu(e),external_scripts_inject_target:e&&e>="2026-01-30"?"head":"body",internal_or_test_user_hostname:e&&e>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:e&&e>="2026-05-30"?250:0,split_storage:!(!e||"2026-05-30">e),detect_google_search_app:!(!e||"2026-05-30">e),disable_capture_url_hashes:!(!e||"2026-06-25">e),cookieWinsOnConflict:!(!e||"unset"===e||"2026-08-29">e)}))(e))},yu=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],bu=e=>{const t={};for(const[i,s]of yu)ft(e[i])||(t[s]=e[i]);const i=xn({},t,e),s=e.__preview_external_dependency_versioned_paths;return ft(s)||(ft(e.strict_script_versioning)&&(i.strict_script_versioning=!!s),mt(s)&&ft(e.asset_host)&&(i.asset_host=s)),_t(e.property_blacklist)&&(ft(e.property_denylist)?i.property_denylist=e.property_blacklist:_t(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:En.error(lu+e.property_denylist)),i};var Su=class{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){En.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},wu=class e{_removeExtension(e){if(!e)return;const t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}_replaceExtension(e,t){var i;return this._removeExtension(e),this._extensions.push(t),null===(i=t.initialize)||void 0===i||i.call(t),t}_inCookielessMode(){return"always"===this.config.cookieless_mode||"on_reject"===this.config.cookieless_mode&&this.consent.isRejected()}_warnIfVolatileIdentityWithoutStableId(){if(this._hasWarnedAboutVolatileIdentity)return;if(this.config.reuseAnonymousId)return;if(this.config.segment)return;if(this._inCookielessMode())return;const e="memory"===this.config.persistence||"sessionStorage"===this.config.persistence;if(!e&&!this.config.disable_persistence)return;if(this._hasStableInitialDistinctId)return;let t,i,s;e?(t=`persistence is set to '${this.config.persistence}'`,i="memory"===this.config.persistence?"on every page load":"for every new browser tab or window",s="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(t="persistence is disabled (disable_persistence is true)",i="on every page load",s="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this._hasWarnedAboutVolatileIdentity=!0,console.warn("[PostHog.js]",`${t} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${i}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${s}`)}_syncCookielessIdentity(){const e=this.persistence;if(!e||this._isConsentTransition)return;if(this._inCookielessMode())return void("on_reject"===this.config.cookieless_mode&&"$posthog_cookieless"!==this.get_distinct_id()&&(this._sync_opt_out_with_persistence(),this._enterCookielessMode()));if("$posthog_cookieless"!==this.get_distinct_id())return;this._is_persistence_disabled()||e.load(!0);const t=this.get_distinct_id();if(!t||"$posthog_cookieless"===t){const t=this.config.get_device_id(Hn());this.register({distinct_id:t,$device_id:t}),e.set_property(pe,Le)}this._sync_opt_out_with_persistence()}get decideEndpointWasHit(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var t;this._isPageUnloading=!1,this._isShutdown=!1,this.webPerformance=new Su,this._personProcessingSetOncePropertiesSent=!1,this.version=i.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new kc,this._extensions=[],this._extensionEventPropertyProducers=[],this._replayDebugPropertiesPaused=!1,this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._isConsentTransition=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=mu(),this.SentryIntegration=ua,this.sentryIntegration=e=>function(e,t){const i=ca(e,t);return{name:la,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._visibilityStateListener=null,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.scrollManager=new wc(this),this.pageViewManager=new da(this),this.rateLimiter=new gl(this),this.requestRouter=new Hc(this),this.consent=new uo(this),this.externalIntegrations=new Qc(this);const s=null!==(t=e.__defaultExtensionClasses)&&void 0!==t?t:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(e,t,i)=>{const s=mt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{const s=mt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",e=>En.info(`send "${null==e?void 0:e.event}"`,e))}init(t,i,s){if(s&&s!==vu){var r;const n=null!==(r=iu[s])&&void 0!==r?r:new e;return n._init(t,i,s),iu[s]=n,iu[vu][s]=n,n}return this._init(t,i,s)}_init(e,t={},s){var r,n,o;const a=mt(e)?e.trim():"";if(!a)return En.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var l;if(this.__loaded)return a!==(null===(l=this.config)||void 0===l?void 0:l.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=mu(t.defaults),t.debug=this._checkLocalStorageForDebug(t.debug),this._originalUserConfig=t,this._triggered_notifs=[],t.person_profiles?this._initialPersonProfilesConfig=t.person_profiles:t.process_person&&(this._initialPersonProfilesConfig=t.process_person);const c=mu(t.defaults),u=bu(t),d=xn({},c,u,{name:s,token:a});gt(c.rageclick)&>(u.rageclick)&&(d.rageclick=xn({},c.rageclick,u.rageclick)),gt(c.session_recording)&>(u.session_recording)&&(d.session_recording=xn({},c.session_recording,u.session_recording)),this.set_config(d),this.config.on_xhr_error&&En.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Za.GZipJS;const h=this._is_persistence_disabled(),_=!this._inCookielessMode();if(this.persistence=new Ya(this.config,h,!0,_),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Ya(ls(ls({},this.config),{},{persistence:"sessionStorage"}),h,!1,_),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!h&&co._is_supported()){const e=co._parse(this._sessionRegisteredPropertiesStorageKey);_t(e)&&e.forEach(e=>{mt(e)&&this._sessionRegisteredPropKeys.add(e)})}else co._remove(this._sessionRegisteredPropertiesStorageKey);const p=ls({},this.persistence.props),g=ls({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new yc((e,t)=>this._send_retriable_request(e,t),this.config.request_queue_config),this._retryQueue=new Sc(this),this.__request_queue=[];const v=this._inCookielessMode();v||(this.sessionManager=new Fc(this),this.sessionPropsManager=new Cc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((e,t,i)=>{((null==i?void 0:i.activityTimeout)||(null==i?void 0:i.sessionPastMaximumLength)||(null==i?void 0:i.crossTabAdoption))&&this._clearSessionRegisteredProps()})),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(En.info("Deferring extension initialization to improve startup performance"),this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._initExtensions(v)},0)):(En.info("Initializing extensions synchronously"),this._initExtensions(v)),i.DEBUG=i.DEBUG||this.config.debug,i.DEBUG&&En.info("Starting in debug mode",{this:this,config:t,thisC:ls({},this.config),p:p,s:g}),this.config.identity_distinct_id&&!(null===(r=t.bootstrap)||void 0===r?void 0:r.distinctID)&&(t.bootstrap=ls(ls({},t.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const f=null===(n=t.bootstrap)||void 0===n?void 0:n.distinctID;if(this._hasStableInitialDistinctId=!!f&&!yt(f),null===(o=t.bootstrap)||void 0===o?void 0:o.distinctID){const e=t.bootstrap.distinctID,i=this.get_distinct_id(),s=this.persistence.get_property(pe);if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"anonymous"===s)this.identify(e);else if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"identified"===s)En.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const i=this.config.get_device_id(Hn()),s=t.bootstrap.isIdentifiedID?i:e;this.persistence.set_property(pe,t.bootstrap.isIdentifiedID?De:Le),this.register({distinct_id:e,$device_id:s})}}if(v)this.register_once({distinct_id:Se,$device_id:null},"");else if(!this.get_distinct_id()){const e=this.config.get_device_id(Hn());this.register_once({distinct_id:e,$device_id:e},""),this.persistence.set_property(pe,Le)}return An(je,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),An(je,"pageshow",()=>{var e;this._isPageUnloading=!1,this._isShutdown||null===(e=this._retryQueue)||void 0===e||e.resume()}),t.segment?aa(this,()=>this._loaded()):this._loaded(),pt(this.config._onCapture)&&this.config._onCapture!==ru&&(En.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",e=>this.config._onCapture(e.event,e))),this.config.ip&&En.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Tc.apply(this,arguments)}().then(e=>{e&&this.register({[w]:e})}).catch(ru),this}_isSharedExtension(e){const t=e;return mt(t.name)&&pt(t.setup)}_enrollExtension(e,t){var i=this;this._isSharedExtension(e)?t.push(Lt(function*(){try{yield e.setup(i._getBrowserClientAdapter())}catch(i){En.error(`Failed to set up extension "${e.name}"`,i);try{var t;yield null===(t=e.dispose)||void 0===t?void 0:t.call(e)}catch(t){En.error(`Failed to dispose extension "${e.name}"`,t)}}})):this._extensions.push(e)}_enrollFeatureFlags(){var t,i,s,r=this;const n=null!==(t=null===(i=this.config.__extensionClasses)||void 0===i?void 0:i.featureFlags)&&void 0!==t?t:null===(s=e.__defaultExtensionClasses)||void 0===s?void 0:s.featureFlags;var o,a,l;if(n)if(this.featureFlags&&this.featureFlags instanceof n||(null===(o=this._featureFlagsReloadingUnsubscribe)||void 0===o||o.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new n(this)),pt(this.featureFlags.onReloading)&&pt(this.featureFlags.setup)){if(!this._featureFlagsReloadingUnsubscribe){this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading(()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)});const e=this.featureFlags;Lt(function*(){try{yield e.setup(r._getBrowserClientAdapter())}catch(t){En.error("Failed to set up feature flags",t);const i=r._featureFlagsReloadingUnsubscribe;r._featureFlagsReloadingUnsubscribe=void 0;try{null==i||i()}catch(e){En.error("Failed to unsubscribe feature flag reloading",e)}try{yield e.dispose()}catch(e){En.error("Failed to dispose feature flags",e)}}})()}}else null===(a=(l=this.featureFlags).initialize)||void 0===a||a.call(l)}_initExtensions(t){const i=performance.now(),s=ls(ls({},e.__defaultExtensionClasses),this.config.__extensionClasses),r=[];var n,o,a,l,c,u,d,h;s.exceptions&&this._extensions.push(this.exceptions=null!==(n=this.exceptions)&&void 0!==n?n:new s.exceptions(this)),s.historyAutocapture&&this._extensions.push(this.historyAutocapture=new s.historyAutocapture(this)),s.tracingHeaders&&this._extensions.push(this.tracingHeaders=new s.tracingHeaders(this)),s.siteApps&&this._extensions.push(this.siteApps=new s.siteApps(this)),s.sessionRecording&&!t&&this._extensions.push(this.sessionRecording=new s.sessionRecording(this)),this.config.disable_scroll_properties||r.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),s.autocapture&&this._enrollExtension(this.autocapture=new s.autocapture(this),r),s.surveys&&this._enrollExtension(this.surveys=null!==(o=this.surveys)&&void 0!==o?o:new s.surveys(this),r),s.logs&&this._enrollExtension(this.logs=null!==(a=this.logs)&&void 0!==a?a:new s.logs(this),r),s.metrics&&this._extensions.push(this.metrics=null!==(l=this.metrics)&&void 0!==l?l:new s.metrics(this)),s.conversations&&this._extensions.push(this.conversations=null!==(c=this.conversations)&&void 0!==c?c:new s.conversations(this)),s.productTours&&this._extensions.push(this.productTours=new s.productTours(this)),s.heatmaps&&this._extensions.push(this.heatmaps=new s.heatmaps(this)),s.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new s.webVitalsAutocapture(this)),s.exceptionObserver&&this._extensions.push(this.exceptionObserver=new s.exceptionObserver(this)),s.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new s.deadClicksAutocapture(this,ra)),s.toolbar&&this._extensions.push(this.toolbar=null!==(u=this.toolbar)&&void 0!==u?u:new s.toolbar(this)),s.experiments&&this._extensions.push(this.experiments=null!==(d=this.experiments)&&void 0!==d?d:new s.experiments(this)),s.webMCP&&this._extensions.push(this.webMCP=null!==(h=this.webMCP)&&void 0!==h?h:new s.webMCP(this)),this._extensions.forEach(e=>{e.initialize&&r.push(()=>{var t;null===(t=e.initialize)||void 0===t||t.call(e)})}),r.push(()=>{if(this._pendingRemoteConfig){const e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach(t=>{var i;return null===(i=t.onRemoteConfig)||void 0===i?void 0:i.call(t,e)})}}),this._processInitTaskQueue(r,i)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void(this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._processInitTaskQueue(e,t)},0));const i=e.shift();if(i)try{i()}catch(e){En.error("Error initializing extension:",e)}}const i=Math.round(performance.now()-t);this.register_for_session({[Ee]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ce]:i}),this.config.__preview_deferred_init_extensions&&En.info(`PostHog extensions initialized (${i}ms)`)}_onRemoteConfig(e){if(!Ge||!Ge.body)return En.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this._onRemoteConfig(e)},500);if(this.config.__preview_deferred_init_extensions&&(this._pendingRemoteConfig=e),this._lastRemoteConfig=e,this.compression=void 0,e.ok){var t;const i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ot(i.supportedCompression,Za.GZipJS)?Za.GZipJS:ot(i.supportedCompression,Za.Base64)?Za.Base64:void 0),(null===(t=i.analytics)||void 0===t?void 0:t.endpoint)&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:Ne}),this._internalEventEmitter.emit("extensionsRemoteConfig",e),this._extensions.forEach(t=>{var i;return null===(i=t.onRemoteConfig)||void 0===i?void 0:i.call(t,e)})}_loaded(){try{this.config.loaded(this)}catch(e){En.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&(null==Ke?void 0:Ke.hostname)){const e=Ke.hostname,t=this.config.internal_or_test_user_hostname;("string"==typeof t?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this._inCookielessMode())&&this._captureInitialPageview()},1),this._remoteConfigLoader=new fl(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null===(e=this._requestQueue)||void 0===e||e.enable())}_dom_loaded(){this.is_capturing()&&kn(this.__request_queue,e=>this._send_retriable_request(e)),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r,n;this._isPageUnloading=!0,null===(e=this.surveys)||void 0===e||null===(t=e.handlePageUnload)||void 0===t||t.call(e),null===(i=this.metrics)||void 0===i||i.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(Ue),null===(s=this.logs)||void 0===s||s.flushLogs("sendBeacon"),null===(r=this._requestQueue)||void 0===r||r.unload(),null===(n=this._retryQueue)||void 0===n||n.unload()):this._shouldCapturePageleave()&&this.capture(Ue,null,{transport:"sendBeacon"})}_send_request(e){mc(this,e)}_send_retriable_request(e,t){this._retryQueue?this._retryQueue.retriableRequest(e,t):this._send_request(t?ls(ls({},e),{},{transport:t}):e)}_execute_array(e){su++;try{let t;const i=[],s=[],r=[];kn(e,e=>{if(e)if(t=e[0],_t(t))r.push(e);else if(pt(e))try{e.call(this)}catch(t){En.error("Error executing queued PostHog call",e,t)}else _t(e)&&"alias"===t?i.push(e):_t(e)&&-1!==t.indexOf("capture")&&pt(this[t])?r.push(e):s.push(e)});const n=function(e,t){kn(e,function(e){try{if(_t(e[0])){let i=t;Pn(e,function(e){i=i[e[0]].apply(i,e.slice(1))})}else t[e[0]].apply(t,e.slice(1))}catch(t){En.error("Error executing queued PostHog call",e,t)}})};n(i,this),n(s,this),n(r,this)}finally{su--}}push(t){if(su>0&&_t(t)&&mt(t[0])){const i=e.prototype[t[0]];return void(pt(i)&&i.apply(this,t.slice(1)))}this._execute_array([t])}get _facebookClickIdChannel(){return{property:k,persistenceKey:P,cookieName:"_fbc",pattern:_u,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[P]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(P)}}}get _facebookBrowserIdChannel(){return{property:x,persistenceKey:F,cookieName:"_fbp",pattern:pu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[F]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(F)}}}_getPersistedMetaIdentifier(e){var t;const i=null===(t=this.persistence)||void 0===t?void 0:t.get_property(e.persistenceKey);return mt(i)&&e.pattern.test(i)?{value:i,delivered:!1}:gt(i)&&mt(i.value)&&e.pattern.test(i.value)?{value:i.value,delivered:!0===i.delivered}:void 0}_storeMetaIdentifier(e,t,i){return t===(null==i?void 0:i.value)?{value:t,pending:!i.delivered}:(e.register(t,!1),{value:t,pending:!0})}_readMetaCookie(e){if(!this.config.save_campaign_params||this._inCookielessMode())return;const t=Ln(e.cookieName);return mt(t)&&e.pattern.test(t)?t:void 0}_updateFacebookClickId(e,t,i,s){if(!this.persistence)return;const r=this._facebookClickIdChannel;this.persistence.refreshKey(r.persistenceKey);const n=this._getPersistedMetaIdentifier(r);if(s)return void r.unregister();if(i)return mt(t)&&_u.test(t)?this._storeMetaIdentifier(r,t,n):void r.unregister();const o=mt(e)&&hu.test(e)?e:void 0,a=this._readMetaCookie(r);return a&&((e,t,i)=>{const s=e.split(".");if(t)return s[3]===t;if(!i)return!0;const r=i.value.split(".");return s[3]===r[3]||Number(s[2])>Number(r[2])})(a,o,n)?this._storeMetaIdentifier(r,a,n):o?(null==n?void 0:n.value.split(".")[3])===o?{value:n.value,pending:!n.delivered}:this._storeMetaIdentifier(r,`fb.1.${Date.now()}.${o}`,n):n?{value:n.value,pending:!n.delivered}:void 0}_updateFacebookBrowserId(e,t,i){if(!this.persistence)return;const s=this._facebookBrowserIdChannel;this.persistence.refreshKey(s.persistenceKey);const r=this._getPersistedMetaIdentifier(s);if(i)return void s.unregister();if(t)return mt(e)&&pu.test(e)?this._storeMetaIdentifier(s,e,r):void s.unregister();const n=this._readMetaCookie(s);return n?this._storeMetaIdentifier(s,n,r):r?{value:r.value,pending:!r.delivered}:void 0}_markMetaIdentifierDelivered(e,t){if(!this.persistence)return;this.persistence.refreshKey(e.persistenceKey);const i=this._getPersistedMetaIdentifier(e);(null==i?void 0:i.value)!==t||i.delivered||e.register(t,!0)}capture(e,t,i){var s,r;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue))return void En.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(ft(e)||!mt(e))return void En.error("No event name provided to posthog.capture");if(this._syncCookielessIdentity(),"$snapshot"===e&&this._inCookielessMode())return;const n=!this.config.opt_out_useragent_filter&&this._is_bot();if(n&&!this.config.__preview_capture_bot_pageviews)return;const o=(null==i?void 0:i.skip_client_rate_limiting)?void 0:this.rateLimiter.clientRateLimitContext();if(null==o?void 0:o.isRateLimited)return void En.critical("This capture call is ignored due to client rate limiting.");let a;(null==t?void 0:t.$current_url)&&!mt(null==t?void 0:t.$current_url)&&(En.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),"$exception"!==e||(null==i?void 0:i._originatedFromCaptureException)||En.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(a=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const l=new Date,c=(null==i?void 0:i.timestamp)||l,u=Zi(null==i?void 0:i.uuid,Hn);let d={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},c,u)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&n&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),o&&(d.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens);const h="$feature_flag_called"===e&&!1===d.properties.$feature_flag_has_experiment&&!0===this.get_property("$minimal_flag_called_events");(null==i?void 0:i.$set)&&!h&&(d.$set=null==i?void 0:i.$set);const _=gt(null==t?void 0:t.$set)?t.$set:void 0,p=_t(null==t?void 0:t.$unset)?t.$unset:[],g=(null==i?void 0:i.$unset)||[],v=e=>{var t;const s=!!(null==i?void 0:i.$set)&&e in i.$set;return{hasProvided:s||!!_&&e in _,provided:s?null==i||null===(t=i.$set)||void 0===t?void 0:t[e]:null==_?void 0:_[e],unset:-1!==p.indexOf(e)||-1!==g.indexOf(e)}},f=v(k),m=v(x),y=[{channel:this._facebookClickIdChannel,hasProvided:f.hasProvided,update:this._updateFacebookClickId(null==a?void 0:a.fbclid,f.provided,f.hasProvided,f.unset)},{channel:this._facebookBrowserIdChannel,hasProvided:m.hasProvided,update:this._updateFacebookBrowserId(m.provided,m.hasProvided,m.unset)}];for(const{channel:e,hasProvided:t,update:i}of y)i&&!0===d.properties.$process_person_profile&&i.pending&&!t&&!h&&(d.$set=ls({[e.property]:i.value},d.$set));const b=null==i?void 0:i.$unset;b&&(d.$unset=b);const S=h?void 0:this._calculate_set_once_properties(null==i?void 0:i.$set_once,e!==ze,e===He);if(S&&(d.$set_once=S),(null==i?void 0:i._noTruncate)||(w=this.config.properties_string_max_length,d=function(e,t){const i=new Set;return function e(s,r){if(s!==Object(s))return t?t(s):s;if(i.has(s))return;let n;if(i.add(s),_t(s))n=[],kn(s,t=>{n.push(e(t))});else{const t={};Pn(It(s)?Rn(s):s,(s,r)=>{i.has(s)||(t[r]=e(s,r))}),n=t}return n}(e)}(d,e=>mt(e)?e.slice(0,w):e)),d.timestamp=c,ft(null==i?void 0:i.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=l),h&&(d.properties=((e,t=[])=>{const i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return sr.forEach(s),t.forEach(s),i})(d.properties,gu)),e===al.DISMISSED||e===al.SENT){const i=null==t?void 0:t[ll.SURVEY_ID],s=null==t?void 0:t[ll.SURVEY_ITERATION];jc({id:i,current_iteration:s}),d.$set=ls(ls({},d.$set),{},{[Rc({id:i,current_iteration:s},e===al.SENT?"responded":"dismissed")]:!0})}else e===al.SHOWN&&(d.$set=ls(ls({},d.$set),{},{[ll.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));var w;if(e===hl.SHOWN){const e=null==t?void 0:t[_l.TOUR_TYPE];e&&(d.$set=ls(ls({},d.$set),{},{[`${_l.TOUR_LAST_SEEN_DATE}/${e}`]:(new Date).toISOString()}))}const E=ls(ls({},d.properties.$set),d.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!St(this.config.before_send)){const e=this._runBeforeSend(d);if(!e)return;d=e,d.uuid=Zi(d.uuid,Hn)}this.sessionRecording&&!this._replayDebugPropertiesPaused&&du(e)&&(this._replayDebugPropertiesPaused=!0,setTimeout(()=>this._replayDebugPropertiesPaused=!1,3e4));const C=y.filter(({channel:e,update:t})=>{var i,s,r;const n=null!==(i=null===(s=d.$set)||void 0===s?void 0:s[e.property])&&void 0!==i?i:gt(null===(r=d.properties)||void 0===r?void 0:r.$set)?d.properties.$set[e.property]:void 0;return(null==t?void 0:t.pending)&&n===t.value});this._internalEventEmitter.emit("eventCaptured",d);const P=null!==(s=null==i?void 0:i._url)&&void 0!==s?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),F="recordings"===(null==i?void 0:i._batchKey)||/\/s\/(?:\?|$)/.test(P),I=ls(ls(ls({method:"POST",url:P,data:d,compression:"best-available",preferSyncCompression:null==i?void 0:i.send_instantly,timestampMode:F?"body":"capture-body",batchKey:null==i?void 0:i._batchKey},F&&(null===(r=d.properties)||void 0===r?void 0:r.$session_id)?{batchGroup:d.properties.$session_id+(d.properties.$window_id?`-${d.properties.$window_id}`:"")}:{}),(null==i?void 0:i.transport)?{transport:i.transport}:{}),C.length?{fireCallbackOnDrop:!0,callback:e=>{if(e.statusCode>=200&&300>e.statusCode)for(const{channel:e,update:t}of C)this._markMetaIdentifierDelivered(e,t.value)}}:{});if(!this.config.request_batching||i&&!(null==i?void 0:i._batchKey)||(null==i?void 0:i.send_instantly)){var T;let e;!I.transport&&!I.callback&&vt(null!==(T=this.config.request_headers)&&void 0!==T?T:{})&&this._isPageUnloading&&(e="sendBeacon"),this._send_retriable_request(I,e)}else this._requestQueue.enqueue(I);return d}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}getExtension(e){var t;return null===(t=this._browserClientAdapter)||void 0===t?void 0:t.getExtension(e)}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new tu(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);let t=!0;return()=>{if(!t)return;t=!1;const i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}_processCookieIdentityChange(e=!0){var t,i,s;return!!(null===(t=this.persistence)||void 0===t?void 0:t.consumeCookieIdentityChange())&&(this._cachedPersonProperties=null,"anonymous"===this.persistence.get_property("$user_state")&&(null===(s=this.sessionPersistence)||void 0===s||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null===(i=this.featureFlags)||void 0===i||i.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,i,s,r,n){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return i;this._syncCookielessIdentity(),this.persistence.syncCookieProperties(),this._processCookieIdentityChange();const o=n?void 0:this.persistence.remove_event_timer(e);let a=ls({},i);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this._inCookielessMode()&&(a[we]=!0),"$snapshot"===e){const e=ls(ls({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=e.distinct_id,(!mt(a.distinct_id)&&!wt(a.distinct_id)||yt(a.distinct_id))&&En.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const l=function(e,i,s,r=!1){var n,o,a,l;if(!Xe)return{};const c=e?[...ka,...i||[]]:[],[u,d]=qi(Xe),[h,_]=function(e){for(let t=0;ji.length>t;t++){const[i,s,r]=ji[t],n=e.match(i);if(n){const t=r&&e.match(r)||n;return[s,(null==t?void 0:t[1])||""]}}return["",""]}(Xe),p=function(){const e="u">typeof navigator?navigator:void 0;return(null==e?void 0:e.brave)?{brave:!0}:{}}(),g={};ft(s)||(g.detectGoogleSearchApp=s);const v={},f=null===(n=navigator)||void 0===n||null===(n=n.userAgentData)||void 0===n?void 0:n.platform,m=null===(o=navigator)||void 0===o?void 0:o.maxTouchPoints,y=null==je||null===(a=je.screen)||void 0===a?void 0:a.width,b=null==je||null===(l=je.screen)||void 0===l?void 0:l.height,S=null==je?void 0:je.devicePixelRatio;ft(f)||(v.userAgentDataPlatform=f),ft(m)||(v.maxTouchPoints=m),ft(y)||(v.screenWidth=y),ft(b)||(v.screenHeight=b),ft(S)||(v.devicePixelRatio=S);const w=xn(Tn({$os:u,$os_version:d,$browser:Li(Xe,navigator.vendor,p,g),$webview_app:h,$webview_app_version:_,$device:Ui(Xe),$device_type:Hi(Xe,v),$timezone:va(),$timezone_offset:Na()}),{$current_url:Ea(r?es(null==Ke?void 0:Ke.href):null==Ke?void 0:Ke.href,c,xa),$host:null==Ke?void 0:Ke.host,$pathname:null==Ke?void 0:Ke.pathname,$raw_user_agent:Xe.length>1e3?Xe.substring(0,997)+"...":Xe,$browser_version:Ni(Xe,navigator.vendor,p,g),$browser_language:$a(),$browser_language_prefix:Ma(),$screen_height:null==je?void 0:je.screen.height,$screen_width:null==je?void 0:je.screen.width,$viewport_height:null==je?void 0:je.innerHeight,$viewport_width:null==je?void 0:je.innerWidth,$lib:t.LIB_NAME,$lib_version:t.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return t.SDK_DIST_CHANNEL&&(w.$sdk_dist_channel=t.SDK_DIST_CHANNEL),w}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:e,windowId:t}=this.sessionManager.checkAndGetSessionAndWindowId(n,s.getTime(),!0);a.$session_id=e,a.$window_id=t}this.sessionPropsManager&&xn(a,this.sessionPropsManager.getSessionProps());try{var c;if(this.sessionRecording){const t=this.sessionRecording.sdkDebugProperties,i=!this._replayDebugPropertiesPaused&&du(e);for(const e in t)(i||ot(cu,e))&&(a[e]=t[e])}a.$sdk_debug_retry_queue_size=null===(c=this._retryQueue)||void 0===c?void 0:c.length}catch(e){a.$sdk_debug_error_capturing_properties=String(e)}let u;if(this.requestRouter.region===Nc&&(a.$lib_custom_api_host=this.config.api_host),u="$pageview"!==e||n?"$pageleave"!==e||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,r),a=xn(a,u),"$pageview"===e&&Ge&&(a.title=Ge.title),!ft(o)){const e=s.getTime()-o;a.$duration=parseFloat((e/1e3).toFixed(3))}Xe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const d=this.persistence.properties(),h=this.sessionPersistence.properties(),_=a.$groups,p=d.$groups;gt(_)&&!vt(_)&&(a.$groups=ls(ls({},gt(p)?p:{}),_)),Pn(["$referrer","$referring_domain"],e=>{e in d&&delete h[e]});const g={};if(this._extensionEventPropertyProducers.length>0)for(const e of this._extensionEventPropertyProducers.slice())try{xn(g,e())}catch(e){En.error("Failed to produce browser extension event properties",e)}a=xn({},l,d,h,ls(ls({},g),a)),a.$is_identified=this._isIdentified(),_t(this.config.property_denylist)?Pn(this.config.property_denylist,function(e){delete a[e]}):En.error(lu+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const v=this.config.sanitize_properties;v&&(En.error(au),a=v(a,e));const f=this._hasPersonProcessing();return a.$process_person_profile=f,f&&!n&&this._requirePersonProcessing("_calculate_event_properties"),a}_calculate_set_once_properties(e,t=!0,i=!1){var s;if(!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;const r=this.persistence.get_initial_props(),n=null===(s=this.sessionPropsManager)||void 0===s?void 0:s.getSetOnceProps();let o=xn({},r,n||{},e||{});const a=this.config.sanitize_properties;return a&&(En.error(au),o=a(o,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),vt(o)?void 0:o}register(e,t){var i;null===(i=this.persistence)||void 0===i||i.register(e,t)}register_once(e,t,i){var s;null===(s=this.persistence)||void 0===s||s.register_once(e,t,i)}register_for_session(e){var t,i;null===(t=this.persistence)||void 0===t||t.syncCookieProperties(),this._processCookieIdentityChange(),null===(i=this.sessionPersistence)||void 0===i||i.register(e),Object.keys(e).forEach(e=>this._sessionRegisteredPropKeys.add(e)),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null===(t=this.persistence)||void 0===t||t.unregister(e)}unregister_for_session(e){var t;null===(t=this.sessionPersistence)||void 0===t||t.unregister(e),this._sessionRegisteredPropKeys.delete(e),this._persistSessionRegisteredPropKeys()}_register_single(e,t){this.register({[e]:t})}_clearSessionRegisteredProps(){this._sessionRegisteredPropKeys.forEach(e=>{var t;null===(t=this.sessionPersistence)||void 0===t||t.unregister(e)}),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(!this._sessionRegisteredPropertiesStorageKey)return;if("memory"===this.config.persistence||(null===(e=this.sessionPersistence)||void 0===e?void 0:e._disabled)||!co._is_supported())return void co._remove(this._sessionRegisteredPropertiesStorageKey);const t=[];this._sessionRegisteredPropKeys.forEach(e=>t.push(e)),t.length>0?co._set(this._sessionRegisteredPropertiesStorageKey,t):co._remove(this._sessionRegisteredPropertiesStorageKey)}getFeatureFlag(e,t){var i;return null===(i=this.featureFlags)||void 0===i?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null===(t=this.featureFlags)||void 0===t?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null===(i=this.featureFlags)||void 0===i?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null===(s=this.featureFlags)||void 0===s?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null===(e=this.featureFlags)||void 0===e||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null===(s=this.featureFlags)||void 0===s||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null===(s=this.featureFlags)||void 0===s||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t=!1,i){var s;return null===(s=this.featureFlags)||void 0===s?void 0:s.getEarlyAccessFeatures(e,t,i)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:ou}),()=>{})}onSessionId(e){var t,i;return null!==(t=null===(i=this.sessionManager)||void 0===i?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t=!1){this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:ou})}getActiveMatchingSurveys(e,t=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:ou})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:ou}),()=>{})}renderSurvey(e,t){var i;null===(i=this.surveys)||void 0===i||i.renderSurvey(e,t)}displaySurvey(e,t=Vc){var i;null===(i=this.surveys)||void 0===i||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null===(t=this.surveys)||void 0===t||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null===(i=this.surveys)||void 0===i?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:ou}}canRenderSurveyAsync(e,t=!1){var i,s;return null!==(i=null===(s=this.surveys)||void 0===s?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:ou})}_validateIdentifyId(e){return!e||yt(e)?(En.critical("Unique user id has not been set in posthog.identify"),!1):"$posthog_cookieless"===e?(En.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(En.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(e,t,i){if(!this.__loaded||!this.persistence)return En.uninitializedWarning("posthog.identify");if(wt(e)&&(e=e.toString(),En.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this._validateIdentifyId(e))return;if(!this._requirePersonProcessing("posthog.identify"))return;this._syncCookielessIdentity();const s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression();let a=!1;try{const s=this.get_distinct_id();this.register({$user_id:e}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:s},""),e!==s&&e!==this.get_property("__alias")&&(this.unregister(E),this.register({distinct_id:e}));const o=(this.persistence.get_property("$user_state")||"anonymous")===Le,c=e!==s,u=!c&&o;if(c&&o){var l;const r=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:s};this.persistence.set_property(pe,De),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$identify",r,{$set:t||{},$set_once:i||{}})&&(this._cachedPersonProperties=Dc(e,t,i)),null===(l=this.featureFlags)||void 0===l||l.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:s)}else if(u){this.persistence.set_property(pe,De);const s=t||{},r=i||{};this.setPersonPropertiesForFlags({$set:s,$set_once:r},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:s,$set_once:r})&&(this._cachedPersonProperties=Dc(e,t,i))}else(t||i)&&this.setPersonProperties(t,i);c||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(_)):u&&(t||i)&&this.reloadFeatureFlags(),a=!0}finally{o&&this.persistence._endCookieSyncSuppression(a)}}setPersonProperties(e,t){if(!e&&!t)return;if(!this._requirePersonProcessing("posthog.setPersonProperties"))return;const i=Dc(this.get_distinct_id(),e,t);this._cachedPersonProperties!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:t||{}},!0),this.capture("$set",{$set:e||{},$set_once:t||{}})&&(this._cachedPersonProperties=i)):En.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var t;const i=(_t(e)?e:[e]).filter(e=>mt(e)&&e.length>0);0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null===(t=this.featureFlags)||void 0===t||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,i){var s;if(!e||!t)return void En.error("posthog.group requires a group type and group key");null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange();const r=this.getGroups(),n=r[e]!==t;if(n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:ls(ls({},r),{},{[e]:t})}),(n||i)&&this._hasPersonProcessing()){const s={$group_type:e,$group_key:t};i&&(s.$group_set=i),this.capture(ze,s)}i&&this.setGroupPropertiesForFlags({[e]:i}),n&&!i&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t=!0){var i;null===(i=this.featureFlags)||void 0===i||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e=!0){var t;null===(t=this.featureFlags)||void 0===t||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t=!0){var i;this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null===(i=this.featureFlags)||void 0===i||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null===(t=this.featureFlags)||void 0===t||t.resetGroupPropertiesForFlags(e)}reset(e){const t=Ct(e)?e:null==e?void 0:e.resetDeviceID,i=Ct(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t=!1,i){var s,r,n,o,a,l;if(En.info("reset"),!this.__loaded)return En.uninitializedWarning("posthog.reset");const c=null==i?void 0:i.sessionID;this.config.bootstrap=i||(null===(s=this._originalUserConfig)||void 0===s?void 0:s.bootstrap)||{},null===(r=this.featureFlags)||void 0===r||null===(n=r.updateConfig)||void 0===n||n.call(r,this.config,this._shouldDisableFlags());const u=this.get_property(S),d=this.get_property(w),h=this.get_property(U);null===(o=this.sessionRecording)||void 0===o||o.flushBeforeIdentityReset();const _=this.is_capturing();t||this.consent.reset(),t||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const p=null===(a=this.persistence)||void 0===a||null===(l=a._beginCookieSyncSuppression)||void 0===l?void 0:l.call(a),g=this._isConsentTransition;this._isConsentTransition=g||t;let v=!1;try{var f,m,y,b,E,C,k,P,x,F,I,T,R;if(null===(f=this.persistence)||void 0===f||f.clear(),null===(m=this.sessionPersistence)||void 0===m||m.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),ft(h)||null===(F=this.persistence)||void 0===F||F.register({$session_recording_remote_config:h}),null===(y=this.surveys)||void 0===y||y.reset(),null===(b=this.featureFlags)||void 0===b||b.reset(),null===(E=this.conversations)||void 0===E||E.reset(),null===(C=this.logs)||void 0===C||C.reset(),null===(k=this.metrics)||void 0===k||k.reset(),null===(P=this.persistence)||void 0===P||P.set_property("$user_state","anonymous"),null===(x=this.sessionManager)||void 0===x||x.resetSessionId(),this._cachedPersonProperties=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:Se,$device_id:null},"");else{const t=this.config.get_device_id(Hn());this.register_once({distinct_id:t,$device_id:e?t:u},""),e||ft(d)||this.register({[w]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),i)if(i.distinctID&&!this._inCookielessMode()&&(null===(R=this.persistence)||void 0===R||R.set_property("$user_state",i.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:i.distinctID})),null===(I=this.featureFlags)||void 0===I||I.initialize(),!St(c)&&!(null===(T=this.sessionManager)||void 0===T?void 0:T.setBootstrapSessionId(c,!0))){const e=ls({},i);delete e.sessionID,this.config.bootstrap=e}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,v=!0}finally{var M,A;this._isConsentTransition=g,p&&(null===(M=this.persistence)||void 0===M||null===(A=M._endCookieSyncSuppression)||void 0===A||A.call(M,v))}this.reloadFeatureFlags()}shutdown(e){var t=this;return Lt(function*(){if(!t.__loaded)return void En.uninitializedWarning("posthog.shutdown");t._isShutdown=!0,clearTimeout(t._extensionInitTimeout),t._extensionInitTimeout=void 0;const e=t._featureFlagsReloadingUnsubscribe;t._featureFlagsReloadingUnsubscribe=void 0;for(const i of[()=>{var e;return null===(e=t.sessionRecording)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.logs)||void 0===e?void 0:e.flushLogs("sendBeacon")},()=>{var e;return null===(e=t.metrics)||void 0===e?void 0:e.flush("sendBeacon")},()=>{var e;return null===(e=t.metrics)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.logs)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.surveys)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.autocapture)||void 0===e?void 0:e.dispose()},()=>null==e?void 0:e(),()=>{var e;return null===(e=t._requestQueue)||void 0===e?void 0:e.unload()},()=>{var e;return null===(e=t._retryQueue)||void 0===e?void 0:e.unload()},()=>{var e;return null===(e=t.featureFlags)||void 0===e?void 0:e.destroy()},()=>{var e;return null===(e=t.persistence)||void 0===e?void 0:e.destroy()},()=>{var e;return null===(e=t.sessionPersistence)||void 0===e?void 0:e.destroy()}])try{const e=i();e&&pt(e.then)&&e.then(void 0,e=>{En.error("Error during shutdown",e)})}catch(e){En.error("Error during shutdown",e)}})()}setIdentity(e,t){var i;delete this.config.identity_claims,this.config.identity_distinct_id=e,this.config.identity_hash=t,this.alias(e),null===(i=this.conversations)||void 0===i||i._onIdentityChanged()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,null===(e=this.conversations)||void 0===e||e._onIdentityCleared()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null===(t=this.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";const{sessionId:t,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let s=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${t}`);if((null==e?void 0:e.withTimestamp)&&i){var r;const t=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+=`?t=${Math.max(Math.floor(((new Date).getTime()-i)/1e3)-t,0)}`}return s}alias(e,t){return e===this.get_property("$people_distinct_id")?(En.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(ft(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(E,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(En.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const t=ls({},this.config);if(gt(e)){var s,r,n,o,a,l,c,u,d,h,_,p,g,v;xn(this.config,bu(e));const S=this._is_persistence_disabled();if(this.persistence){const e="sessionStorage"===this.config.persistence||"memory"===this.config.persistence;var f,m;if(e&&this.sessionPersistence!==this.persistence&&(null===(f=this.sessionPersistence)||void 0===f||f.remove(),null===(m=this.sessionPersistence)||void 0===m||m.destroy()),this.persistence.update_config(this.config,t,S),e)this.sessionPersistence=this.persistence;else if(this.sessionPersistence===this.persistence)this.sessionPersistence=new Ya(ls(ls({},this.config),{},{persistence:"sessionStorage"}),S,!1);else{var y;null===(y=this.sessionPersistence)||void 0===y||y.update_config(ls(ls({},this.config),{},{persistence:"sessionStorage"}),ls(ls({},t),{},{persistence:"sessionStorage"}),S)}}const w=this._checkLocalStorageForDebug(this.config.debug);var b;Ct(w)&&(this.config.debug=w),Ct(this.config.debug)&&(this.config.debug?(i.DEBUG=!0,Qn._is_supported()&&Qn._set("ph_debug",!0),En.info("set_config",{config:e,oldConfig:t,newConfig:ls({},this.config)})):(i.DEBUG=!1,Qn._is_supported()&&Qn._remove("ph_debug"))),null===(s=this.featureFlags)||void 0===s||null===(r=s.updateConfig)||void 0===r||r.call(s,this.config,this._shouldDisableFlags()),null===(n=this.exceptionObserver)||void 0===n||n.onConfigChange(),null===(o=this.exceptions)||void 0===o||o.onConfigChange(),null===(a=this.metrics)||void 0===a||a.onConfigChange(),null===(l=this.webMCP)||void 0===l||l.startIfEnabled(),null===(c=this.sessionRecording)||void 0===c||c.startIfEnabledOrStop(),null===(u=this.tracingHeaders)||void 0===u||u.startIfEnabledOrStop(),null===(d=this.autocapture)||void 0===d||d.startIfEnabled(),null===(h=this.heatmaps)||void 0===h||h.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null===(b=this.historyAutocapture)||void 0===b||b.startIfEnabledOrStop()),null===(_=this.exceptionObserver)||void 0===_||_.startIfEnabledOrStop(),null===(p=this.deadClicksAutocapture)||void 0===p||p.startIfEnabledOrStop(),null===(g=this.surveys)||void 0===g||g.loadIfEnabled(),this._sync_opt_out_with_persistence(),null===(v=this.externalIntegrations)||void 0===v||v.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&aa(this,ru,!1)}}_overrideSDKInfo(e,t){i.LIB_NAME=e,i.LIB_VERSION=t}startSessionRecording(e){const t=!0===e,i={sampling:t||!!(null==e?void 0:e.sampling),linked_flag:t||!!(null==e?void 0:e.linked_flag),url_trigger:t||!!(null==e?void 0:e.url_trigger),event_trigger:t||!!(null==e?void 0:e.event_trigger)};var s,r,n,o,a;Object.values(i).some(Boolean)&&(null===(s=this.sessionManager)||void 0===s||s.checkAndGetSessionAndWindowId(),i.sampling&&(null===(r=this.sessionRecording)||void 0===r||r.overrideSampling()),i.linked_flag&&(null===(n=this.sessionRecording)||void 0===n||n.overrideLinkedFlag()),i.url_trigger&&(null===(o=this.sessionRecording)||void 0===o||o.overrideTrigger("url")),i.event_trigger&&(null===(a=this.sessionRecording)||void 0===a||a.overrideTrigger("event")));this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!!(null===(e=this.sessionRecording)||void 0===e?void 0:e.started)}captureException(e,t){try{if(!this.exceptions)return;const i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(ls(ls({},i),t))}catch(e){return}}addExceptionStep(e,t){var i;null===(i=this.exceptions)||void 0===i||i.addExceptionStep(e,t)}captureLog(e){var t;null===(t=this.logs)||void 0===t||t.captureLog(e)}get logger(){var t,i;return null!==(t=null===(i=this.logs)||void 0===i?void 0:i.logger)&&void 0!==t?t:e._noopLogger}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var t,i;return null!==(t=null===(i=this.toolbar)||void 0===i?void 0:i.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null===(t=this.persistence)||void 0===t?void 0:t.props[e]}getSessionProperty(e){var t;return null===(t=this.sessionPersistence)||void 0===t?void 0:t.props[e]}toString(){var e;let t=null!==(e=this.config.name)&&void 0!==e?e:vu;return t!==vu&&(t="posthog."+t),t}_isIdentified(){var e,t;return"identified"===(null===(e=this.persistence)||void 0===e?void 0:e.get_property("$user_state"))||"identified"===(null===(t=this.sessionPersistence)||void 0===t?void 0:t.get_property("$user_state"))}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||"identified_only"===this.config.person_profiles&&!this._isIdentified()&&vt(this.getGroups())&&!(null===(e=this.persistence)||void 0===e||null===(e=e.props)||void 0===e?void 0:e.__alias)&&!(null===(t=this.persistence)||void 0===t||null===(t=t.props)||void 0===t?void 0:t.$epp))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&!!this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this._requirePersonProcessing("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}_requirePersonProcessing(e){return"never"===this.config.person_profiles?(En.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(be,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;const e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&"on_reject"!==this.config.cookieless_mode)}_sync_opt_out_with_persistence(){var e,t;const i=this._is_persistence_disabled();var s,r,n;return this.is_capturing()||null===(s=this.logs)||void 0===s||s._onOptOut(),(null===(e=this.persistence)||void 0===e?void 0:e._disabled)!==i&&(null===(r=this.persistence)||void 0===r||r.set_disabled(i)),(null===(t=this.sessionPersistence)||void 0===t?void 0:t._disabled)!==i&&(null===(n=this.sessionPersistence)||void 0===n||n.set_disabled(i)),this._persistSessionRegisteredPropKeys(),i}opt_in_capturing(t){var i;if("always"!==this.config.cookieless_mode){if(this._inCookielessMode()){var s,r,n,o,a,l;null===(s=this.sessionRecording)||void 0===s||s.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null===(r=this.sessionManager)||void 0===r||r.destroy(),null===(n=this.pageViewManager)||void 0===n||n.destroy(),this.sessionManager=new Fc(this),this.pageViewManager=new da(this),this.persistence&&(this.sessionPropsManager=new Cc(this,this.sessionManager,this.persistence));const t=null!==(o=null===(a=this.config.__extensionClasses)||void 0===a?void 0:a.sessionRecording)&&void 0!==o?o:null===(l=e.__defaultExtensionClasses)||void 0===l?void 0:l.sessionRecording;var c,u;t&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new t(this)),this._lastRemoteConfig&&(null===(c=this.sessionRecording)||void 0===c||null===(u=c.onRemoteConfig)||void 0===u||u.call(c,this._lastRemoteConfig)))}var d,h;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null===(i=this.sessionRecording)||void 0===i||i.startIfEnabledOrStop(),"on_reject"==this.config.cookieless_mode&&(null===(d=this.surveys)||void 0===d||d.loadIfEnabled()),(ft(null==t?void 0:t.captureEventName)||(null==t?void 0:t.captureEventName))&&this.capture(null!==(h=null==t?void 0:t.captureEventName)&&void 0!==h?h:"$opt_in",null==t?void 0:t.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}else En.warn(nu)}opt_out_capturing(){"always"!==this.config.cookieless_mode?(this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),"on_reject"===this.config.cookieless_mode&&this._enterCookielessMode()):En.warn(nu)}_enterCookielessMode(){var e,t;const i=this.sessionRecording;null==i||i.dispose({discardBufferedEvents:!0}),"$posthog_cookieless"!==this.get_distinct_id()&&this._reset(!0,!0),this.register({distinct_id:Se,$device_id:null}),this._removeExtension(i),this.sessionRecording=void 0,null===(e=this.sessionManager)||void 0===e||e.destroy(),null===(t=this.pageViewManager)||void 0===t||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return!this._isConsentTransition&&("always"===this.config.cookieless_mode||("on_reject"===this.config.cookieless_mode?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing()))}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return Ve?Ic(Ve,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Ge&&("visible"===Ge.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(qe,{title:Ge.title},{send_instantly:!0}),this._visibilityStateListener&&(Ge.removeEventListener(m,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),An(Ge,m,this._visibilityStateListener)))}debug(e){!1===e?(null==je||je.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==je||je.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}_shouldDisableFlags(){const e=this._originalUserConfig||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?(En.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){const n=t in e&&!St(e[t]),o=i in e&&!St(e[i]);return n?e[t]:!!o&&(r&&r.warn(`Config field '${i}' is deprecated. Please use '${t}' instead. The old field will be removed in a future major version.`),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,En)}_runBeforeSend(e){var t;if(St(this.config.before_send))return e;const i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Pt),s=_t(this.config.before_send)?this.config.before_send:[this.config.before_send];let r=e;for(const t of s)try{if(r=t(r),St(r)){const t=`Event '${e.event}' was rejected in beforeSend function`;return kt(e.event)?En.warn(`${t}. This can cause unexpected behavior.`):En.info(t),null}r.properties&&!vt(r.properties)||En.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(t){return En.error(`Error in beforeSend function for event '${e.event}':`,t),null}for(const t of i)if(r.properties&&St(r.properties[t]))return En.warn(`Event '${e.event}' had its '${t}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return r}getPageViewId(){var e;return null===(e=this.pageViewManager._currentPageview)||void 0===e?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}_checkLocalStorageForDebug(e){const t=Ct(e)&&!e,i=Qn._is_supported()&&"true"===Qn._get("ph_debug");return!t&&(!!i||e)}};wu.__defaultExtensionClasses={},wu._noopLogger=(()=>{const e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),function(e,t){for(let i=0;t.length>i;i++)e.prototype[t[i]]=In(e.prototype[t[i]])}(wu,["identify"]);var Eu=class{constructor(e){this.disabled=!1===e;const t=gt(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;const s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)<this.thresholdPx&&this.timeoutMs>i-s.timestamp){if(this.clicks.push({x:e,y:t,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}};const Cu="$copy_autocapture",ku=Cn("[AutoCapture]");function Pu(e,t){return t.length>e?t.slice(0,e)+"...":t}function xu(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do{t=t.previousSibling}while(t&&!po(t));return t}function Fu(e,{e:t,maskAllElementAttributes:i,maskAllText:s,elementAttributeIgnoreList:r,elementsChainAsString:n,disableCaptureUrlHashes:o}){var a,l;if(!po(e))return{props:{}};const c=[e],u=new Set([e]);let d=e;for(;d.parentNode&&!go(d,"body")&&1e3>c.length;){if(fo(d.parentNode)){const e=d.parentNode.host;if(u.has(e))break;u.add(e),c.push(e),d=e;continue}if(!po(d.parentNode))break;if(u.has(d.parentNode))break;u.add(d.parentNode),c.push(d.parentNode),d=d.parentNode}const h="click"===t.type&&"http://www.w3.org/2000/svg"===e.namespaceURI?c.findIndex(e=>go(e,"button")||go(e,"a")):-1;h>0&&(s=s||c.slice(0,h+1).some(e=>!Ho(e)||zo(e)));const _=[],p={};let g,v=!1,f=!1;if(Pn(c,e=>{const t=Ho(e);if(go(e,"a")&&!i&&!(null==r?void 0:r.includes("href"))){const i=e.getAttribute("href");v=!!(t&&i&&Yo(i))&&(o?es(i):i)}ot(bo(e),"ph-no-capture")&&(f=!0),_.push(function(e,t,i,s,r=!1){const n=e.tagName.toLowerCase(),o={tag_name:n};Co.indexOf(n)>-1&&!i&&(o.$el_text="a"===n.toLowerCase()||"button"===n.toLowerCase()?Pu(1024,Zo(e)):Pu(1024,wo(e)));const a=bo(e);t||(null==s?void 0:s.includes("class"))||0>=a.length||(o.classes=a.filter(function(e){return""!==e})),Pn(e.attributes,function(i){var n;if((!zo(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&!(null==s?void 0:s.includes(i.name))&&!t&&Yo(i.value)&&(!mt(n=i.name)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){let e=i.value;"class"===i.name&&(e=mo(e).join(" ")),o["attr__"+i.name]=Pu(1024,"href"===i.name&&r?es(e):e)}});let l=1,c=1,u=e;for(;u=xu(u);)l++,u.tagName===e.tagName&&c++;return o.nth_child=l,o.nth_of_type=c,o}(e,i,s,r,o)),Pn(function(e){if(!Ho(e))return{};const t={};return Pn(e.attributes,function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){const i=e.name.replace("data-ph-capture-attribute-",""),s=e.value;i&&s&&Yo(s)&&(t[i]=s)}}),t}(e),(e,t)=>{({}).hasOwnProperty.call(p,t)||(p[t]=e)})}),f)return{props:{},explicitNoCapture:f};if(h>0&&(e=c[h],_.splice(0,h)),s||(_[0].$el_text=go(e,"a")||go(e,"button")?Zo(e):wo(e)),v){var m,y;_[0].attr__href=v;const e=null===(m=Sa(v))||void 0===m?void 0:m.host,t=null==je||null===(y=je.location)||void 0===y?void 0:y.host;e&&t&&e!==t&&(g=v)}return{props:xn((S=t.type,{$event_type:S,$ce_version:1}),n?{}:{$elements:_},{$elements_chain:(b=_,_t(b)?function(e){return e.map(e=>{var t,i;let s="";if(e.tag_name&&(s+=e.tag_name),e.attr_class){e.attr_class.sort();for(const t of e.attr_class)s+=`.${t.replace(/"/g,"")}`}const r=ls(ls(ls(ls({},e.text?{text:e.text}:{}),{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(i=e.nth_of_type)&&void 0!==i?i:0},e.href?{href:e.href}:{}),e.attr_id?{attr_id:e.attr_id}:{}),e.attributes),n={};return Fn(r).sort(([e],[t])=>function(e,t){return t>e?-1:e>t?1:0}(e,t)).forEach(([e,t])=>n[ea(e.toString())]=ea(t.toString())),s+=":",s+=Fn(n).map(([e,t])=>`${e}="${t}"`).join(""),s}).join(";")}(function(e){return e.map(e=>{var t,i;const s={text:null===(t=e.$el_text)||void 0===t?void 0:t.slice(0,400),tag_name:e.tag_name,href:null===(i=e.attr__href)||void 0===i?void 0:i.slice(0,2048),attr_class:ta(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Fn(e).filter(([e])=>0===e.indexOf("attr__")).forEach(([e,t])=>s.attributes[e]=t),s})}(b)):"")},(null===(a=_[0])||void 0===a?void 0:a.$el_text)?{$el_text:null===(l=_[0])||void 0===l?void 0:l.$el_text}:{},g&&"click"===t.type?{$external_click_url:g}:{},p),target:e};var b,S}var Iu=class{_clearPointer(){this._pointerDown=void 0,clearTimeout(this._pointerExpiry),this._pointerExpiry=void 0}_isExcludedPointerTarget(e){var t;if(!Ho(e))return!0;const i=null!==(t=this._refreshConfig().css_selector_ignorelist)&&void 0!==t?t:Fo,s=new Set;let r=e;for(;r;){if(s.size>=1e3||s.has(r))return!0;s.add(r);const e=r,t=bo(e);if(ot(t,"ph-no-capture")||ot(t,"ph-sensitive")||zo(e)||i.some(t=>ko(e,t)))return!0;const n=r.parentNode;r=fo(n)?n.host:n&&po(n)?n:null}return!1}_trackPointer(e){if(!this.isEnabled||"pointercancel"===e.type)return void this._clearPointer();if("pointerdown"===e.type){this._clearPointer();const i=Eo(e);var t;return void(e.isPrimary&&0===e.button&&!e.ctrlKey&&i&&po(i)&&(this._pointerDown={target:i,excluded:this._isExcludedPointerTarget(i),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:null===(t=this._client)||void 0===t?void 0:t.distinctId}))}const i=this._pointerDown;i&&(e.pointerId!==i.id||Math.abs(e.clientX-i.x)>5||Math.abs(e.clientY-i.y)>5?this._clearPointer():"pointerup"===e.type&&(i.released=!0,this._pointerExpiry=setTimeout(()=>this._clearPointer(),0)))}_recoverClickTarget(e){var t;const i=this._pointerDown;this._clearPointer();const s=Eo(e);if((null==i?void 0:i.released)&&i.target.isConnected&&i.distinctId===(null===(t=this._client)||void 0===t?void 0:t.distinctId)&&e.pointerId===i.id&&(e.detail>0||"touch"===e.pointerType||"pen"===e.pointerType)&&0===e.button&&5>=Math.abs(e.clientX-i.x)&&5>=Math.abs(e.clientY-i.y)&&s&&(go(s,"html")||go(s,"body"))){var r;if(i.excluded)return null;const e=null!==(r=this._refreshConfig().css_selector_ignorelist)&&void 0!==r?r:Fo;return[s,null==Ge?void 0:Ge.documentElement,null==Ge?void 0:Ge.body].some(t=>{if(!t)return!1;const i=bo(t);return ot(i,"ph-no-capture")||ot(i,"ph-sensitive")||!Ho(t)||zo(t)||e.some(e=>ko(t,e))})?null:i.target}}constructor(e){this._configSource=e,this.name=Jc,this._initialized=!1,this._isDisabledServerSide=null,this._hasReceivedConfigResponse=!1,this._elementSelectorsByOwner=new Map,this._elementsChainAsString=!1,this._config={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this._disposed=!1,this._configSource.refresh(this._config),this.rageclicks=new Eu(this._config.rageclick),this._elementSelectors=null}setup(e){this._compileUrlPatterns(),this._client=e;const t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.startIfEnabled())}dispose(){var e;this._disposed||(this._disposed=!0,this._client=void 0,null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,this._elementSelectorsByOwner.clear(),this._elementSelectors=null,this._removeDomEventHandlers())}_refreshConfig(){return this._configSource.refresh(this._config),this._config}_compileUrlPatterns(){var e,t;return this._refreshConfig(),this._config.url_allowlist=null===(e=this._config.url_allowlist)||void 0===e?void 0:e.map(e=>new RegExp(e)),this._config.url_ignorelist=null===(t=this._config.url_ignorelist)||void 0===t?void 0:t.map(e=>new RegExp(e)),this._config}_addDomEventHandlers(){if(!this.isBrowserSupported())return void ku.info("Disabling Automatic Event Collection because this browser is not supported");if(!je||!Ge)return;const e=this._domEventHandler=e=>{e=e||(null==je?void 0:je.event);try{if("blur"===e.type)return void this._clearPointer();if(0===e.type.indexOf("pointer"))return void this._trackPointer(e);const t="click"===e.type?this._recoverClickTarget(e):void 0;if(bt(t))return;this._captureEvent(e,"$autocapture",t)}catch(e){ku.error("Failed to capture event",e)}};if(An(je,"blur",e),An(Ge,"submit",e,{capture:!0}),An(Ge,"change",e,{capture:!0}),An(Ge,"click",e,{capture:!0}),Pn(["pointerdown","pointermove","pointerup","pointercancel"],t=>{An(Ge,t,e,{capture:!0})}),this._refreshConfig().capture_copied_text){const e=this._copiedTextHandler=e=>{e=e||(null==je?void 0:je.event);try{this._captureEvent(e,Cu)}catch(e){ku.error("Failed to capture clipboard event",e)}};An(Ge,"copy",e,{capture:!0}),An(Ge,"cut",e,{capture:!0}),An(Ge,"paste",e,{capture:!0})}}_removeDomEventHandlers(){this._clearPointer(),this._domEventHandler&&(null==je||je.removeEventListener("blur",this._domEventHandler),Pn(["pointerdown","pointermove","pointerup","pointercancel"],e=>{null==Ge||Ge.removeEventListener(e,this._domEventHandler,!0)}),null==Ge||Ge.removeEventListener("submit",this._domEventHandler,!0),null==Ge||Ge.removeEventListener("change",this._domEventHandler,!0),null==Ge||Ge.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==Ge||Ge.removeEventListener("copy",this._copiedTextHandler,!0),null==Ge||Ge.removeEventListener("cut",this._copiedTextHandler,!0),null==Ge||Ge.removeEventListener("paste",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._initialized=!1}startIfEnabled(){this.isEnabled||this._clearPointer(),!this._disposed&&this._client&&this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){if(this._disposed)return;if(this._hasReceivedConfigResponse=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString);const i=t.autocapture_opt_out;var s;Ct(i)&&(null===(s=this._client)||void 0===s||s.kv.set("$autocapture_disabled_server_side",i),this._isDisabledServerSide=i),this.startIfEnabled()}setElementSelectors(e,t=this){if(this._disposed)return;e.size?this._elementSelectorsByOwner.set(t,new Set(e)):this._elementSelectorsByOwner.delete(t);const i=new Set;this._elementSelectorsByOwner.forEach(e=>{e.forEach(e=>i.add(e))}),this._elementSelectors=i}getElementSelectors(e,t){var i;const s=[];return null===(i=this._elementSelectors)||void 0===i||i.forEach(i=>{const r=null==Ge?void 0:Ge.querySelectorAll(i);null==r||r.forEach(r=>{e!==r&&t!==r||ot(s,i)||s.push(i)})}),s}get isEnabled(){var e,t;if(this._disposed)return!1;const i=null===(e=this._client)||void 0===e?void 0:e.kv.get(T),s=this._isDisabledServerSide,r=this._refreshConfig();if(!r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse)return!1;const n=r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(bt(s)&&!Ct(i)&&!n)return!1;const o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!r.enabled&&!o}_captureEvent(e,t="$autocapture",i){if(!this.isEnabled)return void this._clearPointer();let s=i||Eo(e);vo(s)&&(s=s.parentNode||null);const r=this._compileUrlPatterns();var n;"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&r.rageclick&&(null===(n=this.rageclicks)||void 0===n?void 0:n.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime()))&&Bo(s,r.rageclick)&&this._captureEvent(e,"$rageclick",i);const o=t===Cu,a=o?ls(ls({},r),{},{dom_event_allowlist:void 0}):r;if(s&&function(e,t,i,s,r,n){var o;if(!je||qo(e))return!1;if((null==i?void 0:i.url_allowlist)&&!yo(i.url_allowlist,n))return!1;if((null==i?void 0:i.url_ignorelist)&&yo(i.url_ignorelist,n))return!1;if(null==i?void 0:i.dom_event_allowlist){const e=i.dom_event_allowlist;if(e&&!e.some(e=>t.type===e))return!1}const{parentIsUsefulElement:a,targetElementList:l}=Uo(e,s);if(!function(e,t){const i=null==t?void 0:t.element_allowlist;if(ft(i))return!0;for(const t of e)if(i.some(e=>t.tagName.toLowerCase()===e))return!0;return!1}(l,i))return!1;if(!Po(l,null==i?void 0:i.css_selector_allowlist))return!1;if(Po(l,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Fo))return!1;try{const i=je.getComputedStyle(e);if(i&&"pointer"===i.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}const c=e.tagName.toLowerCase();switch(c){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return a?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(Co.indexOf(c)>-1||"true"===e.getAttribute("contenteditable"))}}(s,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:r.getCurrentUrl}})){var l;const{props:i,explicitNoCapture:n,target:o}=Fu(s,{e:e,maskAllElementAttributes:r.maskAllElementAttributes,maskAllText:r.maskAllText,elementAttributeIgnoreList:r.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:r.disableCaptureUrlHashes});if(n)return!1;const a=this.getElementSelectors(s,o);if(a&&a.length>0&&(i.$element_selectors=a),t===Cu){const t=e.type||"clipboard";if("paste"!==t){var c,u;const e=null==je||null===(c=je.getSelection())||void 0===c?void 0:c.toString(),t=So(e);if(!t)return!1;i.$selected_content=t,i.$clipboard_text_length=null!==(u=null==e?void 0:e.length)&&void 0!==u?u:0}i.$copy_type=t}return null===(l=this._client)||void 0===l||l.capture(t,i),!0}}isBrowserSupported(){return pt(null==Ge?void 0:Ge.querySelectorAll)}},Tu=class{constructor(e){this._instance=e}refresh(e){const t=this._instance.config,i=gt(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==i?void 0:i.url_allowlist,e.url_ignorelist=null==i?void 0:i.url_ignorelist,e.dom_event_allowlist=null==i?void 0:i.dom_event_allowlist,e.element_allowlist=null==i?void 0:i.element_allowlist,e.css_selector_allowlist=null==i?void 0:i.css_selector_allowlist,e.css_selector_ignorelist=null==i?void 0:i.css_selector_ignorelist,e.element_attribute_ignorelist=null==i?void 0:i.element_attribute_ignorelist,e.capture_copied_text=null==i?void 0:i.capture_copied_text}};const Ru=Cn("[ExceptionAutocapture]"),$u=()=>{},Mu=e=>{var t;if(pt(e))return null!==(t=e.__posthog_layer__)&&void 0!==t?t:e.__rrweb_layer__};function Au(e,t,i){try{if(!(t in e))return $u;const s={next:e[t]},r=i(function(...e){return s.next.apply(this,e)});return pt(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=r,()=>{if(e[t]===r)return void(e[t]=s.next);let i=e[t],n=Mu(i);for(;n;){if(n.next===r)return void(n.next=s.next);i=n.next,n=Mu(i)}}}catch(e){return $u}}const Ou=Cn("[TracingHeaders]"),Lu=Cn("[Web Vitals]"),Du=9e5,Nu=["CLS","FCP","INP","LCP"],Bu=["INP","LCP"],qu=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Uu="disabled",Hu="lazy_loading",zu=Cn("[SessionRecording]"),ju=[ke,Pe,xe,Fe,Ie,Te,Re,$e,Me],Wu=Cn("[Heatmaps]");function Vu(e){return gt(e)&&"clientX"in e&&"clientY"in e&&wt(e.clientX)&&wt(e.clientY)}const Gu=Cn("[Product Tours]"),Ku=e=>{var t;return!e.config.disable_product_tours&&!!(null===(t=e.persistence)||void 0===t?void 0:t.get_property(N))},Qu=["$set_once","$set"],Ju=Cn("[SiteApps]"),Yu="Error while initializing PostHog app with config id ",Zu=(e,t)=>(null==e?void 0:e.then)?e.then(t):t(e),Xu="SDK is not enabled or survey functionality is not yet loaded",ed="Disabled. Not loading surveys.";var td=class{constructor(e,t){this._configSource=e,this._initialClientState=t,this.name=Xc,this._surveyEventReceiver=null,this._surveyManager=null,this._isInitializingSurveys=!1,this._surveyInitializationFailed=!1,this._surveyCallbacks=[],this._activeMatchingSurveyCallbacks=[],this._getSurveysInFlightPromise=null,this._lastSurveyRefreshFailedAt=null,this._disposed=!1,this._renderTimeouts=new Set,this.onRemoteConfig=e=>{if(this._disposed)return;if(this._config.disableSurveys)return;if(!e.ok)return this._surveyInitializationFailed=!0,this._notifyActiveMatchingSurveyCallbacks({isLoaded:!1,error:"Remote config unavailable. Not loading surveys."}),zc.warn("Remote config unavailable. Not loading surveys.");const t=e.config.surveys;if(St(t))return zc.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=Ct(t)?t:t.length>0,zc.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`),this.loadIfEnabled()},this._notifyActiveMatchingSurveyCallbacks=e=>{this._activeMatchingSurveyCallbacks.slice().forEach(t=>this._notifyActiveMatchingSurveyCallback(t,e))}}setup(e){if(!this._disposed)return this._initializingClient=e,Zu(e.kv.initialize(),()=>{if(this._initializingClient!==e||this._disposed)return;this._initializingClient=void 0,this._client=e;const t=e.onRemoteConfig(this.onRemoteConfig);this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.loadIfEnabled())})}dispose(){var e,t,i,s,r;this._disposed||(this._disposed=!0,this._initializingClient=void 0,this._client=void 0,null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,null===(t=this._surveyEventReceiver)||void 0===t||t.dispose(),this._surveyEventReceiver=null,null===(i=this._surveyManager)||void 0===i||null===(s=i.dispose)||void 0===s||s.call(i),this._surveyManager=null,this._surveyCallbacks=[],this._activeMatchingSurveyCallbacks.forEach(e=>{e.active=!1}),this._activeMatchingSurveyCallbacks=[],null===(r=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===r||r.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0,this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach(e=>clearTimeout(e)),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}initialize(){this.loadIfEnabled()}reset(){var e,t;null===(e=this._surveyManager)||void 0===e||null===(t=e.clearInMemoryInProgressSurveyState)||void 0===t||t.call(e);try{var i;null===(i=this._surveyEventReceiver)||void 0===i||i.reset(),localStorage.removeItem("lastSeenSurveyDate");const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);((null==i?void 0:i.startsWith("seenSurvey_"))||(null==i?void 0:i.startsWith("inProgressSurvey_")))&&e.push(i)}e.forEach(e=>localStorage.removeItem(e))}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}loadIfEnabled(){if(this._disposed||!this._client)return;const e=this._config;if(this._surveyManager)return;if(this._isInitializingSurveys)return void zc.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void zc.info(ed);if(e.cookielessMode&&this._configSource.isOptedOut())return void zc.info("Not loading surveys in cookieless mode without consent.");const t=this._configSource.getExtensions();if(!t)return void this._handleSurveyLoadError("PostHog Extensions not found.");if(ft(this._isSurveysEnabled)&&!e.advancedEnableSurveys)return;const i=this._isSurveysEnabled||e.advancedEnableSurveys;this._isInitializingSurveys=!0,this._surveyInitializationFailed=!1;try{const e=t.generateSurveys;if(e)return this._completeSurveyInitialization(e,i),void(this._isInitializingSurveys=!1);const s=t.loadExternalDependency;if(!s)return this._handleSurveyLoadError(Oe),void(this._isInitializingSurveys=!1);s(e=>{try{if(this._disposed)return;const t=this._configSource.getExtensions();e||!(null==t?void 0:t.generateSurveys)?this._handleSurveyLoadError("Could not load surveys script",e):this._completeSurveyInitialization(t.generateSurveys,i)}finally{this._isInitializingSurveys=!1}})}catch(e){throw this._isInitializingSurveys=!1,this._handleSurveyLoadError("Error initializing surveys",e),e}}_completeSurveyInitialization(e,t){var i,s;if(this._disposed)return;this._surveyManager=e(t),this._surveyEventReceiver=this._configSource.createEventReceiver(this._notifyActiveMatchingSurveyCallbacks);const r=null===(i=null!==(s=this._client)&&void 0!==s?s:this._initialClientState)||void 0===i?void 0:i.kv.get(ie);r&&this._registerEventOrActionBasedSurveys(r),zc.info("Surveys loaded successfully"),this._startActiveMatchingSurveyConditions(),this._notifyActiveMatchingSurveyCallbacks(),this._notifySurveyCallbacks({isLoaded:!0})}_handleSurveyLoadError(e,t){this._surveyInitializationFailed=!0,zc.error(e,t),this._notifyActiveMatchingSurveyCallbacks({isLoaded:!1,error:e}),this._notifySurveyCallbacks({isLoaded:!1,error:e})}onSurveysLoaded(e){return this._surveyCallbacks.push(e),this._surveyManager&&this._notifySurveyCallbacks({isLoaded:!0}),()=>{this._surveyCallbacks=this._surveyCallbacks.filter(t=>t!==e)}}getSurveys(e,t=!1){var i;const s=null!==(i=this._client)&&void 0!==i?i:this._initialClientState;if(!s||this._disposed)return;if(this._config.disableSurveys)return zc.info(ed),e([]);const r=s.kv.get(ie);if(r&&!t)return e(r,{isLoaded:!0}),void(this._shouldBackgroundRefreshSurveys()&&this.getSurveys(()=>{},!0));if(this._getSurveysInFlightPromise)return void this._getSurveysInFlightPromise.then(({surveys:t,context:i})=>{this._disposed||e(t,i)}).catch(e=>zc.error("Error in survey callback",e));const n=this._sendSurveysRequest("/api/surveys/",{method:"GET",query:{token:s.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then(e=>{try{return this._handleSurveyResponse(s,e)}catch(e){return zc.error("Error processing surveys response",e),this._handleSurveyResponse(s,{statusCode:0,error:e})}},e=>this._handleSurveyResponse(s,{statusCode:0,error:e}));this._getSurveysInFlightPromise=n;const o=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then(t=>{o(),this._disposed||(this._notifyActiveMatchingSurveyCallbacks(t.context),e(t.surveys,t.context))},o).catch(e=>zc.error("Error in survey callback",e))}_sendSurveysRequest(e,t){const i=this._client;return i?i.sendRequest(e,t):new Promise(e=>e({statusCode:0,error:new Error(Xu)}))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Xu}};const i=t.statusCode;if(200!==i||!t.json){const e=`Surveys API could not be loaded, status: ${i}`;return 0!==i?zc.error(e):t.error||zc.warn(e),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:e}}}this._lastSurveyRefreshFailedAt=null;const s=t.json.surveys||[];return e.kv.set({[ie]:s,[se]:Date.now()}),this._registerEventOrActionBasedSurveys(s),{surveys:s,context:{isLoaded:!0}}}_registerEventOrActionBasedSurveys(e){var t;const i=e.filter(e=>function(e){return!(!e.start_date||e.end_date)}(e)&&($c(e)||function(e){var t;return!!(null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length)}(e)));null===(t=this._surveyEventReceiver)||void 0===t||t.replace(i)}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e,t;const i=null===(e=null!==(t=this._client)&&void 0!==t?t:this._initialClientState)||void 0===e?void 0:e.kv.get(se);return wt(i)&&Date.now()-i>3e5}_isSurveyRefreshBackingOff(){return wt(this._lastSurveyRefreshFailedAt)&&3e5>Date.now()-this._lastSurveyRefreshFailedAt}markSurveyAsSeen(e,t){var i;const s={id:e,current_iteration:null!==(i=null==t?void 0:t.iteration)&&void 0!==i?i:null};jc(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}_notifySurveyCallbacks(e){for(const t of this._surveyCallbacks)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){zc.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t=!1){if(!St(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);zc.warn("init was not called")}onActiveMatchingSurveysChanged(e){var t,i;if(this._disposed)return()=>{};const s={callback:e,active:!0,revision:0};this._activeMatchingSurveyCallbacks.push(s),this._startActiveMatchingSurveyConditions();const r=null===(t=null!==(i=this._client)&&void 0!==i?i:this._initialClientState)||void 0===t?void 0:t.kv.get(ie);return this._config.disableSurveys||!this._surveyManager&&this._surveyInitializationFailed&&!this._isInitializingSurveys||!r&&!St(this._lastSurveyRefreshFailedAt)&&!this._getSurveysInFlightPromise?this._notifyActiveMatchingSurveyCallback(s,{isLoaded:!1}):this._surveyManager&&this._notifyActiveMatchingSurveyCallback(s),()=>{var e;s.active=!1,this._activeMatchingSurveyCallbacks=this._activeMatchingSurveyCallbacks.filter(e=>e!==s),0===this._activeMatchingSurveyCallbacks.length&&(null===(e=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===e||e.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0)}}_startActiveMatchingSurveyConditions(){var e,t,i;this._surveyManager&&this._activeMatchingSurveyCallbacks.length>0&&(null!==(e=this._activeMatchingSurveyConditionsUnsubscribe)&&void 0!==e||(this._activeMatchingSurveyConditionsUnsubscribe=null===(t=(i=this._configSource).onMatchingConditionsChanged)||void 0===t?void 0:t.call(i,this._notifyActiveMatchingSurveyCallbacks)))}_notifyActiveMatchingSurveyCallback(e,t){if(this._disposed||!e.active)return;const i=++e.revision,s=s=>{if(!this._disposed&&e.active&&i===e.revision)try{const i=null!=t?t:{isLoaded:!0},r=JSON.stringify([s,i]);if(r===e.lastResult)return;e.lastResult=r,e.callback(s,i)}catch(e){zc.error("Error in active matching surveys callback",e)}};try{t&&!t.isLoaded?s([]):this.getActiveMatchingSurveys(s)}catch(e){zc.error("Error in active matching surveys callback",e)}}_getSurveyById(e){let t=null;return this.getSurveys(i=>{var s;t=null!==(s=i.find(t=>t.id===e))&&void 0!==s?s:null}),t}_checkSurveyEligibility(e){if(St(this._surveyManager))return{eligible:!1,reason:Xu};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){if(!this._configSource.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(St(this._surveyManager))return{eligible:!1,reason:Xu};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(St(this._surveyManager))return zc.warn("init was not called"),{visible:!1,disabledReason:Xu};const t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return St(this._surveyManager)?(zc.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Xu})):new Promise(i=>{this.getSurveys(t=>{var s;const r=null!==(s=t.find(t=>t.id===e))&&void 0!==s?s:null;if(r){const e=this._checkSurveyRenderability(r);i({visible:e.eligible,disabledReason:e.reason})}else i({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,i){var s;if(!this._configSource.isCapturing())return;if(St(this._surveyManager))return void zc.warn("init was not called");const r="string"==typeof e?this._getSurveyById(e):e;if(!(null==r?void 0:r.id))return void zc.warn("Survey not found");if(!Wc.includes(r.type))return void zc.warn(`Surveys of type ${r.type} cannot be rendered in the app`);const n=null==Ge?void 0:Ge.querySelector(t);if(n){if(null===(s=r.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds){zc.info(`Rendering survey ${r.id} with delay of ${r.appearance.surveyPopupDelaySeconds} seconds`);const e=setTimeout(()=>{var t,s;this._renderTimeouts.delete(e),!this._disposed&&this._configSource.isCapturing()&&(zc.info(`Rendering survey ${r.id} with delay of ${null===(t=r.appearance)||void 0===t?void 0:t.surveyPopupDelaySeconds} seconds`),null===(s=this._surveyManager)||void 0===s||s.renderSurvey(r,n,i),zc.info(`Survey ${r.id} rendered`))},1e3*r.appearance.surveyPopupDelaySeconds);return void this._renderTimeouts.add(e)}this._surveyManager.renderSurvey(r,n,i)}else zc.warn("Survey element not found")}displaySurvey(e,t){var i;if(!this._configSource.isCapturing())return;if(St(this._surveyManager))return void zc.warn("init was not called");const s=this._getSurveyById(e);if(!s)return void zc.warn("Survey not found");let r=s;if((null===(i=s.appearance)||void 0===i?void 0:i.surveyPopupDelaySeconds)&&t.ignoreDelay&&(r=ls(ls({},s),{},{appearance:ls(ls({},s.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==cl.Popover&&t.initialResponses&&zc.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){const e=this._checkSurveyEligibility(s);if(!e.eligible)return void zc.warn("Survey is not eligible to be displayed: ",e.reason)}t.displayType!==cl.Inline?this._surveyManager.handlePopoverSurvey(r,t):this.renderSurvey(r,t.selector,t.properties)}cancelPendingSurvey(e){St(this._surveyManager)?zc.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e,t;null===(e=this._surveyManager)||void 0===e||null===(t=e.handlePageUnload)||void 0===t||t.call(e)}};function id(e,t,i){if(St(e))return!1;switch(i){case"exact":return e===t;case"contains":{const i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(e)}case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}var sd=class{constructor(e){this._instance=e,this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new kc,this._checkStep=(e,t)=>this._checkStepEvent(e,t)&&this._checkStepUrl(e,t)&&this._checkStepElement(e,t)&&this._checkStepProperties(e,t),this._checkStepEvent=(e,t)=>!(null==t?void 0:t.event)||(null==e?void 0:e.event)===(null==t?void 0:t.event)}init(){var e,t;ft(null===(e=this._instance)||void 0===e?void 0:e._addCaptureHook)||(this._captureHookUnsubscribe=null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook((e,t)=>{this.on(e,t)}))}dispose(){var e,t;null===(e=this._captureHookUnsubscribe)||void 0===e||e.call(this),this._captureHookUnsubscribe=void 0,null===(t=this._instance)||void 0===t||null===(t=t.autocapture)||void 0===t||t.setElementSelectors(new Set,this),this._debugEventEmitter=new kc}register(e){var t,i;if(!ft(null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook)&&(e.forEach(e=>{var t;this._actionRegistry.add(e),null===(t=e.steps)||void 0===t||t.forEach(e=>{this._actionEvents.add((null==e?void 0:e.event)||"")})}),null===(i=this._instance)||void 0===i?void 0:i.autocapture)){const e=new Set;this._actionRegistry.forEach(t=>{var i;null===(i=t.steps)||void 0===i||i.forEach(t=>{(null==t?void 0:t.selector)&&e.add(t.selector)})}),this._instance.autocapture.setElementSelectors(e,this)}}replace(e){this._actionRegistry.clear(),this._actionEvents.clear(),this.register(e)}on(e,t){null!=t&&0!=e.length&&(this._actionEvents.has(e)||this._actionEvents.has(t.event))&&this._actionRegistry.forEach(e=>{this._checkAction(t,e)&&this._debugEventEmitter.emit("actionCaptured",e.name)})}_addActionHook(e){this.onAction("actionCaptured",t=>e(t))}_checkAction(e,t){if(null==(null==t?void 0:t.steps))return!1;for(const i of t.steps)if(this._checkStep(e,i))return!0;return!1}onAction(e,t){return this._debugEventEmitter.on(e,t)}_checkStepUrl(e,t){if(null==t?void 0:t.url){var i;const s=null==e||null===(i=e.properties)||void 0===i?void 0:i.$current_url;if(!s||"string"!=typeof s)return!1;if(!id(s,t.url,t.url_matching||"contains"))return!1}return!0}_checkStepElement(e,t){return!!this._checkStepHref(e,t)&&!!this._checkStepText(e,t)&&!!this._checkStepSelector(e,t)}_checkStepHref(e,t){var i;if(!(null==t?void 0:t.href))return!0;const s=this._getElementsList(e);if(s.length>0)return s.some(e=>id(e.href,t.href,t.href_matching||"exact"));const r=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!r&&id(function(e){const t=e.match(/(?::|")href="(.*?)"/);return t?t[1]:""}(r),t.href,t.href_matching||"exact")}_checkStepText(e,t){var i;if(!(null==t?void 0:t.text))return!0;const s=this._getElementsList(e);if(s.length>0)return s.some(e=>id(e.text,t.text,t.text_matching||"exact")||id(e.$el_text,t.text,t.text_matching||"exact"));const r=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!r&&(n=function(e){const t=[],i=/(?::|")text="(.*?)"/g;let s;for(;!St(s=i.exec(e));)t.includes(s[1])||t.push(s[1]);return t}(r),o=t.text,a=t.text_matching||"exact",n.some(e=>id(e,o,a)));var n,o,a}_checkStepSelector(e,t){var i,s;if(!(null==t?void 0:t.selector))return!0;const r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$element_selectors;if(null==r?void 0:r.includes(t.selector))return!0;const n=(null==e||null===(s=e.properties)||void 0===s?void 0:s.$elements_chain)||"";if(t.selector_regex&&n)try{return new RegExp(t.selector_regex).test(n)}catch(e){return!1}return!1}_getElementsList(e){var t;return null==(null==e||null===(t=e.properties)||void 0===t?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}_checkStepProperties(e,t){return!(null==t?void 0:t.properties)||0===t.properties.length||Lc(t.properties.reduce((e,t)=>{const i=_t(t.value)?t.value.map(String):null!=t.value?[String(t.value)]:[];return e[t.key]={values:i,operator:t.operator||"exact"},e},{}),null==e?void 0:e.properties)}},rd=class{constructor(e,t){var i,s;this._pendingActivatedItems=[],this._instance=e,this._onActivationChanged=t,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map,this._sessionIdUnsubscribe=null===(i=this._instance)||void 0===i||null===(s=i.onSessionId)||void 0===s?void 0:s.call(i,e=>this._onSessionIdChanged(e))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Lc(e.propertyFilters,null==t?void 0:t.properties)}_buildEventToItemMap(e,t){const i=new Map;return e.forEach(e=>{var s;null===(s=e.conditions)||void 0===s||null===(s=s[t])||void 0===s||null===(s=s.values)||void 0===s||s.forEach(t=>{if(null==t?void 0:t.name){const s=i.get(t.name)||[];s.push(e.id),i.set(t.name,s)}})}),i}_getMatchingItems(e,t,i){const s=(i===Xa.Activation?this._eventToItems:this._cancelEventToItems).get(e);let r=[];return this._getItems(e=>{r=e.filter(e=>null==s?void 0:s.includes(e.id))}),r.filter(s=>{var r;const n=null===(r=s.conditions)||void 0===r||null===(r=r[i])||void 0===r||null===(r=r.values)||void 0===r?void 0:r.find(t=>t.name===e);return this._doesEventMatchFilter(n,t)})}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){var i;ft(null===(i=this._instance)||void 0===i?void 0:i._addCaptureHook)||(this._setupEventBasedItems(e,t),this._setupActionBasedItems(e,t))}_setupActionBasedItems(e,t){const i=e.filter(e=>{var t;return null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length});var s;if(t&&this._actionToItems.clear(),0===i.length)return void(t&&(null===(s=this._actionMatcher)||void 0===s||s.replace([])));this._actionMatcher||(this._actionMatcher=new sd(this._instance),this._actionMatcher.init(),this._actionMatcher._addActionHook(e=>this.onAction(e)));const r=[];i.forEach(e=>{var t;null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||t.values.forEach(t=>{if(r.push(t),t.name){var i;const s=null!==(i=this._actionToItems.get(t.name))&&void 0!==i?i:[];s.includes(e.id)||s.push(e.id),this._actionToItems.set(t.name,s)}})}),t?this._actionMatcher.replace(r):this._actionMatcher.register(r)}_mergeItemMaps(e,t){t.forEach((t,i)=>{var s;const r=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach(e=>{r.includes(e)||r.push(e)}),e.set(i,r)})}_setupEventBasedItems(e,t){var i,s;const r=e.filter(e=>{var t,i;return(null===(t=e.conditions)||void 0===t?void 0:t.events)&&(null===(i=e.conditions)||void 0===i||null===(i=i.events)||void 0===i||null===(i=i.values)||void 0===i?void 0:i.length)>0}),n=e.filter(e=>{var t,i;return(null===(t=e.conditions)||void 0===t?void 0:t.cancelEvents)&&(null===(i=e.conditions)||void 0===i||null===(i=i.cancelEvents)||void 0===i||null===(i=i.values)||void 0===i?void 0:i.length)>0}),o=this._buildEventToItemMap(e,Xa.Activation),a=this._buildEventToItemMap(e,Xa.Cancellation);t?(this._eventToItems=o,this._cancelEventToItems=a):(this._mergeItemMaps(this._eventToItems,o),this._mergeItemMaps(this._cancelEventToItems,a)),(0!==r.length||0!==n.length||e.some(e=>{var t;return null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length}))&&(null!==(i=this._captureHookUnsubscribe)&&void 0!==i||(this._captureHookUnsubscribe=null===(s=this._instance)||void 0===s?void 0:s._addCaptureHook((e,t)=>{this.onEvent(e,t)})))}onEvent(e,t){var i,s;const r=this._getLogger(),n=(null==t||null===(i=t.properties)||void 0===i?void 0:i.$survey_id)||(null==t||null===(s=t.properties)||void 0===s?void 0:s.$product_tour_id);if(n&&this.getActivatedIds().includes(n)){const i=this._activationOutcome(e,n,t);if("consume"===i)return r.info("event consumed activated item, removing it",{event:e,itemId:n}),void this._deactivateItems([n]);if("persist"===i)return r.info("shown item promoted to persisted activation",{event:e,itemId:n}),this._persistActivation(n),void this._clearActivationTimestamps([n])}if(this._cancelEventToItems.has(e)){const i=this._getMatchingItems(e,t,Xa.Cancellation);i.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:i.map(e=>e.id)}),this._deactivateItems(i.map(e=>e.id)),i.forEach(e=>this._cancelPendingItem(e.id)))}if(!this._eventToItems.has(e))return;r.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});const o=this._getMatchingItems(e,t,Xa.Activation);this._activateItems(o.map(e=>e.id))}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){var t,i;if(0===e.length)return;const s=!!(null===(t=this._instance)||void 0===t||null===(i=t.get_session_id)||void 0===i?void 0:i.call(t)),r=[];for(const t of e)s&&this._shouldPersistArmedActivation(t)?this._persistActivation(t)&&this._recordActivationTimestamp(t):r.push(t);r.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...r])]),this._getLogger().info("updating activated items",{activatedItems:this.getActivatedIds()}),this._notifyActivationChanged()}_persistActivation(e){this._pendingActivatedItems=this._pendingActivatedItems.filter(t=>t!==e);const t=this._getPersistedActivatedIds();return!t.includes(e)&&(this._setActivatedItems([...t,e]),this._stampActivationSession(),!0)}_deactivateItems(e){const t=new Set(e);this._pendingActivatedItems=this._pendingActivatedItems.filter(e=>!t.has(e));const i=this._getRawPersistedActivatedIds(),s=i.filter(e=>!t.has(e));s.length!==i.length&&(this._setActivatedItems(s),0===s.length&&this._clearActivationSession()),this._clearActivationTimestamps(e),this._notifyActivationChanged()}_notifyActivationChanged(){try{var e;null===(e=this._onActivationChanged)||void 0===e||e.call(this)}catch(e){this._getLogger().error("Error while handling activated items change",e)}}_getRawActivationTimestamps(){var e;const t=this._getActivationTimestampsKey();if(!t)return{};const i=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[t];return i&&"object"==typeof i?i:{}}_recordActivationTimestamp(e){if(!this._getActivationTimestampsKey())return;const t=this._getRawActivationTimestamps();this._writeActivationTimestamps(ls(ls({},t),{},{[e]:Date.now()}))}_clearActivationTimestamps(e){if(!this._getActivationTimestampsKey())return;const t=this._getRawActivationTimestamps(),i={};let s=!1;for(const[r,n]of Object.entries(t))e.includes(r)?s=!0:i[r]=n;s&&(vt(i)?this._clearActivationTimestampsStore():this._writeActivationTimestamps(i))}_clearAllActivationTimestamps(){this._getActivationTimestampsKey()&&this._clearActivationTimestampsStore()}getActivationTimestamp(e){if(!this._getPersistedActivatedIds().includes(e))return;const t=this._getRawActivationTimestamps()[e];return wt(t)?t:void 0}_getRawPersistedActivatedIds(){var e;const t=this._getActivatedKey();return(null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[t])||[]}_getPersistedActivatedIds(){var e,t,i;const s=this._getRawPersistedActivatedIds();if(0===s.length)return[];const r=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[this._getActivatedSessionKey()],n=null===(t=this._instance)||void 0===t||null===(i=t.get_session_id)||void 0===i?void 0:i.call(t);return n&&r===n?s:[]}_stampActivationSession(){var e,t;const i=null===(e=this._instance)||void 0===e||null===(t=e.get_session_id)||void 0===t?void 0:t.call(e);i&&this._setActivatedSession(i)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){var t;const i=null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t?void 0:t.props[this._getActivatedSessionKey()];if(i&&i!==e){const e=this._getRawPersistedActivatedIds(),t=this._getRawActivationTimestamps();e.length>0&&(this._setActivatedItems([]),e.filter(e=>wt(t[e])).forEach(e=>this._cancelPendingItem(e))),this._clearActivationSession(),this._clearAllActivationTimestamps(),e.length>0&&this._notifyActivationChanged()}}getActivatedIds(){return[...new Set([...this._getPersistedActivatedIds(),...this._pendingActivatedItems])].filter(e=>!this._isItemPermanentlyIneligible(e))}dispose(){var e,t,i;null===(e=this._sessionIdUnsubscribe)||void 0===e||e.call(this),this._sessionIdUnsubscribe=void 0,null===(t=this._captureHookUnsubscribe)||void 0===t||t.call(this),this._captureHookUnsubscribe=void 0,null===(i=this._actionMatcher)||void 0===i||i.dispose(),this._actionMatcher=void 0}reset(){this._pendingActivatedItems=[],this._getRawPersistedActivatedIds().length>0&&this._setActivatedItems([]),this._clearActivationSession(),this._clearAllActivationTimestamps(),this._notifyActivationChanged()}getEventToItemsMap(){return this._eventToItems}_getActionMatcher(){return this._actionMatcher}},nd=class extends rd{constructor(e,t){super(e,t)}_getActivatedKey(){return re}_getActivatedSessionKey(){return ne}_getActivationTimestampsKey(){return oe}_writeActivationTimestamps(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated_timestamps:e})}_clearActivationTimestampsStore(){var e;null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e||e.unregister("$surveys_activated_timestamps")}_shouldPersistArmedActivation(e){var t;let i;this._getItems(t=>{i=t.find(t=>t.id===e)});const s=null==i||null===(t=i.appearance)||void 0===t?void 0:t.surveyPopupDelaySeconds;return wt(s)&&s>0}_getShownEventName(){return al.SHOWN}_getItems(e){var t;null===(t=this._instance)||void 0===t||t.getSurveys(e)}_cancelPendingItem(e){var t;null===(t=this._instance)||void 0===t||t.cancelPendingSurvey(e)}_getLogger(){return zc}_setActivatedItems(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated:e})}_setActivatedSession(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated_session:e})}_clearActivatedSession(){var e;null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e||e.unregister("$surveys_activated_session")}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t,i){var s;if(e===al.SENT&&!1===(null==i||null===(s=i.properties)||void 0===s?void 0:s.$survey_completed))return"ignore";let r;return this._getItems(e=>{r=e.find(e=>e.id===t)}),!r||function(e){var t;return $c(e)&&!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t?void 0:t.repeatedActivation)||"always"===e.schedule}(r)?e===al.SHOWN?"consume":"ignore":e===al.SHOWN?"persist":e===al.DISMISSED||e===al.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},od=class{constructor(e){this._instance=e}initialize(){}get(e){if("string"==typeof e)return this._instance.get_property(e);const t={};for(const i of e){const e=this._instance.get_property(i);ft(e)||(t[i]=e)}return t}set(e,t){this._instance.register("string"==typeof e?{[e]:t}:e)}remove(e){"string"!=typeof e?e.forEach(e=>this._instance.unregister(e)):this._instance.unregister(e)}},ad=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=null==tt?void 0:tt.__PosthogExtensions__;if(!e)return;const{generateSurveys:t,loadExternalDependency:i}=e;return{generateSurveys:t?e=>t(this._instance,e):void 0,loadExternalDependency:i?e=>i(this._instance,"surveys",e):void 0}}createEventReceiver(e){return new nd(this._instance,e)}onMatchingConditionsChanged(e){const t=this._instance._addCaptureHook(t=>{"$pageview"!==t&&t!==al.SHOWN&&t!==al.DISMISSED&&t!==al.SENT||e()}),i=()=>e();An(je,"PHSurveyShown",i);let s=!1;const r=this._instance.onFeatureFlags(()=>{s&&e()});return s=!0,()=>{s=!1,t(),r(),null==je||je.removeEventListener("PHSurveyShown",i)}}};const ld=(null==je?void 0:je.location)?Ca(je.location.hash,"__posthog")||Ca(location.hash,"state"):null,cd="_postHogToolbarParams",ud=Cn("[Toolbar]"),dd=Cn("[FeatureFlags]"),hd=Cn("[FeatureFlags]",{debugEnabled:!0}),_d="\" failed. Feature flags didn't load in time.",pd=[502,504],gd=["click","keydown","wheel","touchstart","pointerdown"],vd="connection_error",fd=e=>{const t={};for(let i=0;e.length>i;i++)t[e[i]]=!0;return t},md=e=>{const t={};for(const[i,s]of Fn(e||{}))s&&(t[i]=s);return t};var yd=class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=dd,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._reloadingHandlers=[],this._pendingReloads=new Set,this._activeReloads=new Set,this._hasLoadedFlags=!1,this._requestInFlight=!1,this._requestGeneration=0,this._reloadingDisabled=!1,this._additionalReloadRequested=!1,this._flagsLoadedFromRemote=!1,this._staleCacheRefreshTriggered=!1,this._consecutiveStatusZeroFailures=0,this._hadUserInteraction=!1,this._onOnline=()=>{const e=this._hasStatusZeroCircuitBreakerTripped();this._consecutiveStatusZeroFailures=0,e&&this.reloadFeatureFlags()},this._refreshIfDue=()=>{var e,t;const i=this._refreshIntervalMs,s=null!==(e=this._dueRefreshIntervalMs)&&void 0!==e?e:i;ft(i)||ft(s)||this._config.remoteRequestsDisabled||!this._document||"hidden"===this._document.visibilityState||Date.now()-(null!==(t=this._lastRefreshAt)&&void 0!==t?t:0)<s||(this._dueRefreshIntervalMs=this._hadUserInteraction||!this._config.idleRefreshBackoff?i:Math.min(2*s,36e5),this._hadUserInteraction=!1,this.reloadFeatureFlags(),this._scheduleNextRefresh())},this._onUserInteraction=()=>{this._hadUserInteraction&&this._dueRefreshIntervalMs===this._refreshIntervalMs||this._resumeConfiguredInterval()},this._onVisibilityChange=()=>{var e;"visible"===(null===(e=this._document)||void 0===e?void 0:e.visibilityState)&&this._resumeConfiguredInterval()},this._configSource=e}get _crossTabPersistence(){}_onConfigUpdated(){this._client&&this._syncAutomaticRefresh()}setup(e){try{this._window=typeof window>"u"?void 0:window,this._document=typeof document>"u"?void 0:document}catch(e){this._window=void 0,this._document=void 0}return this._initializingClient=e,this._logger=e.logger.createLogger("[FeatureFlags]"),Zu(e.kv.initialize(),()=>{this._initializingClient===e&&(this._initializingClient=void 0,this._client=e,this._finishSetup(e))})}_finishSetup(e){var t;if(this._client===e)return this._window&&An(this._window,"online",this._onOnline),this._syncAutomaticRefresh(),this._dynamicProperties=e.registerDynamicEventProperties(()=>this._isCacheStale()?this._baseEventProperties:this._eventPropertiesWithFlagValues),this._crossTabPersistenceUnsubscribe=null===(t=this._crossTabPersistence)||void 0===t?void 0:t.onCrossTabFeatureFlagChange(()=>{this._clearBootstrapState(),this._rebuildEventProperties(),this._fireFeatureFlagsCallbacks()}),this._rebuildEventProperties(),this.initialize()}_resumeConfiguredInterval(){this._hadUserInteraction=!0,this._dueRefreshIntervalMs=this._refreshIntervalMs,this._refreshIfDue()}_syncAutomaticRefresh(){var e;const t=this._config.refreshIntervalMs,i=!this._config.remoteRequestsDisabled&&this._document&&!ft(t)&&t>0?t:void 0;this._config.idleRefreshBackoff||(this._dueRefreshIntervalMs=i),i!==this._refreshIntervalMs&&(this._stopAutomaticRefresh(),ft(i)||(this._refreshIntervalMs=i,this._dueRefreshIntervalMs=i,this._scheduleNextRefresh(),(null===(e=this._document)||void 0===e?void 0:e.addEventListener)&&(An(this._document,m,this._onVisibilityChange),kn(gd,e=>{An(this._document,e,this._onUserInteraction,{capture:!0})}))))}_scheduleNextRefresh(){ft(this._refreshIntervalMs)||(ft(this._refreshInterval)||clearInterval(this._refreshInterval),this._lastRefreshAt=Date.now(),this._refreshInterval=setInterval(this._refreshIfDue,this._refreshIntervalMs))}_stopAutomaticRefresh(){var e,t;ft(this._refreshInterval)||(clearInterval(this._refreshInterval),this._refreshInterval=void 0,null===(e=this._document)||void 0===e||null===(t=e.removeEventListener)||void 0===t||t.call(e,"visibilitychange",this._onVisibilityChange),kn(gd,e=>{var t,i;null===(t=this._document)||void 0===t||null===(i=t.removeEventListener)||void 0===i||i.call(t,e,this._onUserInteraction,{capture:!0})})),this._refreshIntervalMs=void 0,this._dueRefreshIntervalMs=void 0,this._hadUserInteraction=!1,this._lastRefreshAt=void 0}destroy(){this._dispose()}dispose(){this._dispose()}_dispose(){var e,t,i;this._stopAutomaticRefresh(),this._requestGeneration++,this._additionalReloadRequested=!1,this._initializingClient=void 0,this._settleReloads(this._pendingReloads,"cancelled"),this._settleReloads(this._activeReloads,"cancelled"),this._client&&(this._clearDebouncer(),null===(e=this._dynamicProperties)||void 0===e||e.dispose(),this._dynamicProperties=void 0,null===(t=this._crossTabPersistenceUnsubscribe)||void 0===t||t.call(this),this._crossTabPersistenceUnsubscribe=void 0,this._reloadingHandlers=[],null===(i=this._window)||void 0===i||i.removeEventListener("online",this._onOnline),this._client=void 0)}get _config(){return this._configSource.get()}_prop(e){var t;return this._bootstrapState&&e in this._bootstrapState?this._bootstrapState[e]:null===(t=this._client)||void 0===t?void 0:t.kv.get(e)}_clearBootstrapState(){return!!this._bootstrapState&&(this._bootstrapState=void 0,!0)}_fallBackToPersistedFlags(){var e;return!ft(null===(e=this._client)||void 0===e?void 0:e.kv.get("$enabled_feature_flags"))&&this._clearBootstrapState()}_set(e){this._persist(()=>{var t;return null===(t=this._client)||void 0===t?void 0:t.kv.set(e)})}_markCrossTabFeatureFlagSnapshot(e,t,i){if(!this._crossTabPersistence||!e.$enabled_feature_flags)return;const s=this._prop("$enabled_feature_flags")||{},o=e.$enabled_feature_flags||{},d=t.flags||t.featureFlags,h=t.flags?Object.entries(t.flags).filter(([,e])=>!(null==e?void 0:e.failed)).map(([e])=>e):[],_=!!t.errorsWhileComputingFlags&&!!t.flags,p=_?h:i&&!_t(d)?Object.keys(d||{}):Array.from(new Set([...Object.keys(s),...Object.keys(o)])),v=this._prop("$feature_flag_payloads")||{},f=e.$feature_flag_payloads||{},m=_||i?p:Array.from(new Set([...Object.keys(v),...Object.keys(f)])),y=!_&&!i,b=!!y||p,S=!!y||m,w={[r]:b,[u]:b,[g]:S};e.$feature_flag_details&&(w[n]=b);for(const t of[l,a,c])ft(e[t])||(w[t]=!0);this._crossTabPersistence.markCrossTabFeatureFlagChanges(w)}_remove(e){this._persist(()=>{var t;return null===(t=this._client)||void 0===t?void 0:t.kv.remove(e)})}_persist(e){try{e()}catch(e){this._logger.error("Failed to update feature flag persistence",e)}}_rebuildEventProperties(){const e={};for(const t of[r,g,l,v]){const i=this._prop(t);ft(i)||(e[t]=i)}this._baseEventProperties=e;const t=ls({},e),i=this._prop(u);if(i)for(const[e,s]of Object.entries(i))t[`$feature/${e}`]=s;this._eventPropertiesWithFlagValues=t}_isCacheStale(){const e=this._config.cacheTtlMs;if(!e||0>=e)return!1;const t=this._prop(a);return"number"!=typeof t||Date.now()-t>e}_checkAndTriggerStaleRefresh(){return!!this._isCacheStale()&&(this._staleCacheRefreshTriggered||this._requestInFlight||(this._staleCacheRefreshTriggered=!0,this._logger.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_getValidEvaluationEnvironments(){const e=this._config.evaluationContexts;return(null==e?void 0:e.length)?e.filter(e=>{const t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid evaluation context found:",e,"Expected non-empty string"),t}):[]}_getValidFlagKeys(){const e=this._config.flagKeys;if(!ft(e))return e.filter(e=>{const t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid flag key found:",e,"Expected non-empty string"),t})}initialize(){var e,t;const i=this._config,s=null!==(e=null===(t=i.bootstrap)||void 0===t?void 0:t.featureFlags)&&void 0!==e?e:{};if(Object.keys(s).length){var r,n;const e=null!==(r=null===(n=i.bootstrap)||void 0===n?void 0:n.featureFlagPayloads)&&void 0!==r?r:{},t=Object.keys(s).filter(e=>!ft(s[e])).reduce((e,t)=>(e[t]=s[t],e),{}),o=Object.keys(e).filter(e=>t[e]).reduce((t,i)=>(t[i]=e[i],t),{});return this._receivedFeatureFlags({featureFlags:t,featureFlagPayloads:o},void 0,{persist:!1})}}updateFlags(e,t,i){var s,r;const n=(null==i?void 0:i.merge)&&null!==(s=this._prop("$enabled_feature_flags"))&&void 0!==s?s:{},o=(null==i?void 0:i.merge)&&null!==(r=this._prop("$feature_flag_payloads"))&&void 0!==r?r:{},a=ls(ls({},n),e),l=ls(ls({},o),t),c={};for(const[e,t]of Object.entries(a))c[e]={key:e,enabled:tr(t),variant:ir(t),reason:void 0,metadata:ft(null==l?void 0:l[e])?void 0:{id:0,version:void 0,description:void 0,payload:l[e]}};this._receivedFeatureFlags({flags:c})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this._prop(n),t=this._prop(v),i=this._prop(f);if(!i&&!t)return e||{};const s=xn({},e||{}),r=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(const e of r){var o,a;const r=s[e],n=null==t?void 0:t[e],l=ft(n)?null!==(o=null==r?void 0:r.enabled)&&void 0!==o&&o:!!n,c=ft(n)?null==r?void 0:r.variant:"string"==typeof n?n:void 0,u=null==i?void 0:i[e],d=ls(ls({},r),{},{enabled:l,variant:l?null!=c?c:null==r?void 0:r.variant:void 0});l!==(null==r?void 0:r.enabled)&&(d.original_enabled=null==r?void 0:r.enabled),c!==(null==r?void 0:r.variant)&&(d.original_variant=null==r?void 0:r.variant),u&&(d.metadata=ls(ls({},null==r?void 0:r.metadata),{},{payload:u,original_payload:null==r||null===(a=r.metadata)||void 0===a?void 0:a.payload})),s[e]=d}return this._override_warning||(this._logger.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:s}),this._override_warning=!0),s}getAllFeatureFlags(){const e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map(i=>{const s=e[i];return{key:i,enabled:tr(s),variant:ir(s),payload:er(t[i])}})}getFlagVariants(){const e=this._prop(u),t=this._prop(v);if(!t)return e||{};const i=xn({},e||{}),s=Object.keys(t);for(let e=0;s.length>e;e++)i[s[e]]=t[s[e]];return this._override_warning||(this._logger.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this._override_warning=!0),i}getFlagPayloads(){const e=this._prop(g),t=this._prop(f);if(!t)return e||{};const i=xn({},e||{}),s=Object.keys(t);for(let e=0;s.length>e;e++)i[s[e]]=t[s[e]];return this._override_warning||(this._logger.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this._override_warning=!0),i}reloadFeatureFlags(){this._reloadingDisabled||this._config.featureFlagsDisabled||this._hasStatusZeroCircuitBreakerTripped()||(this._requestInFlight&&(this._additionalReloadRequested=!0),this._reloadDebouncer||(this._reloadingHandlers.slice().forEach(e=>{try{e()}catch(e){this._logger.error("Error while running feature flags reloading callback",e)}}),this._reloadDebouncer=setTimeout(()=>{this._callFlagsEndpoint()},5)))}reloadFeatureFlagsAsync(){return!this._client||this._reloadingDisabled||this._config.featureFlagsDisabled||this._config.remoteRequestsDisabled||this._hasStatusZeroCircuitBreakerTripped()?Promise.resolve({status:"skipped"}):new Promise(e=>{this._pendingReloads.add(e),this.reloadFeatureFlags()})}_settleReloads(e,t){e.forEach(e=>e({status:t})),e.clear()}_clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}onReloading(e){return this._reloadingHandlers.push(e),()=>{this._reloadingHandlers=this._reloadingHandlers.filter(t=>t!==e)}}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this._reloadingDisabled=e}resetFlagCallReported(){this._remove(_)}_callFlagsEndpoint(e){var t;this._clearDebouncer();const i=this._client;if(!i||this._config.remoteRequestsDisabled||this._hasStatusZeroCircuitBreakerTripped())return void this._settleReloads(this._pendingReloads,"skipped");if(this._requestInFlight)return void(this._additionalReloadRequested=!0);const s={token:i.projectToken,distinct_id:i.distinctId,groups:i.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:ls(ls(ls({},i.initialPersonProperties),this._prop("$stored_person_properties")||{}),{},{$lib:i.library.name,$lib_version:i.library.version}),group_properties:this._prop(d),timezone:va()};ft(i.deviceId)||(s.$device_id=i.deviceId),((null==e?void 0:e.disableFlags)||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);const r=this._getValidEvaluationEnvironments();r.length&&(s.evaluation_contexts=r);const n=this._getValidFlagKeys();ft(n)||(s.flag_keys=n);const a=this._config.onlyEvaluateSurveyFeatureFlags,l="/flags/?v=2"+(a?"&only_evaluate_survey_feature_flags=true":""),c=this._requestGeneration,u=this._pendingReloads;this._pendingReloads=new Set,this._activeReloads=u,this._requestInFlight=!0;const h=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},_=e=>{var t,i;const r=null!==(t=e.json)&&void 0!==t?t:{},n=200!==e.statusCode;if(this._requestInFlight=!1,c!==this._requestGeneration)return void h();if(this._trackStatusZeroReachability(e.statusCode),n||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),s.disable_flags&&!this._additionalReloadRequested)return void this._settleReloads(u,"skipped");this._flagsLoadedFromRemote=!n;const l=[];e.error?l.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?vd:"unknown_error"):200!==e.statusCode&&l.push(`api_error_${e.statusCode}`),r.errorsWhileComputingFlags&&l.push("errors_while_computing_flags");const d=!!(null===(i=r.quotaLimited)||void 0===i?void 0:i.includes("feature_flags"));d&&l.push("quota_limited"),this._set({[o]:l}),d?this._logger.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this._receivedFeatureFlags(r,n,{partialResponse:a}),this._settleReloads(u,s.disable_flags?"skipped":l.length||!r.flags&&!r.featureFlags?"error":"loaded"),h()},p=e=>{this._requestInFlight=!1,c===this._requestGeneration?(this._set({[o]:[vd]}),this._logger.error("Feature flag request failed",e),this._fallBackToPersistedFlags()&&this._fireFeatureFlagsCallbacks(!0),this._settleReloads(u,"error"),h()):h()};let g=null!==(t=this._config.requestMaxRetries)&&void 0!==t?t:1;const v=()=>g>0&&c===this._requestGeneration,f=()=>{if(c!==this._requestGeneration||!this._client||this._config.remoteRequestsDisabled)return this._requestInFlight=!1,this._settleReloads(u,"skipped"),void h();try{i.sendRequest(l,{target:"flags",method:"POST",body:s,compression:this._config.compression,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then(e=>{if((e=>pd.includes(e.statusCode)||(e=>0===e.statusCode&&e.error instanceof Error&&"AbortError"===e.error.name)(e))(e)&&v())return g--,void setTimeout(f,500);_(e)}).catch(p)}catch(e){p(e)}};f()}_hasStatusZeroCircuitBreakerTripped(){return ma(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=ya(e,this._consecutiveStatusZeroFailures,3,()=>this._logger.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(e,t={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return void this._logger.warn('getFeatureFlag for key "'+e+_d);if(this._checkAndTriggerStaleRefresh())return;const s=this.getFeatureFlagResult(e,t);return null!==(i=null==s?void 0:s.variant)&&void 0!==i?i:null==s?void 0:s.enabled}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){const t=this.getFeatureFlagResult(e,{send_event:!1});return null==t?void 0:t.payload}getFeatureFlagResult(e,t={}){if(t.fresh&&!this._flagsLoadedFromRemote)return;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return void this._logger.warn('getFeatureFlagResult for key "'+e+_d);if(this._checkAndTriggerStaleRefresh())return;const i=this.getFlagVariants(),s=e in i,r=i[e],n=this.getFlagPayloads()[e],o=String(r),a=this._prop("$feature_flag_request_id")||void 0,l=this._prop("$feature_flag_evaluated_at")||void 0;let c,u=this._prop("$flag_call_reported")||{};if(this._config.deduplicateCallsPerSession){var d;const e=null===(d=this._client)||void 0===d||null===(d=d.session)||void 0===d?void 0:d.sessionId,t=this._prop(p);e&&e!==t&&(u={},c=e)}if(!t.send_event&&"send_event"in t)c&&this._set({[_]:u,[p]:c});else if(e in u&&u[e].includes(o))c&&this._set({[_]:u,[p]:c});else{var h,g,v,f,m,y,b,S,w,E,C,k,P;_t(u[e])?u[e].push(o):u[e]=[o],this._set(ls({[_]:u},c?{[p]:c}:{}));const t=this.getFeatureFlagDetails(e),i=[...null!==(h=this._prop("$feature_flag_errors"))&&void 0!==h?h:[]];ft(r)&&i.push("flag_missing");const s={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:null!=n?n:null,$feature_flag_request_id:a,$feature_flag_evaluated_at:l,$feature_flag_bootstrapped_response:null!==(g=null===(v=this._config.bootstrap)||void 0===v||null===(v=v.featureFlags)||void 0===v?void 0:v[e])&&void 0!==g?g:null,$feature_flag_bootstrapped_payload:null!==(f=null===(m=this._config.bootstrap)||void 0===m||null===(m=m.featureFlagPayloads)||void 0===m?void 0:m[e])&&void 0!==f?f:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};ft(null==t||null===(y=t.metadata)||void 0===y?void 0:y.has_experiment)||(s.$feature_flag_has_experiment=t.metadata.has_experiment),ft(null==t||null===(b=t.metadata)||void 0===b?void 0:b.version)||(s.$feature_flag_version=t.metadata.version);const d=null!==(S=null==t||null===(w=t.reason)||void 0===w?void 0:w.description)&&void 0!==S?S:null==t||null===(E=t.reason)||void 0===E?void 0:E.code;d&&(s.$feature_flag_reason=d),(null==t||null===(C=t.metadata)||void 0===C?void 0:C.id)&&(s.$feature_flag_id=t.metadata.id),ft(null==t?void 0:t.original_variant)&&ft(null==t?void 0:t.original_enabled)||(s.$feature_flag_original_response=ft(t.original_variant)?t.original_enabled:t.original_variant),(null==t||null===(k=t.metadata)||void 0===k?void 0:k.original_payload)&&(s.$feature_flag_original_payload=null==t||null===(P=t.metadata)||void 0===P?void 0:P.original_payload),i.length&&(s.$feature_flag_error=i.join(",")),this._captureFeatureFlagCalled(s)}return s?{key:e,enabled:!!r,variant:"string"==typeof r?r:void 0,payload:er(n)}:void 0}_captureFeatureFlagCalled(e){try{var t;null===(t=this._client)||void 0===t||t.capture("$feature_flag_called",e)}catch(e){this._logger.error("Failed to capture feature flag call",e)}}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,t){var i=this;return Lt(function*(){const s=i._client;if(!s)return;const r={distinct_id:s.distinctId,token:s.projectToken,person_properties:{$lib:s.library.name,$lib_version:s.library.version}},n=i._getValidEvaluationEnvironments();n.length&&(r.evaluation_contexts=n);const o=i._getValidFlagKeys();let a;ft(o)||(r.flag_keys=o);try{var l;const t=null===(l=(yield s.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:i._config.compression,sentAt:"body",timeoutMs:i._config.requestTimeoutMs})).json)||void 0===l?void 0:l.featureFlagPayloads;a=(null==t?void 0:t[e])||void 0}catch(e){return void i._logger.error("Remote config feature flag request failed",e)}try{t(a)}catch(e){i._logger.error("Remote config feature flag callback failed",e)}})()}isFeatureEnabled(e,t={}){if(t.fresh&&!this._flagsLoadedFromRemote)return t.defaultValue;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return this._logger.warn('isFeatureEnabled for key "'+e+_d),t.defaultValue;const i=this.getFeatureFlag(e,t);return ft(i)?t.defaultValue:!!i}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,i){this._receivedFeatureFlags(e,t,i)}_receivedFeatureFlags(e,t,i){if(!this._client)return;this._hasLoadedFlags=!0;const s=((e,t={},i={},s={},o,d=dd)=>{const h=((e,t)=>{const i=e.flags;if(i){const t=Object.fromEntries(Object.keys(i).map(e=>{var t;return[e,null!==(t=i[e].variant)&&void 0!==t?t:i[e].enabled]})),s=Object.fromEntries(Object.keys(i).filter(e=>i[e].enabled).filter(e=>{var t;return!ft(null===(t=i[e].metadata)||void 0===t?void 0:t.payload)}).map(e=>{var t;return[e,null===(t=i[e].metadata)||void 0===t?void 0:t.payload]}));return ls(ls({},e),{},{featureFlags:t,featureFlagPayloads:s})}return e.featureFlags&&t.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e})(e,d),_=h.flags,p=h.featureFlags,v=h.featureFlagPayloads;if(!p)return;const f=e.requestId,m=e.evaluatedAt;if(_t(p)){d.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const e={};if(p)for(let t=0;p.length>t;t++)e[p[t]]=!0;return{[r]:p,[u]:e,[c]:!1}}let y=p,b=v,S=_;if(null==o?void 0:o.partialResponse){const e=Object.keys(y),r=b||{};y=ls(ls({},t),y),b=ls(ls({},i),r),e.forEach(e=>{e in r||null==b||delete b[e]}),S=ls(ls({},s),S)}else if(e.errorsWhileComputingFlags)if(_){const e=new Set(Object.keys(_).filter(e=>{var t;return!(null===(t=_[e])||void 0===t?void 0:t.failed)}));y=ls(ls({},t),Object.fromEntries(Object.entries(y).filter(([t])=>e.has(t))));const r=Object.fromEntries(Object.entries(b||{}).filter(([t])=>e.has(t)));b=ls(ls({},i),r),e.forEach(e=>{e in r||null==b||delete b[e]}),S=ls(ls({},s),Object.fromEntries(Object.entries(S||{}).filter(([t])=>e.has(t))))}else y=ls(ls({},t),y),b=ls(ls({},i),b),S=ls(ls({},s),S);return ls(ls({[r]:Object.keys(md(y)),[u]:y||{},[g]:b||{},[n]:S||{},[c]:!0===e.minimalFlagCalledEvents},f?{[l]:f}:{}),m?{[a]:m}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),i,this._logger);if(s)if(!1===(null==i?void 0:i.persist)){const e=!ft(this._client.kv.get(u));this._bootstrapState=s,e||this._set(s)}else this._clearBootstrapState(),this._markCrossTabFeatureFlagSnapshot(s,e,!!(null==i?void 0:i.partialResponse)),this._set(s);else t&&this._fallBackToPersistedFlags();t||(this._staleCacheRefreshTriggered=!1),this._fireFeatureFlagsCallbacks(t)}override(e,t=!1){this._logger.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this._overrideFeatureFlags(e)}_overrideFeatureFlags(e){if(this._client){if(!1===e)return this._remove([v,f]),this._fireFeatureFlagsCallbacks(),void hd.info("All overrides cleared");if(_t(e))return this._set({[v]:fd(e)}),this._fireFeatureFlagsCallbacks(),void hd.info("Flag overrides set",{flags:e});if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t;const i=e;this._override_warning=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t);const s={},r=i.flags,n=i.payloads;return r&&(s[v]=_t(r)?fd(r):r),n&&(s[f]=n),Object.keys(s).length&&this._set(s),!1===r&&!1===n?this._remove([v,f]):!1===r?this._remove(v):!1===n&&this._remove(f),this._fireFeatureFlagsCallbacks(),!1===r?hd.info("Flag overrides cleared"):r&&hd.info("Flag overrides set",{flags:r}),void(!1===n?hd.info("Payload overrides cleared"):n&&hd.info("Payload overrides set",{payloads:n}))}if(e&&"object"==typeof e)return this._set({[v]:e}),this._fireFeatureFlagsCallbacks(),void hd.info("Flag overrides set",{flags:e});this._logger.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this._logger.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this._hasLoadedFlags){const{flags:t,flagVariants:i}=this._prepareFeatureFlagsForCallbacks();try{e(t,i)}catch(e){this._logger.error("Error while running feature flags callback",e)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;const n=(this._prop("$early_access_features")||[]).find(t=>t.flagKey===e),o={[`$feature_enrollment/${e}`]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};n&&(a.$early_access_feature_name=n.name),i&&(a.$feature_enrollment_stage=i);const l=ls(ls({},this.getFlagVariants()),{},{[e]:t});null===(s=this._crossTabPersistence)||void 0===s||s.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(o)}),this._set({[r]:Object.keys(md(l)),[u]:l,[h]:ls(ls({},this._prop("$stored_person_properties")||{}),o)}),this._fireFeatureFlagsCallbacks();try{var c;null===(c=this._client)||void 0===c||c.capture("$feature_enrollment_update",a)}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t=!1,i){const r=this._prop(s);!r||t?this._getEarlyAccessFeatures(e,i):e(r)}_getEarlyAccessFeatures(e,t){var i=this;return Lt(function*(){const r=i._client;if(!r)return;const n=t?`&${t.map(e=>`stage=${e}`).join("&")}`:"";let o;try{const e=yield r.sendRequest(`/api/early_access_features/?token=${r.projectToken}${n}`,{target:"api",method:"GET",sentAt:"query"});if(!e.json)return;o=e.json.earlyAccessFeatures,i._set({[s]:o})}catch(e){return void i._logger.error("Early access feature request failed",e)}try{e(o)}catch(e){i._logger.error("Early access feature callback failed",e)}})()}_prepareFeatureFlagsForCallbacks(){const e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(e=>t[e]),flagVariants:Object.keys(t).filter(e=>t[e]).reduce((e,i)=>(e[i]=t[i],e),{})}}_fireFeatureFlagsCallbacks(e){this._rebuildEventProperties();const{flags:t,flagVariants:i}=this._prepareFeatureFlagsForCallbacks();this.featureFlagEventHandlers.forEach(s=>{try{s(t,i,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}})}setPersonPropertiesForFlags(e,t=!0){this._setPersonPropertiesForFlags(e,t)}_setPersonPropertiesForFlags(e,t=!0){const i=this._prop("$stored_person_properties")||{},s=(null==e?void 0:e.$set)||((null==e?void 0:e.$set_once)?{}:e),r=null==e?void 0:e.$set_once,n={};if(r)for(const e in r)({}).hasOwnProperty.call(r,e)&&(e in i||(n[e]=r[e]));this._set({[h]:ls(ls(ls({},i),n),s)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const i=ls({},this._prop("$stored_person_properties")||{});e.forEach(e=>{delete i[e]}),this._set({[h]:i}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this._remove(h),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t=!0){const i=this._prop("$stored_group_properties")||{},s=ls({},i);for(const t of Object.keys(e))s[t]=ls(ls({},i[t]),e[t]);this._set({[d]:s}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this._prop("$stored_group_properties")||{};this._set({[d]:ls(ls({},t),{},{[e]:{}})})}else this._remove(d)}reset(){this._requestGeneration++,this._settleReloads(this._pendingReloads,"cancelled"),this._settleReloads(this._activeReloads,"cancelled"),this._additionalReloadRequested=!1,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._bootstrapState=void 0,this._hasLoadedFlags=!1,this._reloadingDisabled=!1,this._flagsLoadedFromRemote=!1,this.$anon_distinct_id=void 0,this._clearDebouncer(),this._override_warning=!1,this._consecutiveStatusZeroFailures=0}};const bd=Cn("[FeatureFlags]");var Sd=class{constructor(e,t=!1){this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,r,n,o,a,l,c;return{bootstrap:{featureFlags:null!==(i=null===(s=e.bootstrap)||void 0===s?void 0:s.featureFlags)&&void 0!==i?i:void 0,featureFlagPayloads:null!==(r=null===(n=e.bootstrap)||void 0===n?void 0:n.featureFlagPayloads)&&void 0!==r?r:void 0},remoteRequestsDisabled:t,featureFlagsDisabled:!!e.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!e.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!e.advanced_feature_flags_dedup_per_session,cacheTtlMs:e.feature_flag_cache_ttl_ms,refreshIntervalMs:null!==(o=e.remote_config_refresh_interval_ms)&&void 0!==o?o:3e5,idleRefreshBackoff:ft(e.remote_config_refresh_interval_ms),requestTimeoutMs:e.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,null!==(a=e.feature_flag_request_max_retries)&&void 0!==a?a:1),compression:e.disable_compression?void 0:"best-available",evaluationContexts:null!==(l=null!==(c=e.evaluation_contexts)&&void 0!==c?c:e.evaluation_environments)&&void 0!==l?l:[],flagKeys:_t(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(bd.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),ft(e.flag_keys)||_t(e.flag_keys)||bd.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}};const wd=e=>It(e)&&("RangeError"===e.name&&0===e.message.indexOf("Maximum call stack size exceeded")||"InternalError"===e.name&&"too much recursion"===e.message),Ed=Cn("[Error tracking]"),Cd="webkit-masked-url:",kd=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],Pd=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",Cd],xd=["__firefox__","__gCrWeb"],Fd="Refusing to render web experiment since the viewer is a likely bot",Id={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Mc(t,e),not_regex:(e,t)=>!Mc(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},Td=Cn("[Conversations]"),Rd="Conversations not available yet.";function $d(e,t){var i,s,r,n,o,a,l;const c=null!==(i=null==e?void 0:e.flushIntervalMs)&&void 0!==i?i:3e3,u=null!==(s=null==e?void 0:e.maxBufferSize)&&void 0!==s?s:100,d=(null==t?void 0:t.consoleCapture)?void 0:null!==(r=null==e?void 0:e.maxLogsPerInterval)&&void 0!==r?r:1e3,h=ft(d)?Math.max(u,2048):Math.max(u,d),_=ls(ls({},function(){let e="",t="";try{var i;const s="u">typeof globalThis?globalThis:"u">typeof window?window:void 0,r=null==s||null===(i=s.navigator)||void 0===i?void 0:i.userAgent;r&&([e,t]=qi(r))}catch(e){}return function(e,t){const i=function(e){if(e)return{}.hasOwnProperty.call(an,e)?an[e]:e}(e);return ls(ls({},i?{"os.name":i}:{}),t?{"os.version":t}:{})}(e,t)}()),null==e?void 0:e.resourceAttributes);return{serviceName:null!==(n=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==n?n:null==t?void 0:t.serviceNameDefault,serviceVersion:null!==(a=null==_?void 0:_["service.version"])&&void 0!==a?a:null==e?void 0:e.serviceVersion,environment:null!==(l=null==_?void 0:_["deployment.environment"])&&void 0!==l?l:null==e?void 0:e.environment,resourceAttributes:_,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:c,maxBufferSize:u,maxQueueSize:h,maxBatchRecordsPerPost:100,rateCapWindowMs:c,maxLogsPerInterval:d,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}const Md=["debug","log","warn","error","info"],Ad=e=>{for(;null==e?void 0:e.__rrweb_original__;)e=e.__rrweb_original__;return e},Od="console",Ld="__posthogHandledLogsRequestError",Dd=(e,t)=>{const i=e instanceof Error?e:new Error(t);return i[Ld]=!0,i},Nd=e=>!!e&&"object"==typeof e&&!0===e[Ld];var Bd=class{get _coreLogger(){return ls(ls({},this._logger),{},{error:(...e)=>{e.some(Nd)||this._logger.error(...e)}})}constructor(e,t){var i;this._configSource=e,this._getSdkContext=t,this.name="logs",this._isLogsEnabled=!1,this._isLoaded=!1,this._isLoading=!1,this._logger=Cn("[logs]"),this._queue=[],this._consoleQueue=[],this._consecutiveStatusZeroFailures=0,this._setupStarted=!1,this._disposed=!1,this._consoleBuffer=[],this._consoleRecorderUnpatchers=[],this._isRecordingConsole=!1,this._isRecordingConsoleEntry=!1,this._listeningForReconnect=!1,this._onReconnect=()=>{var e,t;this._disposed||(this._consecutiveStatusZeroFailures=0,null===(e=this._core)||void 0===e||e.onReconnect(),null===(t=this._consoleCore)||void 0===t||t.onReconnect())},this._isLogsEnabled=!!(null===(i=e.get())||void 0===i?void 0:i.captureConsoleLogs)}get _isRequestReady(){return!0}_getConsoleLoader(){}_listenForReconnect(){if(!this._listeningForReconnect){try{this._window=typeof window>"u"?void 0:window}catch(e){this._window=void 0}this._window&&(An(this._window,"online",this._onReconnect),this._listeningForReconnect=!0)}}_buildCore(e,t,i,s){this._listenForReconnect();const r=$d(this._configSource.get(),i);return[new fn(this._createHost(e,t),r,this._coreLogger,()=>this._getSdkContext(),e=>e(),void 0,s),r]}_getCore(){const e=this._configSource.get();var t;return this._core&&this._resolvedFrom===e||(null===(t=this._core)||void 0===t||t.reset(),this._resolvedFrom=e,[this._core,this._resolvedConfig]=this._buildCore(()=>this._queue,e=>{this._queue=e})),this._core}_getConsoleCore(){const e=this._configSource.get();var t;return this._consoleCore&&this._consoleResolvedFrom===e||(null===(t=this._consoleCore)||void 0===t||t.reset(),this._consoleResolvedFrom=e,[this._consoleCore,this._consoleResolvedConfig]=this._buildCore(()=>this._consoleQueue,e=>{this._consoleQueue=e},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Od)),this._consoleCore}setup(e){if(!this._disposed&&!this._setupStarted)return this._setupStarted=!0,this._client=e,this._logger=e.logger.createLogger("[logs]"),Zu(e.kv.initialize(),()=>{this._disposed||this._finishSetup(e)})}_finishSetup(e){var t;this._listenForReconnect(),(null===(t=this._configSource.get())||void 0===t?void 0:t.captureConsoleLogs)&&(this._isLogsEnabled=!0),(this._isLogsEnabled||this._configSource.remoteConfigWillArrive&&e.kv.get(this._configSource.captureHintKey))&&this._startConsoleRecorder();let i=!1;const s=e.onRemoteConfig(e=>{var t;i=e.ok&&!0===(null===(t=e.config.logs)||void 0===t?void 0:t.captureConsoleLogs),this.onRemoteConfig(e)});this._disposed?s.dispose():(this._remoteConfigSubscription=s,i||this.loadIfEnabled())}dispose(){var e,t,i,s,r,n,o;this._disposed||(this._disposed=!0,this._stopConsoleRecorder(),null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,this._client=void 0,this._isLoading=!1,null===(t=this._window)||void 0===t||t.removeEventListener("online",this._onReconnect),null===(i=this._consoleLogsDispose)||void 0===i||i.call(this),this._consoleLogsDispose=void 0,null===(s=this._core)||void 0===s||s.clearQueue(),null===(r=this._consoleCore)||void 0===r||r.clearQueue(),null===(n=this._core)||void 0===n||n.reset(),null===(o=this._consoleCore)||void 0===o||o.reset())}onRemoteConfig(e){var t,i;if(this._disposed)return;const s=e.ok?null===(t=e.config.logs)||void 0===t?void 0:t.captureConsoleLogs:void 0;St(s)?this._stopRecorderStartedByPersistedHint():(null===(i=this._client)||void 0===i||i.kv.set(this._configSource.captureHintKey,!!s),s?(this._isLogsEnabled=!0,this._isLoaded||this._startConsoleRecorder(),this.loadIfEnabled()):this._stopRecorderStartedByPersistedHint())}reset(){var e,t,i,s;this._stopConsoleRecorder(),null===(e=this._core)||void 0===e||e.clearQueue(),this._queue=[],null===(t=this._core)||void 0===t||t.reset(),null===(i=this._consoleCore)||void 0===i||i.clearQueue(),this._consoleQueue=[],null===(s=this._consoleCore)||void 0===s||s.reset(),this._consecutiveStatusZeroFailures=0}captureLog(e){!this._disposed&&this._client&&this._getCore().captureLog(e)}captureConsoleLog(e){!this._disposed&&this._client&&this._getConsoleCore().captureLog(e)}captureBufferedConsoleLog(e,t,i){!this._disposed&&this._client&&this._getConsoleCore().captureLog(e,{context:t,occurredAtMs:i})}_onOptOut(){var e;this._stopConsoleRecorder(),null===(e=this._consoleCore)||void 0===e||e.clearQueue(),this._consoleQueue=[]}_stopRecorderStartedByPersistedHint(){this._isLogsEnabled||this._stopConsoleRecorder()}_startConsoleRecorder(){var e;if(this._isRecordingConsole||!(null===(e=this._window)||void 0===e?void 0:e.console))return;const t=$d(this._configSource.get()).maxBufferSize;let i=!0;this._consoleRecorderUnpatchers.push(()=>{i=!1});for(const e of Md){let s;try{s=Ad(this._window.console[e])}catch(e){continue}s&&this._consoleRecorderUnpatchers.push(Au(this._window.console,e,r=>{const n=(...s)=>{try{i&&this._recordConsoleEntry(e,s,t)}catch(e){}return r.apply(this._window.console,s)};return n.__rrweb_original__=s,n}))}this._isRecordingConsole=!0,this._consoleRecorderTimeout=setTimeout(()=>{this._stopConsoleRecorder()},3e4)}_recordConsoleEntry(e,t,i){var s;if(this._isRecordingConsole&&!this._isRecordingConsoleEntry&&0!==t.length)if(null===(s=this._client)||void 0===s?void 0:s.canCapture){if(i>this._consoleBuffer.length){this._isRecordingConsoleEntry=!0;try{this._consoleBuffer.push({level:e,args:t,occurredAtMs:Date.now(),context:this._getSdkContext()})}finally{this._isRecordingConsoleEntry=!1}}}else this._stopConsoleRecorder()}_stopConsoleRecorder(){if(this._consoleBuffer=[],this._isRecordingConsole){this._isRecordingConsole=!1,this._consoleRecorderTimeout&&(clearTimeout(this._consoleRecorderTimeout),this._consoleRecorderTimeout=void 0);for(const e of this._consoleRecorderUnpatchers)e();this._consoleRecorderUnpatchers=[]}}_takeConsoleBuffer(){const e=this._consoleBuffer;return this._stopConsoleRecorder(),e}get logger(){return this._capture_logger||(this._capture_logger={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this._capture_logger}flushLogs(e){this._client&&(e?this._flushViaTransport(e):(this._core&&this._core.flush().catch(e=>this._logFlushError(e)),this._consoleCore&&this._consoleCore.flush().catch(e=>this._logFlushError(e))))}flush(){var e=this;return Lt(function*(){var t,i;const s=null===(t=e._core)||void 0===t?void 0:t.flush().catch(t=>e._logFlushError(t)),r=null===(i=e._consoleCore)||void 0===i?void 0:i.flush().catch(t=>e._logFlushError(t));yield s,yield r})()}_logFlushError(e){Nd(e)||this._logger.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this._disposed||!this._isLogsEnabled||this._isLoaded||this._isLoading)return;const e=this._getConsoleLoader();if(e){this._isLoading=!0;try{e((e,t)=>{if(this._isLoading=!1,!this._disposed&&this._isLogsEnabled)if(e||!t)this._logger.error("Could not load logs script",e),this._stopConsoleRecorder();else{const e=this._takeConsoleBuffer();this._consoleLogsDispose=t.initialize(this._client),this._isLoaded=!0,e.length>0&&t.replay(this._client,e)}})}catch(e){throw this._isLoading=!1,e}}else this._stopConsoleRecorder()}_createHost(e,t){const i=this._client;return{get isDisabled(){return!1},get optedOut(){return!i.canCapture},getPersistedProperty:t=>t===it.LogsQueue?e():void 0,setPersistedProperty(e,i){e===it.LogsQueue&&t(null!=i?i:[])},_sendLogsBatch:e=>this._sendLogsBatch(e),getLibraryId:()=>i.library.name,getLibraryVersion:()=>i.library.version}}_sendLogsBatch(e){return new Promise(t=>{if(ma(this._consecutiveStatusZeroFailures,3))return void t({kind:"fatal",error:Dd(void 0,"logs endpoint is unreachable, dropping batch")});let i=!1;const s=e=>{i||(i=!0,clearTimeout(r),t(e))},r=setTimeout(()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:Dd(void 0,"logs request timed out")})},9e4),n=this._isRequestReady;this._client.sendRequest("/i/v1/logs",{method:"POST",query:{token:this._client.projectToken},body:e,compression:"best-available",timeoutMs:6e4}).then(e=>{var t;const i=e.statusCode;this._trackEndpointReachability(i,n),i>=200&&300>i?s({kind:"ok"}):413===i?s({kind:"too-large"}):0!==i&&408!==i&&429!==i&&500>i?s({kind:"fatal",error:new Error(`logs request failed with status ${i}`)}):0===i?(e.error||this._logger.warn("Logs request failed before receiving an HTTP response"),s({kind:"retry-later",error:Dd(e.error,"logs request failed before receiving an HTTP response")})):s({kind:"retry-later",error:null!==(t=e.error)&&void 0!==t?t:new Error(`logs request failed with status ${i}`)})},e=>{s({kind:"retry-later",error:e})})})}_trackEndpointReachability(e,t){(0!==e||t)&&(this._consecutiveStatusZeroFailures=ya(e,this._consecutiveStatusZeroFailures,3,()=>this._logger.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}_flushViaTransport(e){this._queue.length>0&&this._drainQueueViaTransport(e,this._queue,this._resolvedConfig,this._client.library.name,e=>{this._queue=e}),this._consoleQueue.length>0&&this._drainQueueViaTransport(e,this._consoleQueue,this._consoleResolvedConfig,Od,e=>{this._consoleQueue=e})}_drainQueueViaTransport(e,t,i,s,r){if(0===t.length)return;const n=t.map(e=>e.record);r([]);const o=_n(n,hn(i,this._client.library.name,this._client.library.version),s,this._client.library.version);this._client.sendRequest("/i/v1/logs",{method:"POST",query:{token:this._client.projectToken},body:o,compression:"best-available",transport:e,timeoutMs:6e4}).catch(e=>this._logFlushError(e))}};const qd=Cn("[NetworkMetrics]"),Ud=()=>{var e;return(null==je||null===(e=je.performance)||void 0===e?void 0:e.now)?je.performance.now():Date.now()},Hd={"http:":80,"https:":443},zd=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),jd=(e,t)=>{var i;const s=String(t);return{method:String(e).toUpperCase(),url:(null===(i=Sa(s))||void 0===i?void 0:i.href)||s}},Wd=(e,t,i,s,r,n,o=!1)=>{try{var a,l;const c=r();if(!c)return;const u=i||void 0,d=Ud()-s,h=Sa(t.url);if(h&&"http:"!==h.protocol&&"https:"!==h.protocol)return;const _={url:(null==h?void 0:h.href)||t.url,method:t.method},p=pt(c.name)?c.name(_):mt(c.name)?c.name:"http.client.request.duration";if(!p)return;const g=o&&!u?void 0:((e,t)=>e?400>e?void 0:String(e):(null==t?void 0:t.name)||"_OTHER")(u,n),v=ls(ls(ls(ls(ls({},(e=>{const t=zd.has(e)?e:"_OTHER";return ls({"http.request.method":t},"_OTHER"===t&&e!==t?{"http.request.method_original":e}:{})})(_.method)),h?(e=>{return{"server.address":e.hostname.startsWith("[")&&e.hostname.endsWith("]")?e.hostname.slice(1,-1):e.hostname,"server.port":Number(e.port)||Hd[e.protocol],"url.scheme":e.protocol.slice(0,-1),"url.template":(t=e.pathname,t.split("/").map(e=>(e=>/^\d+$/.test(e)||e.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(e))(e)?":id":e).join("/"))};var t})(h):{}),u?{"http.response.status_code":u}:{}),g?{"error.type":g}:{}),null===(a=c.attributes)||void 0===a?void 0:a.call(c,_,{status:u,durationMs:d}));null===(l=e.metrics)||void 0===l||l.histogram(p,d,{unit:"ms",attributes:v})}catch(e){qd.error("Failed to record network metric",e)}},Vd=()=>{},Gd=(e,t)=>pt(null==je?void 0:je.fetch)?Au(je,"fetch",i=>function(...s){const r=Ud(),n=i.apply(this,s);if(!t())return n;try{var o,a,l;const[i,c]=s,u=jd(null!==(o=null!==(a=null==c?void 0:c.method)&&void 0!==a?a:null==i?void 0:i.method)&&void 0!==o?o:"GET",null!==(l=null==i?void 0:i.url)&&void 0!==l?l:i);return n.then(i=>(Wd(e,u,null==i?void 0:i.status,r,t,void 0,!0),i),i=>{throw Wd(e,u,void 0,r,t,i),i})}catch(e){return qd.error("Failed to observe fetch",e),n}}):Vd,Kd=(e,t)=>{var i;const s=null==je||null===(i=je.XMLHttpRequest)||void 0===i?void 0:i.prototype;if(!s)return Vd;const r=new WeakMap,n=Au(s,"open",e=>function(...t){try{(()=>Xl.has(this))()||r.set(this,jd(t[0],t[1]))}catch(e){qd.error("Failed to observe XHR open",e)}return e.apply(this,t)}),o=Au(s,"send",i=>function(...s){let n;try{const i=r.get(this);if(i&&t()){const s=Ud();n=()=>{this.removeEventListener("loadend",n),Wd(e,i,this.status,s,t)},An(this,"loadend",n)}}catch(e){qd.error("Failed to observe XHR send",e)}try{return i.apply(this,s)}catch(e){throw n&&this.removeEventListener("loadend",n),e}});return()=>{n(),o()}},Qd=new WeakMap,Jd=new Set(["$comment","$defs","$id","$schema","additionalProperties","default","definitions","deprecated","description","examples","minProperties","properties","readOnly","required","title","type","writeOnly"]),Yd={maxStringLength:2048,truncationSuffix:"..."},Zd={maxStringLength:2048,truncationSuffix:"..."};function Xd(e){if(e)return!0===e?{intent:!0,model:!0}:{intent:!1!==e.intent,model:!1!==e.model}}function eh(e,t){return{}.hasOwnProperty.call(e,t)}function th(e,t){const i=Object.create(e);return t&&Object.defineProperty(i,"inputSchema",{configurable:!0,enumerable:!0,writable:!0,value:t}),i}function ih(e,t,i=!1){if(!mt(e))return;const s=e.trim();return s?(i?Qr(s,Yd):s).slice(0,t):void 0}function sh(e){try{return gt(e)&&!0===e.isError}catch(e){return!1}}function rh(e,t){try{return Qr((t?function(e){try{if(!gt(e)||!_t(e.content))return;return e.content.filter(e=>gt(e)&&"text"===e.type&&mt(e.text)).map(e=>e.text).join(" ").trim()||void 0}catch(e){return}}(e):gt(e)&&mt(e.message)?e.message:mt(e)?e:String(e))||"Unknown error",Zd).slice(0,2048)}catch(e){return"Unknown error"}}function nh(e,t){if(t)return"Error";try{if(!gt(e))return"Error";let t=mt(e.name)?e.name.trim():"";const i=e.constructor;return t&&"Error"!==t||!pt(i)||"Error"===i.name||(t=i.name),(t||"Error").slice(0,256)}catch(e){return"Error"}}function oh(e,t){return{message:rh(e,t),type:nh(e,t)}}const ah={featureFlags:class extends yd{constructor(e){const t=new Sd(e.config,e._shouldDisableFlags());super(t),this.name=Yc,this._instance=e,this._mutableConfigSource=t}get _crossTabPersistence(){return this._instance.persistence}updateConfig(e,t){this._mutableConfigSource.update(e,t),this._onConfigUpdated()}}},lh={sessionRecording:class{get _config(){return this._instance.config}get _persistence(){return this._instance.persistence}get started(){var e;return!!(null===(e=this._lazyLoadedSessionRecording)||void 0===e?void 0:e.isStarted)}get status(){var e,t;return"awaiting_config"===this._recordingStatus||"missing_config"===this._recordingStatus?this._recordingStatus:null!==(e=null===(t=this._lazyLoadedSessionRecording)||void 0===t?void 0:t.status)&&void 0!==e?e:this._recordingStatus}constructor(e){if(this._instance=e,this._forceAllowLocalhostNetworkCapture=!1,this._recordingStatus=Uu,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._documentWasEverVisible=(()=>{var e,t;if(!(null==Ge?void 0:Ge.visibilityState)||"visible"===Ge.visibilityState)return!0;const i=null==je||null===(e=je.performance)||void 0===e||null===(t=e.getEntriesByType)||void 0===t?void 0:t.call(e,"visibility-state");return!(null==i?void 0:i.length)||i.some(e=>"visible"===e.name)})(),this._onVisibilityChange=()=>{var e,t;"visible"===(null==Ge?void 0:Ge.visibilityState)&&(this._documentWasEverVisible=!0,null===(e=this._lazyLoadedSessionRecording)||void 0===e||null===(t=e.setDocumentWasEverVisible)||void 0===t||t.call(e,!0))},!this._instance.sessionManager)throw zu.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if("always"===this._config.cookieless_mode)throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');(null==Ge?void 0:Ge.addEventListener)&&An(Ge,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this._sessionRecordingDisposed=!0,null==Ge||null===(t=Ge.removeEventListener)||void 0===t||t.call(Ge,"visibilitychange",this._onVisibilityChange),e?this._discardRecording(!0):this.stopRecording()}get _isRecordingEnabled(){var e;const t=!!(null===(e=this._instance.get_property("$session_recording_remote_config"))||void 0===e?void 0:e.enabled),i=!this._config.disable_session_recording,s=this._config.disable_session_recording||this._instance.consent.isOptedOut();return je&&t&&i&&!s}startIfEnabledOrStop(e){var t;if(this._sessionRecordingDisposed)return;if(this._isRecordingEnabled&&(null===(t=this._lazyLoadedSessionRecording)||void 0===t?void 0:t.isStarted))return;const i=!ft(Object.assign)&&!ft(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),zu.info("starting")):(this._recordingStatus=Uu,this.stopRecording())}_lazyLoadAndStart(e){var t,i;if(this._isRecordingEnabled)if("awaiting_config"!==this._recordingStatus&&"missing_config"!==this._recordingStatus&&(this._recordingStatus=Hu),(null==tt||null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t?void 0:t.record)&&(null===(i=tt.__PosthogExtensions__)||void 0===i?void 0:i.initSessionRecording))this._onScriptLoaded(e);else{var s,r;const t=this._instance.sessionManager;null===(s=tt.__PosthogExtensions__)||void 0===s||null===(r=s.loadExternalDependency)||void 0===r||r.call(s,this._instance,this._scriptName,i=>{if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager===t)return i?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),zu.error("could not load recorder",i)):void this._onScriptLoaded(e);this._recordingStatus="disabled"})}}stopRecording(){var e,t;null===(e=this._persistFlagsOnSessionListener)||void 0===e||e.call(this),this._persistFlagsOnSessionListener=void 0,null===(t=this._lazyLoadedSessionRecording)||void 0===t||t.stop()}_discardRecording(e=!1){var t,i;null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=void 0,null===(i=this._lazyLoadedSessionRecording)||void 0===i||i.discard({discardProducerEvents:e})}_resetSampling(){var e,t;null===(e=this._persistence)||void 0===e||e.unregister("$session_is_sampled"),null===(t=this._persistence)||void 0===t||t.unregister("$replay_sample_rate")}_validateSampleRate(e,t){if(St(e))return null;const i=wt(e)?e:parseFloat(e);return"number"!=typeof(s=i)||!Number.isFinite(s)||0>s||s>1?(zu.warn(`${t} must be between 0 and 1. Ignoring invalid value:`,e),null):i;var s}_persistRemoteConfig(e){if(this._persistence){var t,i;const s=this._persistence,r=()=>{var t;const i=!1===e.sessionRecording?void 0:e.sessionRecording,r=this._validateSampleRate(null===(t=this._config.session_recording)||void 0===t?void 0:t.sampleRate,"session_recording.sampleRate"),n=this._validateSampleRate(null==i?void 0:i.sampleRate,"remote config sampleRate"),o=null!=r?r:n;St(o)&&this._resetSampling();const a=null==i?void 0:i.minimumDurationMilliseconds;s.register({[U]:ls(ls({cache_timestamp:Date.now(),enabled:!!i},i),{},{networkPayloadCapture:ls({capturePerformance:e.capturePerformance},null==i?void 0:i.networkPayloadCapture),canvasRecording:{enabled:null==i?void 0:i.recordCanvas,fps:null==i?void 0:i.canvasFps,quality:null==i?void 0:i.canvasQuality},sampleRate:o,minimumDurationMilliseconds:ft(a)?null:a,endpoint:null==i?void 0:i.endpoint,triggerMatchType:null==i?void 0:i.triggerMatchType,masking:null==i?void 0:i.masking,urlTriggers:null==i?void 0:i.urlTriggers,version:null==i?void 0:i.version,triggerGroups:null==i?void 0:i.triggerGroups})})};r(),null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=null===(i=this._instance.sessionManager)||void 0===i?void 0:i.onSessionId(r)}}onRemoteConfig(e){const t=e.ok?e.config:void 0;return t&&"sessionRecording"in t?!1===t.sessionRecording?(this._persistRemoteConfig(t),void this._discardRecording()):(this._persistRemoteConfig(t),void this.startIfEnabledOrStop()):("awaiting_config"===this._recordingStatus&&(this._recordingStatus="missing_config",this._instance.register_for_session({[Pe]:!0}),zu.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t="log"){var i;(null===(i=this._lazyLoadedSessionRecording)||void 0===i?void 0:i.log)?this._lazyLoadedSessionRecording.log(e,t):zu.warn("log called before recorder was ready")}get _scriptName(){var e,t;const i=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.get_property(U);return(null==i||null===(t=i.scriptConfig)||void 0===t?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){const e=this._instance.get_property(U);if(!e)return!1;let t;try{t="object"==typeof e?e:JSON.parse(e)}catch(e){return zu.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!St(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}_onScriptLoaded(e){var t,i,s;if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager){if(!(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.initSessionRecording))return zu.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ke]:!0});var r;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null===(r=tt.__PosthogExtensions__)||void 0===r?void 0:r.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._isRemoteConfigFresh()){if("missing_config"===this._recordingStatus||"awaiting_config"===this._recordingStatus)return;return this._recordingStatus="awaiting_config",zu.info("persisted remote config is stale, requesting fresh config before starting"),void new fl(this._instance).load()}this._recordingStatus=Hu,null===(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||void 0===i||i.call(s,this._documentWasEverVisible),this._lazyLoadedSessionRecording.start(e)}else this._recordingStatus=Uu}onRRwebEmit(e){var t,i;null===(t=this._lazyLoadedSessionRecording)||void 0===t||null===(i=t.onRRwebEmit)||void 0===i||i.call(t,e)}overrideLinkedFlag(){var e,t;this._lazyLoadedSessionRecording||null===(t=this._persistence)||void 0===t||t.register({$replay_override_linked_flag:!0}),null===(e=this._lazyLoadedSessionRecording)||void 0===e||e.overrideLinkedFlag()}overrideSampling(){var e,t;this._lazyLoadedSessionRecording||null===(t=this._persistence)||void 0===t||t.register({$replay_override_sampling:!0}),null===(e=this._lazyLoadedSessionRecording)||void 0===e||e.overrideSampling()}overrideTrigger(e){var t,i;this._lazyLoadedSessionRecording||null===(i=this._persistence)||void 0===i||i.register({["url"===e?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),null===(t=this._lazyLoadedSessionRecording)||void 0===t||t.overrideTrigger(e)}get sdkDebugProperties(){var e;const t={};for(const e of ju){var i;const s=null===(i=this._instance.sessionPersistence)||void 0===i?void 0:i.get_property(e);ft(s)||(t[e]=s)}return ls(ls({},t),(null===(e=this._lazyLoadedSessionRecording)||void 0===e?void 0:e.sdkDebugProperties)||{$recording_status:this.status})}tryAddCustomEvent(e,t){var i;return!!(null===(i=this._lazyLoadedSessionRecording)||void 0===i?void 0:i.tryAddCustomEvent(e,t))}flushBeforeIdentityReset(){var e,t;null===(e=this._lazyLoadedSessionRecording)||void 0===e||null===(t=e.flushBeforeIdentityReset)||void 0===t||t.call(e)}}},ch={autocapture:class extends Iu{constructor(e){super(new Tu(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._isFlushingPageview=!1,this._instance=e,this._lastLocation=this._getCurrentLocation()}initialize(){this.startIfEnabled()}get isEnabled(){const e=this._getCaptureOptions();return!!(e.path||e.search||this._shouldCaptureHashChanges(e))}startIfEnabled(){this.isEnabled&&(En.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this._lastLocation=this._getCurrentLocation(),this.startIfEnabled()}stop(){this._popstateListener&&this._popstateListener(),this._popstateListener=void 0,this._hashchangeListener&&this._hashchangeListener(),this._hashchangeListener=void 0,En.info("History API monitoring stopped")}monitorHistoryChanges(){je&&je.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(!je||(null===(t=je.history[e])||void 0===t?void 0:t.__posthog_wrapped__))return;const i=this;Au(je.history,e,t=>function(s,r,n){var o;i._isUrlChanging(n)&&i._flushPendingPageview(),t.call(this,s,r,n),i._capturePageview(e,!i._isFlushingPageview&&"popstate"!==(null==je||null===(o=je.event)||void 0===o?void 0:o.type))})}_getCurrentLocation(){const e=null==je?void 0:je.location;if(null==e?void 0:e.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}_getCaptureOptions(){const e=this._instance.config.capture_pageview;return"history_change"===e?{path:!0}:gt(e)?e:{}}_shouldCaptureHashChanges(e=this._getCaptureOptions()){return!!e.hash&&!this._instance.config.disable_capture_url_hashes}_hasLocationChanged(e){const t=this._getCaptureOptions(),i=this._lastLocation;return!(!i||!(t.path&&e.pathname!==i.pathname||t.search&&e.search!==i.search||this._shouldCaptureHashChanges(t)&&e.hash!==i.hash))}_capturePageview(e,t=!1){try{t||this._flushPendingPageview();const i=this._getCurrentLocation();if(!i)return;if(this._hasLocationChanged(i)){const i=()=>this._instance.capture(qe,{navigation_type:e});t?(this._pendingPageview=i,Promise.resolve().then(()=>this._flushPendingPageview())):i()}this._lastLocation=i}catch(t){En.error(`Error capturing ${e} pageview`,t)}}_isUrlChanging(e){var t,i;return!(St(e)||!je)&&(null===(t=Sa(String(e)))||void 0===t?void 0:t.href)!==(null===(i=je.location)||void 0===i?void 0:i.href)}_flushPendingPageview(){const e=this._pendingPageview;if(e){this._pendingPageview=void 0,this._isFlushingPageview=!0;try{e()}catch(e){En.error("Error capturing deferred pageview",e)}finally{this._isFlushingPageview=!1}this._lastLocation=this._getCurrentLocation()}}_setupPopstateListener(){if(this._popstateListener)return;const e=()=>{this._capturePageview("popstate")};An(je,"popstate",e),this._popstateListener=()=>{je&&je.removeEventListener("popstate",e)}}_setupHashchangeListener(){if(this._hashchangeListener)return;const e=()=>{this._capturePageview("hashchange")};An(je,"hashchange",e),this._hashchangeListener=()=>{je&&je.removeEventListener("hashchange",e)}}},heatmaps:class{get _config(){return this.instance.config}constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._flushInterval=null,this.instance=e,this._enabledServerSide=!!(null===(t=this.instance.persistence)||void 0===t?void 0:t.props[R]),this.rageclicks=new Eu(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return gt(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return St(this._config.capture_heatmaps)?St(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Wu.info("starting..."),this._setupListeners(),this._onVisibilityChange()}else{var e;clearInterval(null!==(e=this._flushInterval)&&void 0!==e?e:void 0),this._removeListeners(),this.getAndClearBuffer()}}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("heatmaps"in t))return;const i=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[R]:i}),this._enabledServerSide=i,this.startIfEnabled()}getAndClearBuffer(){const e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){Vu(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval="visible"===(null==Ge?void 0:Ge.visibilityState)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){je&&Ge&&(this._flushHandler=this._flush.bind(this),An(je,Be,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==je?void 0:je.event)),An(Ge,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==je?void 0:je.event)),An(Ge,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new na(this.instance,sa,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),An(Ge,m,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;je&&Ge&&(this._flushHandler&&je.removeEventListener(Be,this._flushHandler),this._onClickHandler&&Ge.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&Ge.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&Ge.removeEventListener(m,this._onVisibilityChange_handler),clearTimeout(this._mouseMoveTimeout),null===(e=this._deadClicksCapture)||void 0===e||e.stop(),this._initialized=!1)}_getProperties(e,t){const i=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),n=function(e,t,i){let s=e;for(;s&&po(s)&&!go(s,"body");){if(s===i)return!1;let e;try{var r,n,o;e=null===(r=null!==(n=null===(o=s.ownerDocument)||void 0===o?void 0:o.defaultView)&&void 0!==n?n:je)||void 0===r?void 0:r.getComputedStyle(s).position}catch(e){return!1}if(ot(t,e))return!0;s=xo(s)}return!1}(Eo(e),["fixed","sticky"],r);return{x:e.clientX+(n?0:s),y:e.clientY+(n?0:i),target_fixed:n,type:t}}_onClick(e,t="click"){var i;if(_o(e.target)||!Vu(e))return;const s=this._getProperties(e,t);(null===(i=this.rageclicks)||void 0===i?void 0:i.isRageClick(e.clientX,e.clientY,(new Date).getTime()))&&Bo(Eo(e),this.instance.config.rageclick)&&this._capture(ls(ls({},s),{},{type:"rageclick"})),this._capture(s)}_onMouseMove(e){!_o(e.target)&&Vu(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(e,"mousemove"))},500))}_capture(e){if(!je)return;const t=this._config.disable_capture_url_hashes?es(je.location.href):je.location.href,i=this._config.custom_personal_data_properties,s=this._config.mask_personal_data_properties?[...ka,...i||[]]:[],r=Ea(t,s,xa);this._buffer=this._buffer||{},this._buffer[r]||(this._buffer[r]=[]),this._buffer[r].push(e)}_flush(){this._buffer&&!vt(this._buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:na,webVitalsAutocapture:class{constructor(e){var t;this._instance=e,this._enabledServerSide=!1,this._initialized=!1,this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this._flushToCapture=()=>{clearTimeout(this._delayedFlushTimer),this._delayedFlushTimer=void 0,0!==this._buffer.metrics.length&&(this._instance.capture("$web_vitals",ls({$current_url:this._buffer.url},this._buffer.metrics.reduce((e,t)=>ls(ls({},e),{},{[`$web_vitals_${t.name}_event`]:ls({},t),[`$web_vitals_${t.name}_value`]:t.value}),{}))),this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this._addToBuffer=e=>{var t;if(this._buffer=this._buffer||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},St(null==e?void 0:e.name)||St(null==e?void 0:e.value))return void Lu.error("Invalid metric received",e);const i="string"==typeof e.navigationURL?e.navigationURL:void 0,s=this._maskedURL(i);if(ft(s))return;const r=wt(e.navigationId)||"string"==typeof e.navigationId?`navigation:${e.navigationId}`:`url:${s}`;if(this._maxAllowedValue&&e.value>=this._maxAllowedValue)return void Lu.error("Ignoring metric with value >= "+this._maxAllowedValue,e);this._buffer.navigationKey!==r&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),ft(this._buffer.navigationKey)&&(this._buffer.navigationKey=r,this._buffer.url=s),this._buffer.firstMetricTimestamp=ft(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;const n=null===(t=this._instance.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0),o=ls(ls(ls({},e),i?{navigationURL:s}:{}),{},{$current_url:s,timestamp:Date.now()});if(delete o.entries,gt(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){const t={};for(const i of qu){const s="url"===i&&"string"==typeof e.attribution[i]?this._maskedURL(e.attribution[i]):e.attribution[i];ft(s)||(t[i]=s)}o.attribution=t}else delete o.attribution;ft(n)||(o.$session_id=n.sessionId,o.$window_id=n.windowId),this._buffer.metrics.push(o),this._buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()},this._startCapturing=()=>{if(this._initialized)return;let e,t,i,s,r=!1;const n=tt.__PosthogExtensions__,o=null==n?void 0:n.postHogWebVitalsCallbacksByFlavor,a=(null==o?void 0:o[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&ft(o)?null==n?void 0:n.postHogWebVitalsCallbacks:void 0);if(!ft(a)){const n=a.withoutAttribution,o=this.attributionMetrics;r=!ft(n),e=o.indexOf("LCP")>-1?a.onLCP:(null==n?void 0:n.onLCP)||a.onLCP,t=o.indexOf("CLS")>-1?a.onCLS:(null==n?void 0:n.onCLS)||a.onCLS,i=o.indexOf("FCP")>-1?a.onFCP:(null==n?void 0:n.onFCP)||a.onFCP,s=o.indexOf("INP")>-1?a.onINP:(null==n?void 0:n.onINP)||a.onINP}if(!(e&&t&&i&&s))return void Lu.error("web vitals callbacks not loaded - not starting");const l={reportSoftNavs:this.useSoftNavs},c=r&&this.attributionMetrics.indexOf("INP")>-1?ls(ls({},l),{},{includeProcessedEventEntries:!1}):l;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("FCP")>-1&&i(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("INP")>-1&&s(this._addToBuffer.bind(this),c),this._initialized=!0},this._enabledServerSide=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[L]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const i=gt(this._perfConfig)?null===(e=this._perfConfig)||void 0===e?void 0:e.web_vitals_allowed_metrics:void 0;return St(i)?(null===(t=this._instance.persistence)||void 0===t?void 0:t.props.$web_vitals_allowed_metrics)||Nu:i}get flushToCaptureTimeoutMs(){return(gt(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=gt(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return Ct(e)?e?Nu:[]:_t(e)?e:Bu}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=gt(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){const e=gt(this._perfConfig)&&wt(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:Du;return e>0&&6e4>=e?Du:e}get isEnabled(){const e=null==Ke?void 0:Ke.protocol;if("http:"!==e&&"https:"!==e)return Lu.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=gt(this._perfConfig)?this._perfConfig.web_vitals:Ct(this._perfConfig)?this._perfConfig:void 0;return Ct(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(Lu.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const i=gt(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=gt(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[L]:i}),this._instance.persistence.register({[q]:s})),this._enabledServerSide=i,this.startIfEnabled()}get _callbackFlavor(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}_loadScript(e){var t;const i=tt.__PosthogExtensions__,s=this._callbackFlavor,r=null==i?void 0:i.postHogWebVitalsCallbacksByFlavor;(null==r?void 0:r[s])||"web-vitals"===s&&ft(r)&&(null==i?void 0:i.postHogWebVitalsCallbacks)?e():null==i||null===(t=i.loadExternalDependency)||void 0===t||t.call(i,this._instance,s,t=>{t?Lu.error("failed to load script",t):e()})}_maskedURL(e){const t=e||(null==je?void 0:je.location.href);if(!t)return void Lu.error("Could not determine current URL");const i=this._instance.config.disable_capture_url_hashes?es(t):t,s=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ka,...s||[]]:[];return Ea(i,r,xa)}}},uh={exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(!je||!this.isEnabled||!(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.errorWrappingFunctions))return;const t=tt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=tt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=tt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this._unwrapOnError&&this._config.capture_unhandled_errors&&(this._unwrapOnError=t(this.captureException.bind(this))),!this._unwrapUnhandledRejection&&this._config.capture_unhandled_rejections&&(this._unwrapUnhandledRejection=i(this.captureException.bind(this))),!this._unwrapConsoleError&&this._config.capture_console_errors&&(this._unwrapConsoleError=s(this.captureException.bind(this)))}catch(e){Ru.error("failed to start",e),this._stopCapturing()}},this._instance=e,this._remoteEnabled=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[M]),this._rateLimiter=new Ut(ls(ls({},function(e={}){var t,i,s,r;return{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(r=e.exceptionRateLimiterBucketSize)&&void 0!==r?r:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking)),{},{refillInterval:1e4,_logger:Ru})),this._config=this._requiredConfig(),this.startIfEnabledOrStop()}_requiredConfig(){const e=this._instance.config.capture_exceptions;let t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?t=ls(ls({},t),e):(ft(e)?this._remoteEnabled:e)&&(t=ls(ls({},t),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this._config.capture_console_errors||this._config.capture_unhandled_errors||this._config.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ru.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.errorWrappingFunctions)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"exception-autocapture",t=>{if(t)return Ru.error("failed to load script",t);e()})}_stopCapturing(){var e,t,i;null===(e=this._unwrapOnError)||void 0===e||e.call(this),this._unwrapOnError=void 0,null===(t=this._unwrapUnhandledRejection)||void 0===t||t.call(this),this._unwrapUnhandledRejection=void 0,null===(i=this._unwrapConsoleError)||void 0===i||i.call(this),this._unwrapConsoleError=void 0}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"autocaptureExceptions"in t&&(this._remoteEnabled=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[M]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}onConfigChange(){this._config=this._requiredConfig()}captureException(e){try{var t,i,s;const r=null!==(t=null==e||null===(i=e.$exception_list)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.type)&&void 0!==t?t:"Exception";if(this._rateLimiter.consumeRateLimit(r))return void Ru.info("Skipping exception capture because of client rate limiting.",{exception:r});null===(s=this._instance.exceptions)||void 0===s||s.sendExceptionEvent(e)}catch(e){}}},exceptions:class{constructor(e){var t,i;this._suppressionRules=[],this._errorPropertiesBuilder=new gs([new Ls,new Vs,new Ns,new Ds,new js,new zs,new qs,new Ws],function(e,...t){return(i,s=0)=>{const r=[],n=i.split("\n"),o=Math.min(n.length,s+1e3),a=[];for(let i=s;o>i;i++){const s=n[i];if(s.length>1024)continue;const o=Fs.test(s)?s.replace(Fs,"$1"):s;if(!o.match(/\S*Error: /)){for(const i of t){const t=i(o,e);if(t){r.push(t);const e=Ts(r);if(e){for(let t=a.length-1;t>=0;t--){const i=a[t];if(e.start>=i.start+i.length)break;a.pop()}a.push(e)}break}}if(As(r,a)>=50)break}}const l=[...a].sort((e,t)=>t.start-e.start),c=l[l.length-1];if(c){const e=$s(r,c);r.splice(c.start-e,e);for(const t of l)t.start-=e}for(const e of l)Rs(r,e);return a.some(e=>0===e.start&&r.length===e.length)&&function(e){const t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`);let i=0;for(let e=1;t.length>e;e++)Os(t,e,i)&&(i=e);e.push(...e.splice(0,i))}(r),function(e){if(!e.length)return[];const t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{return ls(ls({},e),{},{filename:e.filename||(i=t,i[i.length-1]||{}).filename,function:e.function||"?"});var i})}(r)}}("web:javascript",Cs,xs)),this._instance=e,this._suppressionRules=null!==(t=null===(i=this._instance.persistence)||void 0===i?void 0:i.get_property("$error_tracking_suppression_rules"))&&void 0!==t?t:[],this._exceptionStepsConfig=Ys(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new Zs(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=Ys(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(!e.ok)return;const r=e.config;if(!("errorTracking"in r))return;const n=null!==(t=null===(i=r.errorTracking)||void 0===i?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null===(s=r.errorTracking)||void 0===s?void 0:s.captureExtensionExceptions;this._suppressionRules=n,this._instance.persistence&&this._instance.persistence.register({[A]:this._suppressionRules,[O]:o})}get _captureExtensionExceptions(){var e;const t=!!this._instance.get_property(O),i=this._instance.config.error_tracking.captureExtensionExceptions;return null!==(e=null!=i?i:t)&&void 0!==e&&e}buildProperties(e,t){return this._errorPropertiesBuilder.buildFromUnknown(e,{syntheticException:null==t?void 0:t.syntheticException,mechanism:{handled:null==t?void 0:t.handled}})}addExceptionStep(e,t){if(this._exceptionStepsConfig.enabled)try{if(!mt(e)||0===e.trim().length)return void Ed.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:i,droppedKeys:s}=function(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};const t=[];return{sanitizedProperties:Object.keys(e).reduce((i,s)=>Qs.has(s)?(t.push(s),i):(i[s]=e[s],i),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t));s.length>0&&Ed.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this._exceptionStepsBuffer.add(ls({[Gs]:e,[Ks]:(new Date).toISOString()},i))}catch(e){Ed.error("Failed to add exception step. Ignoring breadcrumb.",e)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this._isExceptionList(t)){if(this._matchesSuppressionRule(t))return this._addDroppedExceptionStep("Exception dropped: matched a suppression rule"),void Ed.info("Skipping exception capture because a suppression rule matched");if(!this._captureExtensionExceptions&&this._isExtensionException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by a browser extension"),void Ed.info("Skipping exception capture because it was thrown by an extension");if(!this._captureExtensionExceptions&&this._isInjectedBrowserScriptException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by an injected browser script"),void Ed.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this._isPostHogException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by the PostHog SDK"),void Ed.info("Skipping exception capture because it was thrown by the PostHog SDK")}const i=this._exceptionStepsConfig.enabled&&St(e.$exception_steps)?this._addBufferedExceptionSteps(e):e,s=function(){if("u">typeof process){var e;const t=null===(e=process.env.POSTHOG_RELEASE_ID)||void 0===e?void 0:e.trim();if(t)return t}const t=globalThis._posthogReleaseId;return"string"==typeof t&&t.length>0?t:void 0}();s&&(i.$release_id=s);try{const e=this._instance.capture("$exception",i,{_noTruncate:!0,_batchKey:"exceptionEvent",_originatedFromCaptureException:!0});return e&&this._exceptionStepsBuffer.clear(),e}catch(e){return wd(e)||Ed.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void(wd(e)||Ed.error("Failed to process exception event. Ignoring this exception.",e))}}_addBufferedExceptionSteps(e){try{const t=this._exceptionStepsBuffer.getAttachable();return 0===t.length?e:ls(ls({},e),{},{$exception_steps:t})}catch(t){return Ed.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_addDroppedExceptionStep(e){this._exceptionStepsConfig.enabled&&this._exceptionStepsBuffer.add({[Gs]:e,[Ks]:(new Date).toISOString()})}_coerceExceptionStepProperties(e){return gt(e)?ls({},e):{}}_getExceptionStepsConfig(){var e,t;return null!==(e=null===(t=this._instance.config.error_tracking)||void 0===t?void 0:t.exception_steps)&&void 0!==e?e:{}}_matchesSuppressionRule(e){if(0===e.length)return!1;try{const t=e.reduce((e,{type:t,value:i})=>(mt(t)&&t.length>0&&e.$exception_types.push(t),mt(i)&&i.length>0&&e.$exception_values.push(i),e),{$exception_types:[],$exception_values:[]});return this._suppressionRules.some(e=>{const i=e.values.map(e=>{const i=Oc[e.operator],s=t[e.key];if(!i||!s)return!1;const r=_t(e.value)?e.value:[e.value];return r.length>0&&i(r,s)});return"OR"===e.type?i.some(Boolean):i.every(Boolean)})}catch(e){return Ed.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}_isExtensionException(e){const t=e.flatMap(e=>{var t,i;return null!==(t=null===(i=e.stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[]}),i=t.filter(({filename:e})=>!!e&&Pd.some(t=>e.startsWith(t)));return 0!==i.length&&(!i.every(({filename:e})=>!!e&&e.startsWith(Cd))||e.some(({type:e,value:t})=>"NoResponse"===e||mt(t)&&kd.some(({value:e,exact:i})=>i?t===e:t.includes(e)))&&!t.some(({in_app:e,filename:t})=>e&&!(null==t?void 0:t.startsWith(Cd))))}_isInjectedBrowserScriptException(e){return e.some(({value:e})=>mt(e)&&xd.some(t=>e.includes(t)))}_isPostHogException(e){if(e.length>0){var t,i,s,r;const n=null!==(t=null===(i=e[0].stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[],o=n[n.length-1];return null!==(s=null==o||null===(r=o.filename)||void 0===r?void 0:r.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!St(e)&&_t(e)}}},dh=ls({productTours:class{get _persistence(){return this._instance.persistence}constructor(e){this._productTourManager=null,this._cachedTours=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if("productTours"in t){var i,s;if(this._persistence&&this._persistence.register({[N]:!!t.productTours}),!Ku(this._instance))return!this._productTourManager&&St(null===(i=this._persistence)||void 0===i?void 0:i.props.ph_product_tours)||Gu.info("product tours disabled; stopping and clearing cached tours"),null===(s=this._productTourManager)||void 0===s||s.stop(),this._productTourManager=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this._productTourManager&&Ku(this._instance)&&this._loadScript(()=>this._startProductTours())}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.generateProductTours)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"product-tours",t=>{t?Gu.error("Could not load product tours script",t):e()})}_startProductTours(){var e;!this._productTourManager&&(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.generateProductTours)&&(this._productTourManager=tt.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(_t(this._cachedTours)&&!t)return void e(this._cachedTours,{isLoaded:!0});const i=this._persistence;if(i){const s=i.props[ae];if(_t(s)&&!t)return this._cachedTours=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:t=>{if(!Ku(this._instance))return void e([],{isLoaded:!0});const s=t.statusCode;if(200!==s||!t.json){const i=`Product Tours API could not be loaded, status: ${s}`;return 0===s?t.error||Gu.warn(i):Gu.error(i),void e([],{isLoaded:!1,error:i})}const r=_t(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=r,i&&i.register({[ae]:r}),e(r,{isLoaded:!0})}})}getActiveProductTours(e){St(this._productTourManager)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this._productTourManager.getActiveProductTours(e)}showProductTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.showTourById(e)}previewTour(e){this._productTourManager?this._productTourManager.previewTour(e):this._loadScript(()=>{var t;this._startProductTours(),null===(t=this._productTourManager)||void 0===t||t.previewTour(e)})}dismissProductTour(){var e;null===(e=this._productTourManager)||void 0===e||e.dismissTour("user_clicked_skip")}nextStep(){var e;null===(e=this._productTourManager)||void 0===e||e.nextStep()}previousStep(){var e;null===(e=this._productTourManager)||void 0===e||e.previousStep()}clearCache(){var e;this._cachedTours=null,null===(e=this._persistence)||void 0===e||e.unregister("ph_product_tours")}resetTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.resetTour(e)}resetAllTours(){var e;null===(e=this._productTourManager)||void 0===e||e.resetAllTours()}cancelPendingTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.cancelPendingTour(e)}}},ah),hh={siteApps:class{constructor(e){this._instance=e,this._siteAppElementPatchCount=0,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}_eventCollector(e,t){if(!t)return;const i=this.globalsForEvent(t);this._bufferedInvocations.push(i),this._bufferedInvocations.length>1e3&&(this._bufferedInvocations=this._bufferedInvocations.slice(10))}get siteAppLoaders(){var e;return null===(e=tt._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.siteApps}initialize(){if(this.isEnabled){const e=this._instance._addCaptureHook(this._eventCollector.bind(this));this._stopBuffering=()=>{e(),this._bufferedInvocations=[],this._stopBuffering=void 0}}}globalsForEvent(e){var t,i,s,r,n,o,a;if(!e)throw new Error("Event payload is required");const l={},c=this._instance.get_property("$groups")||[],u=this._instance.get_property("$stored_group_properties")||{};for(const[e,t]of Object.entries(u))l[e]={id:c[e],type:e,properties:t};const{$set_once:d,$set:h}=e;return{event:ls(ls({},_r(e,Qu)),{},{properties:ls(ls(ls({},e.properties),h?{$set:ls(ls({},null!==(t=null===(i=e.properties)||void 0===i?void 0:i.$set)&&void 0!==t?t:{}),h)}:{}),d?{$set_once:ls(ls({},null!==(s=null===(r=e.properties)||void 0===r?void 0:r.$set_once)&&void 0!==s?s:{}),d)}:{}),elements_chain:null!==(n=null===(o=e.properties)||void 0===o?void 0:o.$elements_chain)&&void 0!==n?n:"",distinct_id:null===(a=e.properties)||void 0===a?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}_prepareElementForSiteApp(e){var t;const i=null===(t=e.tagName)||void 0===t?void 0:t.toLowerCase();if("style"===i&&this._instance.config.prepare_external_dependency_stylesheet){return this._instance.config.prepare_external_dependency_stylesheet(e)||(Ju.error("prepare_external_dependency_stylesheet returned null"),null)}if("script"===i&&this._instance.config.prepare_external_dependency_script){return this._instance.config.prepare_external_dependency_script(e)||(Ju.error("prepare_external_dependency_script returned null"),null)}return e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,r,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const l=null==Ge?void 0:Ge.defaultView,c=null==l||null===(e=l.Node)||void 0===e?void 0:e.prototype;if(!l||!c)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();const u=[],d=this,h=new WeakSet,_=(e,t,i)=>{if(!(null==e?void 0:e[t]))return;const s=e[t];e[t]=i(s),u.push(()=>{e[t]=s})},p=e=>{if(h.has(e))return e;const t=d._prepareElementForSiteApp(e);return t&&h.add(t),t},g=e=>e.map(e=>"string"==typeof e?e:p(e)).filter(e=>!bt(e));return _(c,"appendChild",e=>function(t){const i=p(t);return i?e.call(this,i):t}),_(c,"insertBefore",e=>function(t,i){const s=p(t);return s?e.call(this,s,i):t}),_(c,"replaceChild",e=>function(t,i){const s=p(t);return s?e.call(this,s,i):i}),[null===(t=l.Element)||void 0===t?void 0:t.prototype,null===(i=l.Document)||void 0===i?void 0:i.prototype,null===(s=l.DocumentFragment)||void 0===s?void 0:s.prototype].forEach(e=>{_(e,"append",e=>function(...t){return e.apply(this,g(t))}),_(e,"prepend",e=>function(...t){return e.apply(this,g(t))})}),[null===(r=l.Element)||void 0===r?void 0:r.prototype,null===(n=l.CharacterData)||void 0===n?void 0:n.prototype,null===(o=l.DocumentType)||void 0===o?void 0:o.prototype].forEach(e=>{_(e,"before",e=>function(...t){return e.apply(this,g(t))}),_(e,"after",e=>function(...t){return e.apply(this,g(t))}),_(e,"replaceWith",e=>function(...t){const i=g(t);return t.length&&!i.length?void 0:e.apply(this,i)})}),_(null===(a=l.Element)||void 0===a?void 0:a.prototype,"insertAdjacentElement",e=>function(t,i){const s=p(i);return s?e.call(this,t,s):null}),this._restoreSiteAppElementPatches=()=>{u.forEach(e=>e()),this._restoreSiteAppElementPatches=void 0},this._releaseSiteAppElementPatches()}_releaseSiteAppElementPatches(){let e=!1;return()=>{var t;e||(e=!0,this._siteAppElementPatchCount--,0===this._siteAppElementPatchCount&&(null===(t=this._restoreSiteAppElementPatches)||void 0===t||t.call(this)))}}_runWithPreparedSiteAppElements(e,t=!0){const i=this._patchSiteAppElementInsertionMethods();try{const s=e(i);return t&&i(),s}catch(e){throw i(),e}}setupSiteApp(e){const t=this.apps[e.id],i=()=>{var i;!t.errored&&this._bufferedInvocations.length&&(Ju.info(`Processing ${this._bufferedInvocations.length} events for site app with id ${e.id}`),this._bufferedInvocations.forEach(e=>this._runWithPreparedSiteAppElements(()=>{var i;return null===(i=t.processEvent)||void 0===i?void 0:i.call(t,e)})),t.processedBuffer=!0),Object.values(this.apps).every(e=>e.processedBuffer||e.errored)&&(null===(i=this._stopBuffering)||void 0===i||i.call(this))};let s=!1;const r=r=>{t.errored=!r,t.loaded=!0,Ju.info(`Site app with id ${e.id} ${r?"loaded":"errored"}`),s&&i()};try{const{processEvent:i}=this._runWithPreparedSiteAppElements(t=>e.init({posthog:this._instance,callback(e){t(),r(e)}}),!1);i&&(t.processEvent=i),s=!0}catch(t){Ju.error(Yu+e.id,t),r(!1)}if(s&&t.loaded)try{i()}catch(i){Ju.error(`Error while processing buffered events PostHog app with config id ${e.id}`,i),t.errored=!0}}_setupSiteApps(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}_onCapturedEvent(e){if(0===Object.keys(this.apps).length)return;const t=this.globalsForEvent(e);for(const i of Object.values(this.apps))try{this._runWithPreparedSiteAppElements(()=>{var e;return null===(e=i.processEvent)||void 0===e?void 0:e.call(i,t)})}catch(t){Ju.error(`Error while processing event ${e.event} for site app ${i.id}`,t)}}onRemoteConfig(e){var t,i,s;if(null===(t=this.siteAppLoaders)||void 0===t?void 0:t.length)return this.isEnabled?(this._setupSiteApps(),void this._instance.on("eventCaptured",e=>this._onCapturedEvent(e))):void Ju.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null===(i=this._stopBuffering)||void 0===i||i.call(this),!e.ok)return;const r=e.config;if(null===(s=r.siteApps)||void 0===s?void 0:s.length)if(this.isEnabled)for(const{id:e,url:t}of r.siteApps){var n,o;tt[`__$$ph_site_app_${e}`]=this._instance,null===(n=tt.__PosthogExtensions__)||void 0===n||null===(o=n.loadSiteApp)||void 0===o||o.call(n,this._instance,t,t=>{if(t)return Ju.error(Yu+e,t)})}else Ju.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},_h={tracingHeaders:class{constructor(e){this._instance=e,this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._startCapturing=()=>{const e=this._syncHostnamesForPatch();var t,i;e?(ft(this._restoreXHRPatch)&&(this._restoreXHRPatch=null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.tracingHeadersPatchFns)||void 0===t?void 0:t._patchXHR(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),ft(this._restoreFetchPatch)&&(this._restoreFetchPatch=null===(i=tt.__PosthogExtensions__)||void 0===i||null===(i=i.tracingHeadersPatchFns)||void 0===i?void 0:i._patchFetch(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this._stopCapturing()}}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.tracingHeadersPatchFns)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"tracing-headers",t=>{if(t)return Ou.error("failed to load script",t);e()})}_getConfiguredHostnames(){var e,t;return null!==(e=null!==(t=this._instance.config.tracing_headers)&&void 0!==t?t:this._instance.config.addTracingHeaders)&&void 0!==e?e:this._instance.config.__add_tracing_headers}_syncHostnamesForPatch(){const e=this._getConfiguredHostnames();return _t(e)?(_t(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):(_t(this._hostnamesForPatch)&&this._hostnamesForPatch.splice(0),this._hostnamesForPatch=e||void 0,this._hostnamesForPatch)}_stopCapturing(){var e,t;null===(e=this._restoreXHRPatch)||void 0===e||e.call(this),null===(t=this._restoreFetchPatch)||void 0===t||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0}startIfEnabledOrStop(){this._syncHostnamesForPatch()?this._loadScript(this._startCapturing):this._stopCapturing()}}},ph=ls({surveys:class extends td{constructor(e){var t;super(new ad(e),(t=e,{get projectToken(){return t.config.token},kv:new od(t)})),this._instance=e}_sendSurveysRequest(e,t){const i=t.query?rc(e,t.query):e;return new Promise(e=>{var s;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor(null!==(s=t.target)&&void 0!==s?s:"api",i),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:e})})}}},ah),gh={toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){tt.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=tt.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,i=void 0){var s,r;if(On(this.instance.config))return!1;if(!je||!Ge)return!1;e=null!==(s=e)&&void 0!==s?s:je.location,i=null!==(r=i)&&void 0!==r?r:je.history;try{if(!t){try{je.localStorage.setItem("test","test"),je.localStorage.removeItem("test")}catch(e){return!1}t=null==je?void 0:je.localStorage}const s=ld||Ca(e.hash,"__posthog")||Ca(e.hash,"state");let r;const n=s?ts(()=>JSON.parse(atob(decodeURIComponent(s))))||ts(()=>JSON.parse(decodeURIComponent(s))):null;return n&&"ph_authorize"===n.action?(r=n,r.source="url",r&&Object.keys(r).length>0&&(n.desiredHash?e.hash=n.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):(r=JSON.parse(t.getItem(cd)||"{}"),r.source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch(e){return!1}}_callLoadToolbar(e){const t=tt.ph_load_toolbar||tt.ph_load_editor;!St(t)&&pt(t)?t(e,this.instance):ud.warn("No toolbar load function found")}loadToolbar(e){const t=!!(null==Ge?void 0:Ge.getElementById("__POSTHOG_TOOLBAR__"));if(!je||t)return!1;const i="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,s=ls(ls({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},i?{instrument:!1}:{});if(je.localStorage.setItem(cd,JSON.stringify(ls(ls({},s),{},{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(s);else if(0===this._getToolbarState()){var r,n;this._setToolbarState(1),null===(r=tt.__PosthogExtensions__)||void 0===r||null===(n=r.loadExternalDependency)||void 0===n||n.call(r,this.instance,"toolbar",e=>{if(e)return ud.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(s)}),An(je,"turbolinks:load",()=>{this._setToolbarState(0),this.loadToolbar(s)})}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,i=void 0){return this.maybeLoadToolbar(e,t,i)}}},vh=ls({experiments:class e{get _config(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(t=!1)=>{this.getWebExperiments(t=>{e._logInfo("retrieved web experiments from the server"),this._flagToExperiments=new Map,t.forEach(t=>{if(t.feature_flag_key){var i;this._flagToExperiments&&(e._logInfo("setting flag key ",t.feature_flag_key," to web experiment ",t),null===(i=this._flagToExperiments)||void 0===i||i.set(t.feature_flag_key,t));const s=this._instance.getFeatureFlag(t.feature_flag_key);mt(s)&&t.variants[s]&&this._applyTransforms(t.name,s,t.variants[s].transforms)}else if(t.variants)for(const i in t.variants){const s=t.variants[i];e._matchesTestVariant(s,this._instance)&&this._applyTransforms(t.name,i,s.transforms)}})},t)},this._instance.onFeatureFlags(e=>{this.onFeatureFlags(e)})}initialize(){}onFeatureFlags(t){if(this._is_bot())e._logInfo(Fd);else if(!this._config.disable_web_experiments){if(St(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();e._logInfo("applying feature flags",t),t.forEach(e=>{var t;if(this._flagToExperiments&&(null===(t=this._flagToExperiments)||void 0===t?void 0:t.has(e))){var i;const t=this._instance.getFeatureFlag(e),s=null===(i=this._flagToExperiments)||void 0===i?void 0:i.get(e);t&&(null==s?void 0:s.variants[t])&&this._applyTransforms(s.name,t,s.variants[t].transforms)}})}}previewWebExperiment(){const t=e.getWindowLocation();if(null==t?void 0:t.search){const i=wa(null==t?void 0:t.search,"__experiment_id"),s=wa(null==t?void 0:t.search,"__experiment_variant");i&&s&&(e._logInfo(`previewing web experiments ${i} && ${s}`),this.getWebExperiments(e=>{this._showPreviewWebExperiment(parseInt(i),s,e)},!1,!0))}}loadIfEnabled(){this._config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._config.disable_web_experiments&&!i)return e([]);const s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this._config.token}`),method:"GET",timestampMode:"query",callback:t=>e(200===t.statusCode&&t.json&&t.json.experiments||[])})}_showPreviewWebExperiment(t,i,s){const r=s.filter(e=>e.id===t);r&&r.length>0&&(e._logInfo(`Previewing web experiment [${r[0].name}] with variant [${i}]`),this._applyTransforms(r[0].name,i,r[0].variants[i].transforms))}static _matchesTestVariant(t,i){return!St(t.conditions)&&e._matchUrlConditions(t,i)&&e._matchUTMConditions(t)}static _matchUrlConditions(t,i){var s;if(St(t.conditions)||St(null===(s=t.conditions)||void 0===s?void 0:s.url))return!0;const r=e.getWindowLocation();if(r){var n,o,a;const e=ho(i,r.href);return!(null===(n=t.conditions)||void 0===n?void 0:n.url)||Id[null!==(o=null===(a=t.conditions)||void 0===a?void 0:a.urlMatchType)&&void 0!==o?o:"icontains"](t.conditions.url,e)}return!1}static getWindowLocation(){return null==je?void 0:je.location}static _matchUTMConditions(e){var t;if(St(e.conditions)||St(null===(t=e.conditions)||void 0===t?void 0:t.utm))return!0;const i=Ia();if(i.utm_source){var s,r,n,o,a,l,c,u;const t=!(null===(s=e.conditions)||void 0===s||null===(s=s.utm)||void 0===s?void 0:s.utm_campaign)||(null===(r=e.conditions)||void 0===r||null===(r=r.utm)||void 0===r?void 0:r.utm_campaign)==i.utm_campaign,d=!(null===(n=e.conditions)||void 0===n||null===(n=n.utm)||void 0===n?void 0:n.utm_source)||(null===(o=e.conditions)||void 0===o||null===(o=o.utm)||void 0===o?void 0:o.utm_source)==i.utm_source,h=!(null===(a=e.conditions)||void 0===a||null===(a=a.utm)||void 0===a?void 0:a.utm_medium)||(null===(l=e.conditions)||void 0===l||null===(l=l.utm)||void 0===l?void 0:l.utm_medium)==i.utm_medium,_=!(null===(c=e.conditions)||void 0===c||null===(c=c.utm)||void 0===c?void 0:c.utm_term)||(null===(u=e.conditions)||void 0===u||null===(u=u.utm)||void 0===u?void 0:u.utm_term)==i.utm_term;return t&&h&&_&&d}return!1}static _logInfo(e,...t){En.info(`[WebExperiments] ${e}`,t)}_applyTransforms(t,i,s){this._is_bot()?e._logInfo(Fd):"control"!==i?s.forEach(s=>{if(s.selector){var r;e._logInfo(`applying transform of variant ${i} for experiment ${t} `,s);const n=null===(r=document)||void 0===r?void 0:r.querySelectorAll(s.selector);null==n||n.forEach(e=>{const t=e;s.html&&(t.innerHTML=s.html),s.css&&t.setAttribute("style",s.css)})}}):e._logInfo("Control variants leave the page unmodified.")}_is_bot(){return Ve&&this._instance?Ic(Ve,this._config.custom_blocked_useragents):void 0}}},ah),fh={conversations:class{constructor(e){this._instance=e,this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations)return;if(this._remoteConfigSuccessful=e.ok,!e.ok)return;const t=e.config.conversations;St(t)||(Ct(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this.loadIfEnabled())}reset(){var e;null===(e=this._conversationsManager)||void 0===e||e.reset(),this._conversationsManager=null,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1}loadIfEnabled(){if(this._conversationsManager)return;if(this._isInitializing)return;if(this._instance.config.disable_conversations)return;if(On(this._instance.config))return;if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=null==tt?void 0:tt.__PosthogExtensions__;if(e&&!ft(this._isConversationsEnabled)&&this._isConversationsEnabled)if(this._remoteConfig&&this._remoteConfig.token){this._isInitializing=!0;try{const t=e.initConversations;if(t)return this._completeInitialization(t),void(this._isInitializing=!1);const i=e.loadExternalDependency;if(!i)return void this._handleLoadError(Oe);i(this._instance,"conversations",t=>{t||!e.initConversations?this._handleLoadError("Could not load conversations script",t):this._completeInitialization(e.initConversations),this._isInitializing=!1})}catch(e){this._handleLoadError("Error initializing conversations",e),this._isInitializing=!1}}else Td.error("Conversations enabled but missing token in remote config.")}_completeInitialization(e){if(this._remoteConfig)try{this._conversationsManager=e(this._remoteConfig,this._instance),this._loadFailed=!1,Td.info("Conversations loaded successfully")}catch(e){this._handleLoadError("Error completing conversations initialization",e)}else Td.error("Cannot complete initialization: remote config is null")}_handleLoadError(e,t){Td.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():Td.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return!0===this._isConversationsEnabled&&!bt(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":On(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":ft(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?St(this._remoteConfig)||!this._remoteConfig.token?"missing_token":(null==tt?void 0:tt.__PosthogExtensions__)?this._isInitializing?"initializing":this._loadFailed?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.isVisible())&&void 0!==e&&e}sendMessage(e,t,i){var s=this;return Lt(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,i):(Td.warn(Rd),null)})()}getMessages(e,t){var i=this;return Lt(function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(Td.warn(Rd),null)})()}markAsRead(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Td.warn(Rd),null)})()}getTickets(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Td.warn(Rd),null)})()}requestRestoreLink(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(Td.warn(Rd),null)})()}restoreFromToken(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(Td.warn(Rd),null)})()}restoreFromUrlToken(){var e=this;return Lt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(Td.warn(Rd),null)})()}getCurrentTicketId(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}_onIdentityChanged(){var e;null===(e=this._conversationsManager)||void 0===e||e.setIdentity()}_onIdentityCleared(){var e;null===(e=this._conversationsManager)||void 0===e||e.clearIdentity()}}},mh={logs:class extends Bd{constructor(e){super({get(){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.logs},captureHintKey:B,get remoteConfigWillArrive(){var t,i;return!(null===(t=e._shouldDisableFlags)||void 0===t?void 0:t.call(e))||!!(null===(i=tt._POSTHOG_REMOTE_CONFIG)||void 0===i||null===(i=i[e.config.token])||void 0===i?void 0:i.config)}},()=>function(e){var t;const i={};if(i.distinctId=e.get_distinct_id(),e.sessionManager){const{sessionId:t,windowId:s,sessionStartTimestamp:r,lastActivityTimestamp:n}=e.sessionManager.checkAndGetSessionAndWindowId(!0);i.sessionId=t,i.windowId=s,St(r)||(i.sessionStartTimestamp=r),St(n)||(i.lastActivityTimestamp=n)}if((null==tt||null===(t=tt.location)||void 0===t?void 0:t.href)&&(i.currentUrl=e.config.disable_capture_url_hashes?es(tt.location.href):tt.location.href),e.featureFlags){const t=e.featureFlags.getFlags();t&&t.length>0&&(i.activeFeatureFlags=t)}return i}(e)),this._instance=e,this.name=Zc,this._listenForReconnect()}get _isRequestReady(){return this._instance.__loaded}_getConsoleLoader(){const e=Cn("[logs]"),t=null==tt?void 0:tt.__PosthogExtensions__;if(!t)return void e.error("PostHog Extensions not found.");const i=t.loadExternalDependency;if(i)return e=>{i(this._instance,"logs",i=>{const s=t.logs;e(i,(null==s?void 0:s.initializeLogs)?{initialize:e=>s.initializeLogs(e),replay(e,t){var i;return null===(i=s.replayConsoleBuffer)||void 0===i?void 0:i.call(s,e,t)}}:void 0)})};e.error(Oe)}}},yh={metrics:class{constructor(e){this._instance=e,this._logger=Cn("[metrics]"),this._disposed=!1}initialize(){this.onConfigChange()}onConfigChange(){var e;if(this._disposed)return;const t=!!(null===(e=this._instance.config.metrics)||void 0===e?void 0:e.network);t&&!this._stopNetworkMetrics?this._stopNetworkMetrics=(e=>{let t=!0;const i=()=>t?(e=>{var t;const i=null===(t=e.config.metrics)||void 0===t?void 0:t.network;return!0===i?{}:i||void 0})(e):void 0,s=Gd(e,i),r=Kd(e,i);return()=>{t=!1,s(),r()}})(this._instance):!t&&this._stopNetworkMetrics&&(this._stopNetworkMetrics(),this._stopNetworkMetrics=void 0)}_getCore(){var e;const t=null===(e=this._instance)||void 0===e||null===(e=e.config)||void 0===e?void 0:e.metrics;var i;return this._core&&this._resolvedFrom===t||(null===(i=this._core)||void 0===i||i.reset(),this._resolvedFrom=t,this._core=new Sn(this._createHost(),function(e){var t,i,s,r,n;const o=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(t=null==o?void 0:o["service.name"])&&void 0!==t?t:null==e?void 0:e.serviceName,serviceVersion:null!==(i=null==o?void 0:o["service.version"])&&void 0!==i?i:null==e?void 0:e.serviceVersion,environment:null!==(s=null==o?void 0:o["deployment.environment"])&&void 0!==s?s:null==e?void 0:e.environment,resourceAttributes:o,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:null!==(r=null==e?void 0:e.flushIntervalMs)&&void 0!==r?r:1e4,maxSeriesPerFlush:null!==(n=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==n?n:1e3}}(t),this._logger)),this._core}count(e,t=1,i){this._getCore().count(e,t,i)}gauge(e,t,i){this._getCore().gauge(e,t,i)}histogram(e,t,i){this._getCore().histogram(e,t,i)}flush(e){if(!this._core)return Promise.resolve();if(e){const t=this._core.drainWindow();return t&&this._sendMetricsBatch(t,e),Promise.resolve()}return this._core.flush().catch(e=>this._logger.error("PostHog metrics flush failed:",e))}reset(){var e;null===(e=this._core)||void 0===e||e.reset()}dispose(){var e,t;this._disposed=!0,null===(e=this._stopNetworkMetrics)||void 0===e||e.call(this),this._stopNetworkMetrics=void 0,null===(t=this._core)||void 0===t||t.reset()}_createHost(){const e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},_sendMetricsBatch:e=>t._sendMetricsBatch(e),getLibraryId:()=>i.LIB_NAME,getLibraryVersion:()=>i.LIB_VERSION}}_sendMetricsBatch(e,t){return new Promise(i=>{let s=!1;const r=e=>{s||(s=!0,clearTimeout(n),i(e))},n=setTimeout(()=>r({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(ls(ls({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),{},{fireCallbackOnDrop:!0,callback(e){const t=e.statusCode;if(t>=200&&300>t)r({kind:"ok"});else if(413===t)r({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)r({kind:"fatal",error:new Error(`metrics request failed with status ${t}`)});else{var i;r({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error(`metrics request failed with status ${t}`)})}}}))})}_metricsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},bh={webMCP:class{constructor(e){this._instance=e,this._isPatched=!1}initialize(){this.startIfEnabled()}startIfEnabled(){if(!this._instance.config.capture_webmcp||this._isPatched)return;const e=null==Ge?void 0:Ge.modelContext;if(!e||!pt(e.registerTool))return;const t=Qd.get(e);if(t)return t.instances.add(this._instance),void(this._isPatched=!0);const i={instances:new Set([this._instance])},s=e.registerTool,r=this;Au(e,"registerTool",e=>{const t=e;return function(e,...s){let n=e;try{n=r._wrapTool(e,i)}catch(i){return t.call(this,e,...s)}return t.call(this,n,...s)}}),e.registerTool!==s&&(Qd.set(e,i),this._isPatched=!0)}_wrapTool(e,t){if(!e||!pt(e.execute))return e;const i=e.execute,s=this,{tool:r,injected:n}=function(e,t){const i={intent:!1,model:!1},s=e.inputSchema;if(!function(e){return!!ft(e)||gt(e)&&Object.keys(e).every(e=>Jd.has(e)||e.startsWith("x-"))&&!0!==e.additionalProperties&&!gt(e.additionalProperties)&&(!e.type||"object"===e.type)&&(!e.properties||gt(e.properties))&&(!e.required||_t(e.required))}(s))return{tool:th(e),injected:i};const r=(null==s?void 0:s.properties)||{},n=e=>eh(r,e)||_t(null==s?void 0:s.required)&&s.required.includes(e);if(i.intent=t.intent&&!n("context"),i.model=t.model&&!n("llm_model"),!i.intent&&!i.model)return{tool:th(e),injected:i};const o=ls({},r),a=_t(null==s?void 0:s.required)?[...s.required]:[];return i.intent&&(o.context={type:"string",description:'Explain why this tool is called and how it supports the user\'s goal. Describe the abstract purpose only. Do not include personal or identifying information. Generalize specific entities as roles such as "a customer".'},a.includes("context")||a.push("context")),i.model&&(o.llm_model={type:"string",description:'The exact model identifier you are running as, taken from your system prompt or environment. Pass "unknown" if you do not know it. Never guess.'},a.includes("llm_model")||a.push("llm_model")),{tool:th(e,ls(ls({},s),{},{type:(null==s?void 0:s.type)||"object",properties:o,required:a})),injected:i}}(e,function(e){const t={intent:!1,model:!1};for(const i of e.instances){const e=Xd(i.config.capture_webmcp);t.intent||(t.intent=!0===(null==e?void 0:e.intent)),t.model||(t.model=!0===(null==e?void 0:e.model))}return t}(t));return Object.defineProperty(r,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const a=new Date,l=function(e,t){if(!gt(e))return{};try{const i=t.intent?ih(e.context,2048,!0):void 0,s=t.model?ih(e.llm_model,256):void 0;return ls(ls({},i&&"{}"!==i?{intent:i}:{}),s&&"unknown"!==s.toLowerCase()?{model:s}:{})}catch(e){return{}}}(o[0],n),c=function(e,t){const i=e[0];if(!gt(i))return e;try{const s=t.intent&&eh(i,"context"),r=t.model&&eh(i,"llm_model");if(!s&&!r)return e;const n=ls({},i);return s&&delete n.context,r&&delete n.llm_model,[n,...e.slice(1)]}catch(t){return e}}(o,n);let u;try{u=i.apply(this===r?e:this,c)}catch(e){throw s._captureToolCall(t,r,a,{error:e,errorResult:!1},l),e}if((d=u)&&"function"==typeof d.then)return Promise.resolve(u).then(e=>{const i=sh(e)?{error:e,errorResult:!0}:void 0;return s._captureToolCall(t,r,a,i,l),e},e=>{throw s._captureToolCall(t,r,a,{error:e,errorResult:!1},l),e});var d;const h=sh(u)?{error:u,errorResult:!0}:void 0;return s._captureToolCall(t,r,a,h,l),u}}),r}_captureToolCall(e,t,i,s,r){const n=Date.now()-i.getTime();let o;for(const a of e.instances){const e=Xd(a.config.capture_webmcp);if(e){s&&!o&&(o=oh(s.error,s.errorResult));try{a.capture("$mcp_tool_call",ls(ls(ls({$mcp_source:"posthog_mcp_analytics",$mcp_interface:"webmcp",$mcp_tool_name:t.name,$mcp_resource_name:t.name,$mcp_tool_description:t.description,$mcp_server_name:null==Ke?void 0:Ke.hostname,$mcp_duration_ms:n,$mcp_is_error:!!s},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),e.intent&&r.intent?{$mcp_intent:r.intent,$mcp_intent_source:"context_parameter"}:{}),e.model&&r.model?{$mcp_llm_model:r.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:i})}catch(e){continue}}}}}};wu.__defaultExtensionClasses=ls({},ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls({},ah),lh),ch),uh),dh),hh),ph),_h),gh),vh),fh),mh),yh),bh));const Sh=function(){i.SDK_DIST_CHANNEL="npm";const e=iu[vu]=new wu;return function(){function e(){e.done||(e.done=!0,fc=!1,Pn(iu,function(e){e._dom_loaded()}))}(null==Ge?void 0:Ge.addEventListener)?"complete"===Ge.readyState?e():An(Ge,"DOMContentLoaded",e,{capture:!1}):je&&En.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),e}();export{Za as Compression,dl as DEFAULT_PRODUCT_TOUR_APPEARANCE,cl as DisplaySurveyType,wu as PostHog,hl as ProductTourEventName,_l as ProductTourEventProperties,al as SurveyEventName,ll as SurveyEventProperties,Xa as SurveyEventType,tl as SurveyPosition,nl as SurveyQuestionBranchingType,rl as SurveyQuestionType,ol as SurveySchedule,il as SurveyTabPosition,sl as SurveyType,el as SurveyWidgetType,Sh as default,Sh as posthog,ml as severityLevels};
|
|
1
|
+
const e="0.9.4",t={DEBUG:(!1,!1),LIB_VERSION:(e,"1.438.9"),LIB_NAME:("browser-common","web"),JS_SDK_VERSION:e};var i=t;const s="$early_access_features",r="$active_feature_flags",n="$feature_flag_details",o="$feature_flag_errors",a="$feature_flag_evaluated_at",l="$feature_flag_request_id",c="$minimal_flag_called_events",u="$enabled_feature_flags",d="$stored_group_properties",h="$stored_person_properties",_="$flag_call_reported",p="$flag_call_reported_session_id",g="$feature_flag_payloads",v="$override_feature_flags",f="$override_feature_flag_payloads",m="visibilitychange",y="$people_distinct_id",b="distinct_id",S="$device_id",w="$device_model",E="__alias",C="__cmpns",k="$fbc",P="$fbc_persistence",x="$fbp",F="$fbp_persistence",I="__timers",T="$autocapture_disabled_server_side",R="$heatmaps_enabled_server_side",M="$exception_capture_enabled_server_side",A="$error_tracking_suppression_rules",O="$error_tracking_capture_extension_exceptions",L="$web_vitals_enabled_server_side",D="$dead_clicks_enabled_server_side",N="$product_tours_enabled_server_side",B="$logs_capture_enabled_server_side",q="$web_vitals_allowed_metrics",U="$session_recording_remote_config",H="$session_recording_enabled_server_side",z="$replay_sample_rate",j="$replay_override_sampling",W="$replay_override_linked_flag",V="$replay_override_url_trigger",G="$replay_override_event_trigger",K="$sesid",Q="$session_is_sampled",J="$session_past_minimum_duration",Y="$session_recording_url_trigger_activated_session",Z="$session_recording_event_trigger_activated_session",X="$debug_first_full_snapshot_timestamp",ee="$sess_rec_flush_size",te="$groups",ie="$surveys",se="$surveys_loaded_at",re="$surveys_activated",ne="$surveys_activated_session",oe="$surveys_activated_timestamps",ae="ph_product_tours",le="$product_tours_activated",ce="$product_tours_activated_session",ue="$conversations_widget_session_id",de="$conversations_ticket_id",he="$conversations_widget_state",_e="$conversations_user_traits",pe="$user_state",ge="$client_session_props",ve="$capture_rate_limit",fe="$initial_campaign_params",me="$initial_referrer_info",ye="$initial_person_info",be="$epp",Se="$posthog_cookieless",we="$cookieless_mode",Ee="$sdk_debug_extensions_init_method",Ce="$sdk_debug_extensions_init_time_ms",ke="$sdk_debug_recording_script_not_loaded",Pe="$sdk_debug_replay_stale_config",xe="$sdk_debug_replay_event_trigger_status",Fe="$sdk_debug_replay_linked_flag_trigger_status",Ie="$sdk_debug_replay_matched_recording_trigger_groups",Te="$sdk_debug_replay_pending_trigger_conditions",Re="$sdk_debug_replay_remote_trigger_matching_config",$e="$sdk_debug_replay_trigger_groups_count",Me="$sdk_debug_replay_url_trigger_status",Ae="$session_recording_start_reason",Oe="PostHog loadExternalDependency extension not found.",Le="anonymous",De="identified",Ne="identified_only",Be="beforeunload",qe="$pageview",Ue="$pageleave",He="$identify",ze="$groupidentify",je="u">typeof window?window:void 0,We="u">typeof globalThis?globalThis:je,Ve=null==We?void 0:We.navigator,Ge=null==We?void 0:We.document,Ke=null==We?void 0:We.location,Qe=null==We?void 0:We.fetch,Je=(null==We?void 0:We.XMLHttpRequest)&&"withCredentials"in new We.XMLHttpRequest?We.XMLHttpRequest:void 0,Ye=null==We?void 0:We.AbortController,Ze=null==We?void 0:We.CompressionStream,Xe=null==Ve?void 0:Ve.userAgent,et="undefined"!=typeof globalThis?globalThis:je;et&&"undefined"==typeof self&&(et.self=et),et&&"undefined"==typeof File&&(et.File=function(){});const tt=null!=je?je:{};var it=function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({}),st=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({});const rt=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],nt=["token"];function ot(e,t){return-1!==e.indexOf(t)}const at=function(e){return e.trim()},lt=function(e){return e.replace(/^\$/,"")};function ct(e){var t;const i=[];return null!==(t=JSON.stringify(e,function(e,t){if("bigint"==typeof t)return t.toString();if("function"!=typeof t&&"symbol"!=typeof t){if(t instanceof Error)return{name:t.name,message:t.message,stack:t.stack};if(t&&"object"==typeof t){for(;i.length>0&&i[i.length-1]!==this;)i.pop();if(i.includes(t))return"[Circular]";i.push(t)}return t}}))&&void 0!==t?t:"null"}const ut=Object.prototype,dt=ut.hasOwnProperty,ht=ut.toString,_t=Array.isArray||function(e){return"[object Array]"===ht.call(e)},pt=e=>"function"==typeof e,gt=e=>e===Object(e)&&!_t(e),vt=e=>{if(gt(e)){for(const t in e)if(dt.call(e,t))return!1;return!0}return!1},ft=e=>void 0===e,mt=e=>"[object String]"==ht.call(e),yt=e=>mt(e)&&0===e.trim().length,bt=e=>null===e,St=e=>ft(e)||bt(e),wt=e=>"[object Number]"==ht.call(e)&&e==e,Et=e=>wt(e)&&e>0,Ct=e=>"[object Boolean]"===ht.call(e),kt=e=>ot(rt,e),Pt=e=>ot(nt,e);function xt(e){return null===e||"object"!=typeof e}function Ft(e,t){return{}.toString.call(e)===`[object ${t}]`}function It(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return Rt(e,Error)}}function Tt(e){return"u">typeof Event&&Rt(e,Event)}function Rt(e,t){try{return e instanceof t}catch(e){return!1}}const $t=[!0,"true",1,"1","yes"],Mt=e=>ot($t,e),At=[!1,"false",0,"0","no"];function Ot(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function Lt(e){return function(){var t=this,i=arguments;return new Promise(function(s,r){var n=e.apply(t,i);function o(e){Ot(n,s,r,o,a,"next",e)}function a(e){Ot(n,s,r,o,a,"throw",e)}o(void 0)})}}const Dt=["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","pinterestbot","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"],Nt=new Map,Bt=function(e,t=[]){if(!e)return!1;const i=function(e,t){let i="";for(let e=0;t.length>e;e++){const s=t[e];i+=s.length+":"+s}return e.length+":"+e+"|"+t.length+":"+i}(e,t),s=Nt.get(i);if(void 0!==s)return s;const r=e.toLowerCase(),n=Dt.concat(t).some(e=>-1!==r.indexOf(e.toLowerCase()));return 256>Nt.size||Nt.clear(),Nt.set(i,n),n};function qt(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),wt(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),qt(null!=r?r:i,t,i,s))}var Ut=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=qt(e.bucketSize,0,100,e._logger),this._refillRate=qt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=qt(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){const i=Math.floor((t-e.lastAccess)/this._refillInterval);i>0&&(e.tokens=Math.min(e.tokens+i*this._refillRate,this._bucketSize),e.lastAccess=e.lastAccess+i*this._refillInterval)}consumeRateLimit(e){var t;const i=Date.now(),s=String(e);let r=this._buckets[s];return r?this._applyRefill(r,i):(r={tokens:this._bucketSize,lastAccess:i},this._buckets[s]=r),0===r.tokens||(r.tokens--,0===r.tokens&&(null===(t=this._onBucketRateLimited)||void 0===t||t.call(this,e)),0===r.tokens)}stop(){this._buckets={}}};const Ht="Mobile",zt="Android",jt="Tablet",Wt="Android Tablet",Vt="iPad",Gt="Apple Watch",Kt="Safari",Qt="BlackBerry",Jt="Samsung Internet",Yt="Chrome",Zt="Chrome iOS",Xt="Internet Explorer",ei="Internet Explorer Mobile",ti="Opera",ii="Microsoft Edge",si="Firefox",ri="Firefox iOS",ni="Nintendo",oi="PlayStation",ai="Xbox",li="Android Mobile",ci="Mobile Safari",ui="Windows",di="Windows Phone",hi="Nokia",_i="Ouya",pi="Generic "+Ht.toLowerCase(),gi="Generic "+jt.toLowerCase(),vi="Konqueror",fi="Oculus Browser",mi="Vivaldi",yi="Yandex",bi="Whale",Si="DuckDuckGo",wi="Pale Moon",Ei="Waterfox",Ci="Brave",ki="Claude",Pi="Codex",xi="ChatGPT",Fi="Google Search App",Ii=new RegExp("Version/(\\d+(\\.\\d+)?)"),Ti=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),Ri=new RegExp(ai,"i"),$i=new RegExp("PlayStation \\w+","i"),Mi=new RegExp("Nintendo \\w+","i"),Ai=new RegExp("BlackBerry|PlayBook|BB10","i"),Oi={"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"},Li=function(e,t,i,s){t=t||"";const r=function(e){return(null==e?void 0:e.brave)?Ci:null}(i);return r||((null==s?void 0:s.detectGoogleSearchApp)&&ot(e,"GSA/")?Fi:ot(e," OPR/")&&ot(e,"Mini")?"Opera Mini":ot(e," OPR/")?ti:Ai.test(e)?Qt:ot(e,"IEMobile")||ot(e,"WPDesktop")?ei:ot(e,"OculusBrowser")?fi:ot(e,"SamsungBrowser")?Jt:ot(e,"Edge")||ot(e,"Edg/")?ii:ot(e,"Vivaldi/")?mi:ot(e,"YaBrowser/")?yi:ot(e,"Whale/")?bi:ot(e,"DuckDuckGo/")||ot(e,"Ddg/")?Si:ot(e,"Claude/")?ki:ot(e,"Codex/")?Pi:ot(e,"ChatGPT/")?xi:ot(e,"FBIOS")?"Facebook Mobile":ot(e,"UCWEB")||ot(e,"UCBrowser")?"UC Browser":ot(e,"CriOS")?Zt:ot(e,"CrMo")||ot(e,Yt)?Yt:ot(e,zt)&&ot(e,Kt)?li:ot(e,"FxiOS")?ri:ot(e.toLowerCase(),vi.toLowerCase())?vi:ot(e,"Brave/")?Ci:((e,t)=>t&&ot(t,"Apple")||function(e){return ot(e,Kt)&&!ot(e,Yt)&&!ot(e,zt)}(e))(e,t)?ot(e,Ht)?ci:Kt:ot(e,"PaleMoon/")?wi:ot(e,"Waterfox/")?Ei:ot(e,si)?si:ot(e,"MSIE")||ot(e,"Trident/")?Xt:ot(e,"Gecko")?si:"")},Di={[ei]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[ii]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Yt]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Zt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Kt]:[Ii],[ci]:[Ii],[ti]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[si]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[ri]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[vi]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Qt]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ii],[li]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[Jt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[fi]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[mi]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[yi]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[bi]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Ci]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[ki]:[Ti],[Pi]:[Ti],[xi]:[Ti],[Si]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[wi]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Ei]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Fi]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[Xt]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},Ni=function(e,t,i,s){const r=Li(e,t,i,s),n=Di[r];if(ft(n))return null;for(let t=0;n.length>t;t++){const i=e.match(n[t]);if(i)return parseFloat(i[i.length-2])}return null},Bi=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[ai,e&&e[1]||""]],[new RegExp(ni,"i"),[ni,""]],[new RegExp(oi,"i"),[oi,""]],[Ai,[Qt,""]],[new RegExp(ui,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[di,""];if(new RegExp(Ht).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){let e=Oi[i[1]]||"";return/arm/i.test(t)&&(e="RT"),[ui,e]}return[ui,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=ft(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[zt,[e[2],e[3],e[4]||"0"].join(".")]:[zt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],qi=function(e){for(let t=0;Bi.length>t;t++){const[i,s]=Bi[t],r=i.exec(e),n=r&&(pt(s)?s(r,e):s);if(n)return n}return["",""]},Ui=function(e){return Mi.test(e)?ni:$i.test(e)?oi:Ri.test(e)?ai:new RegExp(_i,"i").test(e)?_i:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?di:/iPad/.test(e)?Vt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Gt:Ai.test(e)?Qt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(hi,"i").test(e)?hi:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(Ht).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?zt:Wt:new RegExp("(pda|Mobile)","i").test(e)?pi:new RegExp(jt,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?gi:""},Hi=function(e,t){var i;const s=Ui(e);return s===Vt||s===Wt||"Kobo"===s||"Kindle Fire"===s||s===gi?jt:s===ni||s===ai||s===oi||s===_i?"Console":s===Gt?"Wearable":s?Ht:"Android"===(null==t?void 0:t.userAgentDataPlatform)&&(null!==(i=null==t?void 0:t.maxTouchPoints)&&void 0!==i?i:0)>0?600>Math.min(null!==(r=null==t?void 0:t.screenWidth)&&void 0!==r?r:0,null!==(n=null==t?void 0:t.screenHeight)&&void 0!==n?n:0)/(null!==(o=null==t?void 0:t.devicePixelRatio)&&void 0!==o?o:1)?Ht:jt:"Desktop";var r,n,o},zi=/\bFBAV\/(\d+(?:\.\d+)*)/i,ji=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",zi],[/\bFBAN\/EMA\b/i,"Facebook Lite",zi],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",zi],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],Wi="[Truncated]",Vi="[Unserializable]";function Gi(e){let t="";for(let i=0;e.length>i;i++){const s=e.charCodeAt(i);if(55296>s||s>56319)t+=56320>s||s>57343?e[i]:"�";else{const s=e.charCodeAt(i+1);56320>s||s>57343?t+="�":(t+=e[i]+e[i+1],i++)}}return t}function Ki(e,t){if(!t)return e;let i=[];try{i=Object.keys(t)}catch(e){i=[]}for(const s of i){let i;try{i=t[s]}catch(e){i=Vi}Object.defineProperty(e,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}Date,Date;const Qi=3e5;var Ji=class{record(e){if("too-large"===e.kind)return;if("retry-later"!==e.kind)return void this.reset();if(!e.retryAfterMs)return;const t=this.isOpen(),i=Date.now(),s=Math.min(e.retryAfterMs,Qi);if(!t)return this._installedAt=i,void(this._until=i+s);this._until=Math.max(this._until,Math.min(i+s,this._installedAt+Qi))}remainingMs(){const e=Date.now();if(this._installedAt-5e3>e)return this.reset(),0;const t=Math.min(Qi,Math.max(0,this._until-e));return 0===t&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}};const Yi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Zi(e,t){return"string"==typeof(i=e)&&Yi.test(i)?e:t();var i}function Xi(e,t){const i=new Error(t);try{Object.defineProperty(i,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){}return i}function es(e){return e?e.split("#")[0]:e}function ts(e){try{return e()}catch(e){return}}function is(e,t){const i=setTimeout(e,t);return null!=i&&i.unref&&(null==i||i.unref()),i}function ss(e,t,i){return rs.apply(this,arguments)}function rs(){return(rs=Lt(function*(e,t,i){let s;try{return yield Promise.race([e,new Promise((e,r)=>{s=is(()=>{try{null==i||i(),e()}catch(e){r(e)}},t)})])}finally{clearTimeout(s)}})).apply(this,arguments)}function ns(e){return ns="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ns(e)}function os(e,t,i){return(t=function(e){var t=function(e){if("object"!=ns(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!=ns(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==ns(t)?t:t+""}(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function as(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function ls(e){for(var t=1;arguments.length>t;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?as(Object(i),!0).forEach(function(t){os(e,t,i[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):as(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}let cs,us,ds,hs;function _s(e){var t;const i=globalThis._posthogChunkIds,s=globalThis._debugIds;if(!i&&!s)return;const r=i?Object.keys(i):[],n=s?Object.keys(s):[];if(hs&&ps(i,r,us)&&ps(s,n,ds))return hs;us=i?ls({},i):void 0,ds=s?ls({},s):void 0,hs={},null!==(t=cs)&&void 0!==t||(cs={});const o=(t,i)=>{for(const r of t){const t=i[r];if(!t)continue;const n=null==cs?void 0:cs[r];if(n){hs[n]=t;continue}const o=e(r);for(let e=o.length-1;e>=0;e--){var s;const i=null===(s=o[e])||void 0===s?void 0:s.filename;if(i){hs[i]=t,cs[r]=i;break}}}};return s&&o(n,s),i&&o(r,i),hs}function ps(e,t,i){return e&&i?t.length===Object.keys(i).length&&t.every(t=>e[t]===i[t]):e===i}var gs=class{constructor(e,t,i=[]){this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t={}){const i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(t),n=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(n,i),$exception_level:"error"}}modifyFrames(e){var t=this;return Lt(function*(){for(const i of e)i.stacktrace&&i.stacktrace.frames&&_t(i.stacktrace.frames)&&(i.stacktrace.frames=yield t.applyModifiers(i.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null===(t=e.syntheticException)||void 0===t?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var i;let s,r;if(null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch(e){}return ls(ls({},e),{},{cause:s,stack:r,errors:null===(i=e.errors)||void 0===i?void 0:i.map(e=>this.parseStacktrace(e,t))})}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(const i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Lt(function*(){let i=e;for(const e of t.modifiers)i=yield e(i);return i})()}convertToExceptionList(e,t){const i=[],s=(e,r,n)=>{var o;const a=i.length,l=void 0===r?ls(ls({type:"string"==typeof t.type&&t.type.length>0?t.type:"generic"},"boolean"==typeof t.handled?{handled:t.handled}:void 0===t.handled?{handled:!0}:{}),{},{synthetic:"boolean"==typeof t.synthetic?t.synthetic:e.synthetic,exception_id:a}):{type:"chained",source:n,synthetic:e.synthetic,exception_id:a,parent_id:r},c={type:e.type,value:e.value,mechanism:l};e.stack&&(c.stacktrace={type:"raw",frames:e.stack}),i.push(c),e.cause&&s(e.cause,a,"cause");for(const t of null!==(o=e.errors)&&void 0!==o?o:[])s(t,a,"member")};return s(e),i}buildParsingContext(e){var t;return{chunkIdMap:_s(this.stackParser),skipFirstLines:null!==(t=e.skipFirstLines)&&void 0!==t?t:1}}getAggregateErrors(e){try{if(It(e)){let i=Object.getPrototypeOf(e);for(let s=0;i&&100>s;s++){var t;const s=null===(t=Object.getOwnPropertyDescriptor(i,"constructor"))||void 0===t?void 0:t.value;if("function"==typeof s&&"AggregateError"===s.name){const t=e.errors;return _t(t)?t:void 0}i=Object.getPrototypeOf(i)}}}catch(e){}}buildCoercingContext(e,t,i=0){let s=0,r=0,n=!1;const o=new Set,a=[],l={},c=(e,t,i=0)=>{const c=u(t,i),d=c.apply;if(c.apply=t=>{a.push(e);try{return d(t)}finally{a.pop()}},i>4||i>0&&-1!==a.indexOf(e))return this.coerceFallback(c);const h="object"==typeof e&&null!==e||"function"==typeof e;if(0===i&&s>=50||h&&o.has(e))return;h&&o.add(e),0===i&&s++;const _=this.getAggregateErrors(e);let p,g;n||(n=!!_);try{if(p=this.applyCoercers(e,c),!p)throw l}catch(e){if(e===l)return void(0===i&&s--);if(!n)throw e;p=this.coerceFallback(c)}if(!_||s>=50)return p;try{g=_.length}catch(e){return p}if(!Number.isInteger(g)||0>g||g>4294967295)return p;const v=[];for(let e=0;50>s&&1e3>r&&g>e;e++){let i;r++;try{i=c.next(_[e])}catch(e){s++,i=this.coerceFallback(u(t+1))}i&&v.push(i)}return ls(ls({},p),{},{errors:v})},u=(i,s=0)=>ls(ls({},t),{},{syntheticException:0==i?t.syntheticException:void 0,mechanism:0==i?e:{},apply(e){const t=c(e,i,s+1);if(!t)throw l;return t},next:e=>c(e,i+1)}),d=u(i);return ls(ls({},d),{},{apply:e=>{var t;return null!==(t=c(e,i))&&void 0!==t?t:this.coerceFallback(d)}})}};const vs=/^([a-z][a-z0-9.+-]+):/i,fs=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ms(e){if(!e||"<anonymous>"===e)return!1;const t=vs.exec(e);return!t||fs.includes(t[1].toLowerCase())}function ys(e,t,i,s,r){const n={platform:e,filename:t,function:"<anonymous>"===i?"?":i,in_app:ms(t)};return ft(s)||(n.lineno=s),ft(r)||(n.colno=r),n}const bs=(e,t)=>{const i=-1!==e.indexOf("safari-extension"),s=-1!==e.indexOf("safari-web-extension");return i||s?[-1!==e.indexOf("@")?e.split("@")[0]:"?",i?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},Ss=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ws=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Es=/\((\S*)(?::(\d+))(?::(\d+))\)/,Cs=(e,t)=>{const i=Ss.exec(e);if(i){const[,e,s,r]=i;return ys(t,e,"?",+s,+r)}const s=ws.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){const e=Es.exec(s[2]);e&&(s[2]=e[1],s[3]=e[2],s[4]=e[3])}const[e,i]=bs(s[1]||"?",s[2]);return ys(t,i,e,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},ks=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ps=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,xs=(e,t)=>{const i=ks.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){const e=Ps.exec(i[3]);e&&(i[1]=i[1]||"eval",i[3]=e[1],i[4]=e[2],i[5]="")}let e=i[3],s=i[1]||"?";return[s,e]=bs(s,e),ys(t,e,s,i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},Fs=/\(error: (.*)\)/;function Is(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function Ts(e){for(let t=1;10>=t;t++){const i=e.length-2*t;if(0>i)break;let s=!0;for(let r=0;t>r;r++)if(!Is(e[i+r],e[i+t+r])){s=!1;break}if(s){for(let s=0;t>s;s++)e[i+s]=e[i+t+s];return e.length=i+t,{start:i,length:t}}}}function Rs(e,t){const i=t.start+t.length,s=Ms(e,t);s&&e.splice(i+s===e.length?i:t.start,s)}function $s(e,t){let i=t.start;for(;i>0&&Is(e[i-1],e[i-1+t.length]);)i--;return t.start-i}function Ms(e,t){const i=t.start+t.length;let s=i;for(;e.length>s&&Is(e[s],e[s-t.length]);)s++;return s-i}function As(e,t){const i=t[0];let s=e.length-(i?$s(e,i):0);for(const i of t)s-=Ms(e,i);return s}function Os(e,t,i){for(let s=0;e.length>s;s++){const r=e[(t+s)%e.length],n=e[(i+s)%e.length];if(r!==n)return n>r}return!1}var Ls=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const i=mt(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:i?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){const t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return Ft(e,"DOMException")}isDOMError(e){return Ft(e,"DOMError")}},Ds=class{match(e){return It(e)}coerce(e,t){var i;const s=this.getStack(e),r=void 0===s?null===(i=t.syntheticException)||void 0===i?void 0:i.stack:void 0,n=!!r;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:r,cause:e.cause?t.next(e.cause):void 0,synthetic:n}}getType(e){return e.name||e.constructor.name}getMessage(e,t){const i=e.message;return String(i.error&&"string"==typeof i.error.message?i.error.message:i)}getStack(e){try{const t=e.stacktrace;if("string"==typeof t&&t.length>0)return t;const i=e.stack;return"string"==typeof i&&i.length>0?i:void 0}catch(e){return}}},Ns=class{match(e){return!!Ft(e,"ErrorEvent")&&(null!=e.error||this._hasUsableMessage(e))}coerce(e,t){var i;if(null!=e.error)return t.apply(e.error);const s=t.apply(e.message);return ls(ls({},s),{},{stack:null!==(i=this._buildLocationStack(e))&&void 0!==i?i:s.stack,synthetic:!0})}_hasUsableMessage(e){return mt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i;const s=e,r=null!==(t=s.lineno)&&void 0!==t?t:0,n=null!==(i=s.colno)&&void 0!==i?i:0;if(mt(s.filename)&&0!==s.filename.length&&0!==r)return`Error\n at ${s.filename}:${r}:${n}`}};const Bs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var qs=class{match(e){return"string"==typeof e}coerce(e,t){var i;const[s,r]=this.getInfos(e);return{type:null!=s?s:"Error",value:null!=r?r:e,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}getInfos(e){let t="Error",i=e;const s=e.match(Bs);return s&&(t=s[1],i=s[2]),[t,i]}};const Us=["fatal","error","warning","log","info","debug"];function Hs(e,t=40){const i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(let e=i.length;e>0;e--){const s=i.slice(0,e).join(", ");if(t>=s.length)return e===i.length?s:s.length>t?`${s.slice(0,t)}...`:s}return""}var zs=class{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s;const r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null!==(i=this.getStack(e))&&void 0!==i?i:null===(s=t.syntheticException)||void 0===s?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(Tt(e))return e.constructor.name;const t="name"in e?e.name:void 0;return mt(t)&&!yt(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;const t=this.getObjectClassName(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${Hs(e)}`}isSeverityLevel(e){return mt(e)&&!yt(e)&&Us.indexOf(e)>=0}getStack(e){try{return mt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:mt(e.stack)&&e.stack.length>0?e.stack:void 0}catch(e){return}}getErrorPropertyFromObject(e){for(const t in e)if({}.hasOwnProperty.call(e,t)){const i=e[t];if(It(i))return i}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}},js=class{match(e){return Tt(e)}coerce(e,t){var i;const s=e.constructor.name;return{type:s,value:`${s} captured as exception with keys: ${Hs(e)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}},Ws=class{match(e){return xt(e)}coerce(e,t){var i;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}}},Vs=class{match(e){return Ft(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Tt(e))return!1;try{const t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch(e){return!1}}coerce(e,t){var i;const s=this.getUnhandledRejectionReason(e);return xt(s)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(s)}`,stack:null===(i=t.syntheticException)||void 0===i?void 0:i.stack,synthetic:!0}:t.apply(s)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch(e){}return e}};const Gs="$message",Ks="$timestamp",Qs=new Set([Gs,Ks]),Js={enabled:!0,max_bytes:32768};function Ys(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Js.enabled,max_bytes:Xs(e.max_bytes,Js.max_bytes)}:ls({},Js)}var Zs=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Ys(e)}setConfig(e){this._config=Ys(e),this._trimToMaxBytes()}add(e){const t=function(e){let t;try{t=ct(e)}catch(e){return}try{const e=JSON.parse(t);if(!gt(e))return;const i=e,s=i[Gs],r=i[Ks];if(!mt(s)||0===s.trim().length)return;if(!mt(r)&&!wt(r))return;return{step:i,json:t}}catch(e){return}}(e);if(!t)return;const i=function(e){if("u">typeof TextEncoder)return(new TextEncoder).encode(e).length;const t=encodeURIComponent(e);let i=0;for(let e=0;t.length>e;e++)"%"===t[e]?(i+=1,e+=2):i+=1;return i}(t.json);i>this._config.max_bytes||(this._entries.push({step:t.step,bytes:i}),this._totalBytes+=i,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;){const e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}};function Xs(e,t){if(!wt(e)||1/0===e||-1/0===e)return t;const i=Math.floor(e);return 0>i?t:i}const er=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function tr(e){return"string"==typeof e||e}function ir(e){return"string"==typeof e?e:void 0}const sr=["$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","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],rr="NativeGzipValidationError",nr=e=>e.length>=2&&31===e[0]&&139===e[1],or=(e,t)=>e===st.GZipJS||t===st.GZipJS||"gzip"===t,ar=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):"");let lr;const cr=e=>{throw Xi(rr,`Native gzip produced invalid output: ${e}`)},ur=(dr=Lt(function*(e,t){18>e.size&&cr("too-short");const i=new Uint8Array(yield e.slice(0,10).arrayBuffer());nr(i)&&8===i[2]||cr("invalid-header");const s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{const t=(()=>{if(lr)return lr;lr=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)t=1&t?3988292384^t>>>1:t>>>1;lr[e]=t>>>0}return lr})();let i=4294967295;for(let s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&cr("invalid-crc");const r=t.length>>>0;s.getUint32(4,!0)!==r&&cr("invalid-size")}),function(e,t){return dr.apply(this,arguments)});var dr;function hr(){return hr=Lt(function*(e,t=!0,i){try{const t=(new TextEncoder).encode(e),i=new globalThis.CompressionStream("gzip"),r=i.writable.getWriter(),n=r.write(t).then(()=>r.close()).catch((s=Lt(function*(e){try{yield r.abort(e)}catch(e){}throw e}),function(e){return s.apply(this,arguments)})),o=new Response(i.readable).blob(),[a]=yield Promise.all([o,n]);return yield ur(a,t),a}catch(e){if(null==i?void 0:i.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}var s}),hr.apply(this,arguments)}function _r(e,t){if(null==e)return{};var i,s,r=function(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(t.includes(s))continue;i[s]=e[s]}return i}(e,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(s=0;n.length>s;s++)t.includes(i=n[s])||{}.propertyIsEnumerable.call(e,i)&&(r[i]=e[i])}return r}const pr="[redacted]",gr=/^[A-Za-z0-9+/\n\r]+=*$/,vr=/^[A-Za-z0-9_-]+={0,2}$/,fr=/[-_]/,mr=/^data:[^,\s]*;base64,/i,yr=/^[A-Za-z0-9+/_-]+={0,2}$/,br=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,Sr=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,wr=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,Er=/[\s<>"]/,Cr=new RegExp(wr.source,"i"),kr=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Pr=new RegExp(`^${kr.source}`,"i"),xr=new RegExp(kr.source,"gi"),Fr=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,Ir=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,Tr=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,Rr=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,$r=/\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g,Mr=/(^|[^\w:])((?:(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}|(?:[0-9A-Fa-f]{1,4}:){1,7}:|(?:[0-9A-Fa-f]{1,4}:){1,6}:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,5}|::(?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4}){0,6})))(?=$|[^\w:])/g,Ar=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,Or=/\b\d(?:[ ./-]?\d){12,}\b/g,Lr=/\d+/g,Dr=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,Nr=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;function Br(e){return function(e){return Sr.test(e)}(e)||Fr.test(e)||Ir.test(e)}function qr(e){return e.split("&",129).length>128}function Ur(e,t,i){return Br(e)||t.includes(";")&&function(e){return e.split(";").some(e=>Br(e.split("=",1)[0]))}(t)?pr:Cr.test(t)?i?Gr(t,{allowNestedUrls:!1,stripPunctuation:!0}):pr:t}function Hr(e,t){const i=new URLSearchParams;let s=!1,r=!1;for(const[n,o]of new URLSearchParams(e)){const e=Kr(n),a=Kr(o);s||(s=e!==n||a!==o);const l=Ur(e,a,t);s||(s=l!==a),r=Br(e)||l!==a,i.append(e,l)}return{changed:s,lastFieldSensitive:r,serialized:i.toString()}}function zr(e,t){if(!e.includes("="))return{value:jr(e,t),lastFieldSensitive:!1};const i=Hr(e,t);return{value:i.changed?i.serialized:e,lastFieldSensitive:i.lastFieldSensitive}}function jr(e,t){return t?Gr(e,{allowNestedUrls:!1,stripPunctuation:!0}):Cr.test(e)?pr:e}function Wr(e,t,i){return"#"===e?!t.fragment&&(t.fragment=!0):"?"===e&&(t.fragment?"="!==i&&!t.fragmentQuery&&(t.fragmentQuery=!0):!t.query&&(t.query=!0))}function Vr(e,t){var i;if(e.length>8192&&Pr.test(e))return pr;const{address:s,suffix:r}=t.stripPunctuation?function(e){let t=e.length;for(;t>0&&".,;:!?)]}'".includes(e[t-1]);)t--;return{address:e.slice(0,t),suffix:e.slice(t)}}(e):{address:e,suffix:""};let n;try{n=new URL(s)}catch(e){return pr+r}const o=n.search.slice(1),a=""!==n.hash,l=function(e){const t=e.slice(1),i=t.indexOf("?");return 0>i?{head:t,tail:null}:{head:t.slice(0,i),tail:t.slice(i+1)}}(n.hash);if(qr(o)||qr(l.head)||qr(null!==(i=l.tail)&&void 0!==i?i:""))return pr+r;let c=!1;(n.username||n.password)&&(n.username=pr,n.password="",c=!0);const u=Hr(o,t.allowNestedUrls);u.changed&&(n.search=u.serialized,c=!0);const d=zr(l.head,t.allowNestedUrls),h=null===l.tail?null:(_=l.tail,d.lastFieldSensitive?{value:""===_?"":pr,lastFieldSensitive:!0}:zr(_,t.allowNestedUrls));var _;const p=null===h?d.value:`${d.value}?${h.value}`;p!==n.hash.slice(1)&&(n.hash=p,c=!0);const g=a?null!=h?h:d:u;return(c?Kr(n.toString()):s)+(g.lastFieldSensitive?"":r)}function Gr(e,t){return e.replace(wr,i=>function(e,t){const i=function(e){if(!e.includes("://"))return[];const t=[...e.matchAll(xr)].map(e=>e.index),i=[],s={query:!1,fragment:!1,fragmentQuery:!1};let r=0,n=!1,o="";for(let a=0;e.length>a&&t.length>r;a++){t[r]===a&&(a>0&&"="!==o&&i.push(a),r++);const l=e[a];Wr(l,s,o)?(o=l,n=!0):n&&"=&".includes(l)&&(o=l)}return i}(e);if(0===i.length)return Vr(e,t);let s="",r=0;for(const n of i)s+=Vr(e.slice(r,n),ls(ls({},t),{},{stripPunctuation:!1})),r=n;return s+Vr(e.slice(r),t)}(i,ls(ls({},t),{},{stripPunctuation:t.stripPunctuation&&i.length!==e.length})))}function Kr(e){return e.replace(br,pr)}function Qr(e,t){return function(e){return e.length>=10240&&(gr.test(e)||function(e){const t=mr.exec(e);if(!t)return!1;let i;try{i=decodeURIComponent(e.slice(t[0].length))}catch(e){return!1}return yr.test(i.replace(/[\r\n]/g,""))}(e)||fr.test(e)&&vr.test(e))}(e)?"[binary data redacted - not supported by PostHog MCP analytics]":function(e,t,i){const s=4*i.maxStringLength;if(e.length>s){const r=t(e.slice(0,function(e,t){let i=t;for(;i>0&&!Er.test(e[i-1]);)i--;return i}(e,s)));if(r.length>=2*i.maxStringLength)return r+i.truncationSuffix}return t(e)}(e,e=>function(e){return Gr(e,{allowNestedUrls:!0,stripPunctuation:!0})}(function(e){let t=e.replace(Tr," ");return t=t.replace(Rr,pr),t=t.replace($r,pr),t=t.replace(Mr,`$1${pr}`),t=t.replace(Or,Yr),t=t.replace(Ar,pr),t=t.replace(Dr,`$1${pr}`),t=t.replace(Nr,`$1${pr}`),t}(Kr(e))),t)}function Jr(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let r=e.charCodeAt(s)-48;if(0>r||r>9)return!1;i&&(r*=2,r>9&&(r-=9)),t+=r,i=!i}return t%10==0}function Yr(e){const t=[];for(let i=Lr.exec(e);null!==i;i=Lr.exec(e))t.push({digits:i[0],start:i.index,end:i.index+i[0].length});let i="",s=0,r=0;for(;t.length>r;){let n="",o=-1;for(let e=r;t.length>e&&(n+=t[e].digits,19>=n.length);e++)n.length>=13&&Jr(n)&&(o=e);0>o?r++:(i+=e.slice(s,t[r].start)+pr,s=t[o].end,r=o+1)}return i+e.slice(s)}const Zr={}.propertyIsEnumerable;function Xr(e,t){try{return sn(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch(e){return[]}}function en(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:Wi};if(i.remainingNodes--,Ct(e))return{boolValue:e};if("bigint"==typeof e)return function(e,t){const i=e.toString(),s=BigInt("9223372036854775808");return e>=s||-s>e?(null==t||t.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}(e,t);if("number"==typeof e){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=0x8000000000000000||-0x8000000000000000>e?(null==t||t.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if("string"==typeof e)return{stringValue:Gi(e)};if("function"==typeof e)return{stringValue:"[Function]"};if("symbol"==typeof e)return{stringValue:String(e)};if("object"==typeof e&&null!==e){if(i.ancestors.has(e))return{stringValue:"[Circular]"};if(s>=20)return{stringValue:Wi};if(e instanceof Date){const t=e.getTime(),i=Number.isFinite(t)?e.toISOString():String(e);return{stringValue:"string"==typeof i?Gi(i):String(i)}}i.ancestors.add(e);try{try{const r=e.toJSON;if("function"==typeof r)return en(r.call(e),t,i,s+1)}catch(e){}return _t(e)?{arrayValue:{values:tn(e,t,i,s+1)}}:{kvlistValue:{values:sn(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Gi(String(e))}}function tn(e,t,i,s){const r=[],n=Math.min(e.length,1e3);let o=0;for(;n>o&&i.remainingNodes>0;o++)try{const n=o in e?e[o]:void 0;if(St(n))continue;r.push(en(n,t,i,s))}catch(e){r.push({stringValue:Vi})}return e.length>o&&r.push({stringValue:Wi}),r}function sn(e,t,i,s){const r=[];for(const n in e)if(Zr.call(e,n)){if(!n){null==t||t.debug("Dropping an attribute with an empty key");continue}if(r.length>=1e3||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[n];if(bt(o)||ft(o))continue;r.push({key:Gi(n),value:en(o,t,i,s)})}catch(e){r.push({key:Gi(n),value:{stringValue:Vi}})}}return r}function rn(e,t,i){return ls(ls(ls(ls({},Ki({},e.resourceAttributes)),{},{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment}),e.serviceVersion&&{"service.version":e.serviceVersion}),{},{"telemetry.sdk.name":t,"telemetry.sdk.version":i})}const nn=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function on(e,t){const i=Ki({},e),s={};for(const e of nn)({}).hasOwnProperty.call(i,e)&&(s[e]=i[e],delete i[e]);return[...Xr(i,t),...Xr(s,t)]}const an={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};const ln={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}},cn=ln.info;function un(e){try{return Gi(String(e))}catch(e){return Vi}}function dn(e,t,i,s){const r=e.level||"info",{text:n,number:o}=ln[r]||cn,a=function(e=Date.now()){return String(e)+"000000"}(wt(s)?s:void 0),l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),St(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),St(t.lastActivityTimestamp)||(l.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(l["url.full"]=t.currentUrl),t.screenName&&(l["screen.name"]=t.screenName),t.appState&&(l["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(l.feature_flags=t.activeFeatureFlags);const c=ls({},l),u=e.attributes;if(u){let e=[];try{e=Object.keys(u)}catch(t){e=[]}for(const t of e){let e;try{e=u[t]}catch(t){e=Vi}Object.defineProperty(c,t,{value:e,enumerable:!0,writable:!0,configurable:!0})}}const d={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:n,body:{stringValue:un(e.body)},attributes:Xr(c,i)};return e.trace_id&&(d.traceId=e.trace_id),e.span_id&&(d.spanId=e.span_id),ft(e.trace_flags)||(d.flags=e.trace_flags),d}function hn(e,t,i){return rn(e,t,i)}function _n(e,t,i,s){return{resourceLogs:[{resource:{attributes:on(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}var pn=class{constructor(e){this._onFire=e,this._firesAt=0}get pending(){return!!this._timer}arm(e){this.clear(),this._firesAt=Date.now()+e,this._timer=is(()=>{this._timer=void 0,this._onFire()},e)}armNoEarlierThan(e){this._timer&&Date.now()+e<=this._firesAt||this.arm(e)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}};function gn(){return.75+.5*Math.random()}function vn(e,t,i,s){const r=Math.min(Math.max(0,t-1),6),n=e*Math.pow(2,r);return Math.round((void 0===s?n:Math.min(n,Math.max(s,e)))*i)}var fn=class{constructor(e,t,i,s,r,n=()=>Promise.resolve(),o){var a;this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=r,this._waitForStoragePersist=n,this._scopeName=o,this._flushTimer=new pn(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._retryAfter=new Ji,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(a=t.maxQueueSize)&&void 0!==a?a:t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(it.LogsQueue,[])}reset(){this._flushTimer.clear(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.isOpen()?this._hasQueuedRecords()&&this._armFlushTimer():this._flushInBackground()}captureLog(e,t){var i;if(this._instance.isDisabled)return;if(this._instance.optedOut)return;if(!(null==e?void 0:e.body))return;const s=this._runBeforeSend(e);if(null===s)return;if(!s.body)return void this._logger.info("Log was rejected in beforeSend function");if(!this._checkRateLimit())return;const r={record:dn(s,null!==(i=null==t?void 0:t.context)&&void 0!==i?i:this._getContext(),this._logger,null==t?void 0:t.occurredAtMs)};this._onReady(()=>this._enqueue(r))}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=_t(t)?t:[t];let s=e;for(const e of i)try{const t=e(s);if(!t)return this._logger.info("Log was rejected in beforeSend function"),null;s=t}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return s}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;const e=Date.now(),t=e-this._intervalWindowStart;return this._rateCapWindowMs>t&&t>=0||(this._intervalWindowStart=e,this._intervalLogCount=0,this._droppedWarned=!1),this._maxLogsPerInterval>this._intervalLogCount?(this._intervalLogCount++,!0):(this._droppedWarned||(this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`),this._droppedWarned=!0),!1)}flush(){var e=this;return Lt(function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally(()=>{e._flushPromise=null})),e._flushPromise})()}_flushInner(){var e=this;return Lt(function*(){var t;e._flushTimer.clear();let i=null!==(t=e._instance.getPersistedProperty(it.LogsQueue))&&void 0!==t?t:[];if(0===i.length)return;const s=i.length;let r=0;for(;i.length>0&&s>r;){var n,o;const t=e._queueGeneration;e._evictedSinceAdvance=0;const s=Math.min(i.length,e._maxBatchRecordsPerPost),a=i.slice(0,s),l=_n(a.map(e=>e.record),e._buildResourceAttributes(),null!==(n=e._scopeName)&&void 0!==n?n:e._instance.getLibraryId(),e._instance.getLibraryVersion()),c=yield e._instance._sendLogsBatch(l);if(e._queueGeneration!==t)return;if("too-large"===c.kind&&a.length>1)e._maxBatchRecordsPerPost=Math.max(1,Math.floor(a.length/2)),e._logger.warn(`Logs batch of size ${a.length} was too large for the ingestion endpoint, reducing batch size to ${e._maxBatchRecordsPerPost}`);else{if(e._retryAfter.record(c),e._flushTimer.pending&&e._flushTimer.arm(Math.max(e._flushIntervalMs,e._retryAfter.remainingMs())),"retry-later"===c.kind)throw c.error;if("too-large"===c.kind?e._logger.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===c.kind&&e._config.maxBatchRecordsPerPost>e._maxBatchRecordsPerPost&&(e._maxBatchRecordsPerPost=Math.min(e._config.maxBatchRecordsPerPost,e._maxBatchRecordsPerPost+1)),yield e._persistQueueAdvance(a.length),i=null!==(o=e._instance.getPersistedProperty(it.LogsQueue))&&void 0!==o?o:[],r+=a.length,"fatal"===c.kind)throw c.error}}})()}_persistQueueAdvance(e){var t=this;return Lt(function*(){var i;const s=Math.max(0,e-t._evictedSinceAdvance),r=null!==(i=t._instance.getPersistedProperty(it.LogsQueue))&&void 0!==i?i:[];t._instance.setPersistedProperty(it.LogsQueue,r.slice(s)),yield t._waitForStoragePersist()})()}_buildResourceAttributes(){return hn(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(this._instance.optedOut)return;const i=null!==(t=this._instance.getPersistedProperty(it.LogsQueue))&&void 0!==t?t:[];this._maxQueueSize>i.length||(i.shift(),this._evictedSinceAdvance++,this._logger.info("Logs queue is full, dropping oldest record.")),i.push(e),this._instance.setPersistedProperty(it.LogsQueue,i),this._maxBufferSize>i.length||this._retryAfter.isOpen()?this._armFlushTimer():this._flushInBackground()}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(Math.max(this._flushIntervalMs,this._retryAfter.remainingMs()))}_nextFlushDelay(){return Math.max(vn(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){const e=this._instance.getPersistedProperty(it.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Lt(function*(){t._flushTimer.clear();const i=t.flush().catch(()=>{});void 0!==e?yield ss(i,e):yield i})()}flushWithTimeout(e){var t=this;return Lt(function*(){const i=t.flush();yield ss(i,e,()=>{i.catch(()=>{})})})()}_flushInBackground(){this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},e=>{this._consecutiveFlushFailures++,this._flushJitter=gn(),this._logger.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())})}};const mn=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function yn(e){return String(e)+"000000"}function bn(e,t,i,s){let r="";return s&&(r=Object.keys(s).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(s[e])}`).join(",")),`${e}\0${t}\0${null!=i?i:""}\0${r}`}var Sn=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushTimer=new pn(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new Ji,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(e,t=1,i){this._capture({name:e,type:"count",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}flush(){var e=this;const t=this._flushPromise,i=function(){var i=Lt(function*(){t&&(yield t.catch(()=>{})),yield e._doFlush()});return function(){return i.apply(this,arguments)}}()().finally(()=>{this._flushPromise===i&&(this._flushPromise=null)});return this._flushPromise=i,i}drainWindow(){if(0===this._series.size)return null;const 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._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),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;const t=this._runBeforeSend(e);if(null===t)return;if(!t.name||"string"!=typeof t.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof t.value||!Number.isFinite(t.value))return void this._logger.warn(`Dropping metric '${t.name}': value must be a finite number`);if("count"===t.type&&0>t.value)return void this._logger.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let i,s;try{i=t.attributes?ls({},t.attributes):void 0,s=bn(t.type,t.name,t.unit,i)}catch(e){return void this._logger.warn(`Dropping metric '${t.name}': attributes could not be serialized`,e)}let r=this._series.get(s);if(!r){if(!this._admitNewSeries())return;r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now()},this._series.set(s,r)}const n=this._typeByName.get(t.name);void 0===n?this._typeByName.set(t.name,t.type):n===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${n}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(r,t.value),this._armFlushTimer()}_admitNewSeries(){return this._config.maxSeriesPerFlush>this._series.size||(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":var i;e.total=(null!==(i=e.total)&&void 0!==i?i: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(mn.length+1).fill(0)});const i=e.hist;i.count+=1,i.sum+=t,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t),i.bucketCounts[function(e,t){for(let i=0;t.length>i;i++)if(t[i]>=e)return i;return t.length}(t,mn)]+=1;break}}}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=_t(t)?t:[t];let s=e;for(const e of i)try{const t=e(s);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;s=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return s}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(vn(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_doFlush(){var e=this;return Lt(function*(){if(e._flushTimer.clear(),0===e._series.size)return;const t=e._series;e._series=new Map,e._seriesCapWarned=!1,e._typeByName=new Map,e._typeCollisionWarned=new Set;const i=e._generation,s=yield e._instance._sendMetricsBatch(e._buildPayload(t));if(i===e._generation)switch(e._retryAfter.record(s),"retry-later"===s.kind?(e._consecutiveFlushFailures++,e._flushJitter=gn()):(e._consecutiveFlushFailures=0,e._flushJitter=1),e._flushTimer.pending&&e._flushTimer.arm(e._nextFlushDelay()),s.kind){case"ok":return;case"retry-later":return e._mergeWindowBack(t),void e._flushTimer.armNoEarlierThan(e._nextFlushDelay());case"too-large":return void e._logger.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void e._logger.error("Failed to send metrics batch:",s.error)}})()}_buildPayload(e){return t=this._buildMetrics(e),i=function(e,t,i){return rn(e,t,i)}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),s=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:on(i)},scopeMetrics:[{scope:{name:s,version:r},metrics:t}]}]};var t,i,s,r}_buildMetrics(e){const t=yn(Date.now()),i=new Map;for(const o of e.values()){var s;const e=bn(o.type,o.name,o.unit,void 0);let a=i.get(e);a||(a=ls({name:o.name},o.unit&&{unit:o.unit}),"count"===o.type?a.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===o.type?a.gauge={dataPoints:[]}:a.histogram={aggregationTemporality:1,dataPoints:[]},i.set(e,a));const l=Xr(null!==(s=o.attributes)&&void 0!==s?s:{},this._logger),c=yn(o.windowStartMs);if("count"===o.type){var r;const e={attributes:l,startTimeUnixNano:c,timeUnixNano:t,asDouble:null!==(r=o.total)&&void 0!==r?r:0};a.sum.dataPoints.push(e)}else if("gauge"===o.type){var n;const e={attributes:l,timeUnixNano:t,asDouble:null!==(n=o.last)&&void 0!==n?n:0};a.gauge.dataPoints.push(e)}else o.hist&&a.histogram.dataPoints.push({attributes:l,startTimeUnixNano:c,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:mn})}return Array.from(i.values())}_mergeWindowBack(e){for(const[s,r]of e){const e=this._series.get(s);if(e)switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.type){case"count":var t,i;e.total=(null!==(t=e.total)&&void 0!==t?t:0)+(null!==(i=r.total)&&void 0!==i?i:0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;e.hist.bucketCounts.length>t;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}else this._admitNewSeries()&&this._series.set(s,r)}}};const wn=(e,{debugEnabled:i}={})=>{const s={_log(s,...r){let n;try{n=typeof window>"u"?void 0:window}catch(e){return}n&&(t.DEBUG||n.POSTHOG_DEBUG||i)&&!ft(n.console)&&n.console&&("__rrweb_original__"in n.console[s]?n.console[s].__rrweb_original__:n.console[s])(e,...r)},debug(...e){s._log("debug",...e)},info(...e){s._log("log",...e)},warn(...e){s._log("warn",...e)},error(...e){s._log("error",...e)},critical(...t){console.error(e,...t)},uninitializedWarning(e){s.error(`You must initialize PostHog before calling ${e}`)},createLogger:(t,i)=>wn(`${e} ${t}`,i)};return s},En=wn("[PostHog.js]"),Cn=En.createLogger;function kn(e,t){_t(e)&&e.forEach(t)}function Pn(e,t){if(!St(e))if(_t(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(const i in e)dt.call(e,i)&&t(e[i],i)}const xn=function(e,...t){for(const i of t)for(const t in i)void 0!==i[t]&&(e[t]=i[t]);return e};function Fn(e){const t=Object.keys(e);let i=t.length;const s=new Array(i);for(;i--;)s[i]=[t[i],e[t[i]]];return s}const In=function(e){return function(...t){try{return e.apply(this,t)}catch(e){En.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),En.critical(e)}}},Tn=function(e){const t={};return Pn(e,function(e,i){(mt(e)&&e.length>0||wt(e))&&(t[i]=e)}),t};function Rn(e){const t=ls({},e);for(const i of["name","message","stack","cause","errors"])try{i in e&&(t[i]=e[i])}catch(e){}return t}const $n=["herokuapp.com","vercel.app","netlify.app"];function Mn(e){const t=null==e?void 0:e.hostname;if(!mt(t))return!1;const i=t.split(".").slice(-2).join(".");for(const e of $n)if(i===e)return!1;return!0}function An(e,t,i,s){const{capture:r=!1,passive:n=!0}=null!=s?s:{};null==e||e.addEventListener(t,i,{capture:r,passive:n})}function On(e){return"ph_toolbar_internal"===e.name}const Ln=e=>{if(Ge){try{const t=e+"=",i=Ge.cookie.split(";").filter(e=>e.length);for(let e=0;i.length>e;e++){let s=i[e];for(;" "==s.charAt(0);)s=s.substring(1,s.length);if(0===s.indexOf(t))return decodeURIComponent(s.substring(t.length,s.length))}}catch(e){}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return wt(e)&&isFinite(e)&&Math.floor(e)===e});var Dn=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,s,r){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||!Number.isInteger(r)||0>t||0>i||0>s||0>r||t>0xffffffffffff||i>4095||s>1073741823||r>4294967295)throw new RangeError("invalid field value");const n=new Uint8Array(16);return n[0]=t/Math.pow(2,40),n[1]=t/Math.pow(2,32),n[2]=t/Math.pow(2,24),n[3]=t/Math.pow(2,16),n[4]=t/256,n[5]=t,n[6]=112|i>>>8,n[7]=i,n[8]=128|s>>>24,n[9]=s>>>16,n[10]=s>>>8,n[11]=s,n[12]=r>>>24,n[13]=r>>>16,n[14]=r>>>8,n[15]=r,new e(n)}toString(){let e="";for(let t=0;this.bytes.length>t;t++)e=e+(this.bytes[t]>>>4).toString(16)+(15&this.bytes[t]).toString(16),3!==t&&5!==t&&7!==t&&9!==t||(e+="-");if(36!==e.length)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new e(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;16>t;t++){const i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}},Nn=class{generate(){const e=this.generateOrAbort();if(!ft(e))return e;{this._timestamp=0;const e=this.generateOrAbort();if(ft(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const e=(()=>{const e=Date.now();return wt(e)&&isFinite(e)?Math.min(Math.max(Math.floor(e),0),0xffffffffffff):0})();if(e>this._timestamp)this._timestamp=e,this._resetCounter();else{if(this._timestamp>=e+1e4)return;this._counter++,this._counter>4398046511103&&(this._timestamp++,this._resetCounter())}return Dn.fromFieldsV7(this._timestamp,Math.trunc(this._counter/Math.pow(2,30)),this._counter&Math.pow(2,30)-1,this._random.nextUint32())}_resetCounter(){this._counter=1024*this._random.nextUint32()+(1023&this._random.nextUint32())}constructor(){this._timestamp=0,this._counter=0,this._random=new qn}};let Bn=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};je&&!ft(je.crypto)&&crypto.getRandomValues&&(Bn=e=>crypto.getRandomValues(e));var qn=class{nextUint32(){return this._buffer.length>this._cursor||(Bn(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}};let Un;const Hn=()=>zn().toString(),zn=()=>(Un||(Un=new Nn)).generate();let jn="";const Wn=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let Vn=null;const Gn={_is_supported(){if(!bt(Vn))return Vn;if(Vn=!1,Ge)try{const e=`__ph_cookie_support_${Hn()}`;Gn._set(e,"xyz"),Vn='"xyz"'===Ln(e),Gn._remove(e)}catch(e){Vn=!1}return Vn},_error(e){En.error("cookieStore error: "+e)},_get:Ln,_parse(e){let t;try{t=JSON.parse(Gn._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Ge)return!1;try{let n="",o="";const a=function(e,t){if(t){let t=function(e,t=Ge){if(jn)return jn;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";const i=e.split(".");let s=Math.min(i.length,8);const r="dmn_chk_"+Hn();for(;!jn&&s--;){const e=i.slice(s).join("."),n=r+"=1;domain=."+e+";path=/";t.cookie=n+";max-age=3",t.cookie.includes(r)&&(t.cookie=n+";max-age=0",jn=e)}return jn}(e);if(!t){const i=(e=>{const t=e.match(Wn);return t?t[0]:""})(e);i!==t&&En.info("Warning: cookie subdomain discovery mismatch",i,t),t=i}return t?"; domain=."+t:""}return""}(Ge.location.hostname,s);if(i){const e=new Date;e.setTime(e.getTime()+864e5*i),n="; expires="+e.toUTCString()}r&&(o="; secure");const l=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return l.length>3686.4&&En.warn("cookieStore warning: large cookie, len="+l.length),Ge.cookie=l,!0}catch(e){return!1}},_remove(e,t){if((null==Ge?void 0:Ge.cookie)&&(!t||!bt(Ln(e))))try{Gn._set(e,"",-1,t)}catch(e){return}}};let Kn=null;const Qn={_is_supported(){if(!bt(Kn))return Kn;let e=!0;if(ft(je))e=!1;else try{const t="__mplssupport__";Qn._set(t,"xyz"),'"xyz"'!==Qn._get(t)&&(e=!1),Qn._remove(t)}catch(t){e=!1}return e||En.error("localStorage unsupported; falling back to cookie store"),Kn=e,e},_error(e){En.error("localStorage error: "+e)},_get(e){try{return null==je?void 0:je.localStorage.getItem(e)}catch(e){Qn._error(e)}return null},_parse(e){try{return JSON.parse(Qn._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==je||je.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Qn._error(e)}return!1},_remove(e){try{null==je||je.localStorage.removeItem(e)}catch(e){Qn._error(e)}}},Jn=[h,r,u,n,g,l,a,o,_],Yn=[S,b,K,Q,be,ye,P,pe],Zn=e=>e+"_cpm",Xn=["__proto__","constructor","prototype"],eo=e=>{if(!gt(e))return{};const t={};return Object.keys(e).forEach(i=>{-1===Xn.indexOf(i)&&(t[i]=e[i])}),t},to=(e,t=[])=>{const i={};return[...Yn,...t].forEach(t=>{const s=e[t];ft(s)||bt(s)||""===s||(i[t]=s)}),i},io=e=>{let t=5381,i=2166136261;for(let s=0;e.length>s;s++){const r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},so=(e,t)=>({p:t,f:io(JSON.stringify(e))}),ro=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const i=Gn._parse(Zn(e)),s=(null==i?void 0:i.f)===io(t)&&_t(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},no=(e,t)=>t+"|"+(Gn._get(Zn(e))||""),oo={},ao={_is_supported:()=>!0,_error(e){En.error("memoryStorage error: "+e)},_get:e=>e in oo?oo[e]:null,_parse:e=>e in oo?oo[e]:null,_set:(e,t)=>(oo[e]=t,!0),_remove(e){delete oo[e]}};let lo=null;const co={_is_supported(){if(!bt(lo))return lo;if(lo=!0,ft(je))lo=!1;else try{const e="__support__";co._set(e,"xyz"),'"xyz"'!==co._get(e)&&(lo=!1),co._remove(e)}catch(e){lo=!1}return lo},_error(e){En.error("sessionStorage error: ",e)},_get(e){try{return null==je?void 0:je.sessionStorage.getItem(e)}catch(e){co._error(e)}return null},_parse(e){try{return JSON.parse(co._get(e))||null}catch(e){}return null},_set(e,t){try{return null==je||je.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){co._error(e)}return!1},_remove(e){try{null==je||je.sessionStorage.removeItem(e)}catch(e){co._error(e)}}};var uo=class{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return"always"===this._config.cookieless_mode||this.isRejected()||-1===this.consent&&"on_reject"===this._config.cookieless_mode}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return 0===this.consent}isRejected(){return 0===this.consent||-1===this.consent&&this._config.opt_out_capturing_by_default}optInOut(e){this._storage._set(this._storageKey,e?1:0,this._config.cookie_expiration,this._config.cross_subdomain_cookie,this._config.secure_cookie)}reset(){this._storage._remove(this._storageKey,this._config.cross_subdomain_cookie)}get _storageKey(){const{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:i}=this._instance.config;return i||(t?t+e:"__ph_opt_in_out_"+e)}get _storedConsent(){const e=this._storage._get(this._storageKey);return Mt(e)?1:ot(At,e)?0:-1}get _storage(){const e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?Qn:Gn,i=t._is_supported()?t:ao;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;const t="localStorage"===e?Gn:Qn;t._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut(Mt(t._get(this._storageKey))),t._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==Ve?void 0:Ve.doNotTrack,null==Ve?void 0:Ve.msDoNotTrack,tt.doNotTrack,null==Ve?void 0:Ve.globalPrivacyControl].some(e=>Mt(e))}};function ho(e,t){var i;const s=null==e||null===(i=e.config)||void 0===i?void 0:i.get_current_url;if(!pt(s))return t;try{const e=s(t);return mt(e)&&e?e:t}catch(e){return En.error("Error in get_current_url, falling back to window.location.href",e),t}}function _o(e){var t;return e instanceof Element&&("__POSTHOG_TOOLBAR__"===e.id||!!(null===(t=e.closest)||void 0===t?void 0:t.call(e,".toolbar-global-fade-container")))}function po(e){return!!e&&1===e.nodeType}function go(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function vo(e){return!!e&&3===e.nodeType}function fo(e){return!!e&&11===e.nodeType&&po(e.host)}function mo(e){return e?at(e).split(/\s+/):[]}function yo(e,t){const i=function(e){var t;const i=null==je||null===(t=je.location)||void 0===t?void 0:t.href;return ft(i)?void 0:ho(e,i)}(t);return!!(i&&e&&e.some(e=>i.match(e)))}function bo(e){let t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return mo(t)}function So(e){return St(e)?null:at(e).split(/(\s+)/).filter(e=>Yo(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function wo(e){let t="";return Ho(e)&&!zo(e)&&e.childNodes&&e.childNodes.length&&Pn(e.childNodes,function(e){var i;vo(e)&&e.textContent&&(t+=null!==(i=So(e.textContent))&&void 0!==i?i:"")}),at(t)}function Eo(e){var t;return ft(e.target)?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null}const Co=["a","button","form","input","select","textarea","label"];function ko(e,t){const i=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!i&&i.call(e,t)}catch(e){return!1}}function Po(e,t){if(ft(t))return!0;for(const i of e)if(t.some(e=>ko(i,e)))return!0;return!1}function xo(e){const t=e.parentNode;return!(!t||!po(t))&&t}const Fo=[".ph-no-autocapture","[data-ph-no-autocapture]"],Io=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],To=[...Io,"+","-","−","–"],Ro=To.length+10,$o=["button","a","input","select","textarea","label"],Mo=["button","link","tab","menuitem","option"],Ao=(e,t)=>/[a-z0-9]/i.test(t)?ot(To,t)?new RegExp(`\\b${t}\\b`).test(e):e.includes(t):e===t,Oo=e=>ot($o,e.tagName.toLowerCase())||ot(Mo,(e.getAttribute("role")||"").toLowerCase());function Lo(e){let t="",i="";const s=e=>{po(e)&&Ho(e)&&!zo(e)&&(t+=` ${wo(e)}`,i=i||e.getAttribute("aria-label")||"",Pn(e.childNodes,s))};s(e),t=at(t.replace(/\s+/g," "));const r=(Yo(t)?t:"").toLowerCase(),n=e.getAttribute("aria-label")||(r?"":i);return{safeText:r,ariaLabel:at(n).toLowerCase()}}const Do=[".ph-no-rageclick",".ph-no-capture"],No=["","text","search","email","password","url","tel","number"];function Bo(e,t){if(!je||qo(e))return!1;let i,s,r;var n,o;if(Ct(t)?(i=!!t&&Do,s=void 0,r=!1):(i=null!==(n=null==t?void 0:t.css_selector_ignorelist)&&void 0!==n?n:Do,s=null==t?void 0:t.content_ignorelist,r=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(r&&function(e){return!(!e||!po(e))&&(!!go(e,"textarea")||(go(e,"input")?ot(No,(e.getAttribute("type")||"").toLowerCase()):function(e){var t;if(e.isContentEditable)return!0;const i=null===(t=e.getAttribute)||void 0===t?void 0:t.call(e,"contenteditable");return"true"===i||""===i}(e)))}(e))return!1;const{targetElementList:a}=Uo(e,!1);return!(s&&function(e,{safeText:t,ariaLabel:i}){let s;if(!0===e)s=Io;else{if(!_t(e))return!1;if(e.length>Ro)return En.error(`[PostHog] content_ignorelist array cannot exceed ${Ro} items. Use css_selector_ignorelist for more complex matching.`),!1;s=e.map(e=>e.toLowerCase())}return s.some(e=>Ao(t,e)||Ao(i,e))}(s,function(e,t){for(const e of t)if(Oo(e))return Lo(e);for(const e of t){try{if("pointer"!==(null==je?void 0:je.getComputedStyle(e).getPropertyValue("cursor")))break}catch(e){break}const t=Lo(e);if(t.safeText||t.ariaLabel)return t}return Lo(e)}(e,a))||Po(a,i))}const qo=e=>!e||go(e,"html")||!po(e),Uo=(e,t)=>{if(!je||qo(e))return{parentIsUsefulElement:!1,targetElementList:[]};let i=!1;const s=[e];let r=e;for(;r.parentNode&&!go(r,"body");){if(fo(r.parentNode)){s.push(r.parentNode.host),r=r.parentNode.host;continue}const e=xo(r);if(!e)break;if(t||Co.indexOf(e.tagName.toLowerCase())>-1)i=!0;else try{const t=je.getComputedStyle(e);t&&"pointer"===t.getPropertyValue("cursor")&&(i=!0)}catch(e){}s.push(e),r=e}return{parentIsUsefulElement:i,targetElementList:s}};function Ho(e){const t=new Set;let i=0;for(let s=e;s.parentNode&&!go(s,"body");s=s.parentNode){if(i++>=1e3||t.has(s))return!1;t.add(s);const e=bo(s);if(ot(e,"ph-sensitive")||ot(e,"ph-no-capture"))return!1}if(ot(bo(e),"ph-include"))return!0;const s=e.type||"";if(mt(s))switch(s.toLowerCase()){case"hidden":case"password":return!1}const r=e.name||e.id||"";return!mt(r)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(r.replace(/[^a-zA-Z0-9]/g,""))}function zo(e){return!!(go(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||go(e,"select")||go(e,"textarea")||"true"===e.getAttribute("contenteditable"))}const jo=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),Wo=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,Vo=[16,15,14,13],Go=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Ko=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),Qo=/[0-9A-Za-z_]/;function Jo(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let r=e.charCodeAt(s)-48;i&&(r*=2,r>9&&(r-=9)),t+=r,i=!i}return t%10==0}function Yo(e,t=!0){if(St(e))return!1;if(mt(e)){if(e=at(e),t?jo.test((e||"").replace(/[- ]/g,"")):function(e){let t;for(Wo.lastIndex=0;t=Wo.exec(e);){const e=t[2];if(!e)continue;const i=e.replace(/[- ]/g,"");for(let e=0;i.length>e;e++)for(const t of Vo){const s=e+t;if(i.length>=s){const t=i.slice(e,s);if(jo.test(t)&&Jo(t))return!0}}}return!1}(e))return!1;if(t?Go.test(e):function(e){let t;for(Ko.lastIndex=0;t=Ko.exec(e);){const e=t[1],i=t[3];if(!(e&&i&&Qo.test(e)&&Qo.test(i)))return!0}return!1}(e))return!1}return!0}function Zo(e){let t=wo(e);return t=`${t} ${Xo(e)}`.trim(),Yo(t)?t:""}function Xo(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Pn(e.childNodes,function(e){var i;if(e&&"span"===(null===(i=e.tagName)||void 0===i?void 0:i.toLowerCase()))try{const i=wo(e);t=`${t} ${i}`.trim(),e.childNodes&&e.childNodes.length&&(t=`${t} ${Xo(e)}`.trim())}catch(e){En.error("[AutoCapture]",e)}}),t}function ea(e){return e.replace(/"|\\"/g,'\\"')}function ta(e){const t=e.attr__class;if(t)return _t(t)?t:mo(t)}const ia=Cn("[Dead Clicks]"),sa=()=>!0,ra=e=>{var t;const i=!!(null===(t=e.instance.persistence)||void 0===t?void 0:t.get_property(D)),s=e.instance.config.capture_dead_clicks;return Ct(s)?s:!!gt(s)||i};var na=class{get lazyLoadedDeadClicksAutocapture(){return this._lazyLoadedDeadClicksAutocapture}constructor(e,t,i){this.instance=e,this.isEnabled=t,this.onCapture=i,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[D]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript(()=>{this._start()}):this.stop()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.initDeadClicksAutocapture)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this.instance,"dead-clicks-autocapture",t=>{t?ia.error("failed to load script",t):e()})}_start(){var e;if(Ge){if(!this._lazyLoadedDeadClicksAutocapture&&(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.initDeadClicksAutocapture)){const e=gt(this.instance.config.capture_dead_clicks)?ls({},this.instance.config.capture_dead_clicks):{};e.__onCapture=this.onCapture,this.onCapture&&(e.capture_dead_swipes=!1),this._lazyLoadedDeadClicksAutocapture=tt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,e),this._lazyLoadedDeadClicksAutocapture.start(Ge),ia.info("starting...")}}else ia.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,ia.info("stopping..."))}};const oa=Cn("[SegmentIntegration]");function aa(e,t,i=!0){const s=e.config.segment;if(!s)return t();const{analytics:r,filterProperties:n}=(e=>pt(e.register))(o=s)?{analytics:o}:o;var o;!function(e,t,i,s){const r=t=>{const r=()=>t.anonymousId()||Hn();e.config.get_device_id=r,s&&t.id()&&(e.register({distinct_id:t.id(),$device_id:r()}),e.persistence.set_property(pe,De)),i(s?void 0:t.anonymousId()||void 0)},n=t.user();"then"in n&&pt(n.then)?n.then(r):r(n)}(e,r,i=>{r.register(((e,t,{filterProperties:i}={})=>{"undefined"!=typeof Promise&&Promise.resolve||oa.warn("This browser does not have Promise support, and can not use the segment integration");const s=(s,r)=>{if(!r)return s;const n=!!t&&s.event.anonymousId===t&&!s.event.userId;n||s.event.userId||s.event.anonymousId===e.get_distinct_id()||(oa.info("No userId set, resetting PostHog"),e.reset()),n||(t=void 0),s.event.userId&&s.event.userId!==e.get_distinct_id()&&(oa.info("UserId set, identifying with PostHog"),e.identify(s.event.userId));let o=e.calculateEventProperties(r,s.event.properties);if(!St(i)){const e=s.event.properties||{},t={};for(const i of Object.keys(o))dt.call(e,i)||(t[i]=o[i]);const r=((e,t)=>{const i=_t(e)?e:[e];let s=ls({},t);for(const e of i)try{if(s=e(s),St(s))return null}catch(e){return oa.error("Error in Segment filterProperties:",e),null}return s})(i,t);if(St(r))return s;o=r}return s.event.properties=Object.assign({},o,s.event.properties),s};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(e){return s(e,e.event.event)},page(e){return s(e,qe)},identify(e){return s(e,He)},screen(e){return s(e,"$screen")}}})(e,i,{filterProperties:n})).then(()=>{t()},e=>{oa.error("Failed to register the Segment integration",e),t()})},i)}const la="posthog-js";function ca(e,{organization:t,projectId:i,prefix:s,severityAllowList:r=["error"],sendExceptionsToPostHog:n=!0}={}){return o=>{var a,l,c,u,d;if("*"!==r&&!r.includes(o.level)||!e.__loaded)return o;o.tags||(o.tags={});const h=e.requestRouter.endpointFor("ui",`/project/${e.config.token}/person/${e.get_distinct_id()}`);o.tags["PostHog Person URL"]=h,e.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));const _=(null===(a=o.exception)||void 0===a?void 0:a.values)||[],p=_.map(e=>ls(ls({},e),{},{stacktrace:e.stacktrace?ls(ls({},e.stacktrace),{},{type:"raw",frames:(e.stacktrace.frames||[]).map(e=>ls(ls({},e),{},{platform:"web:javascript"}))}):void 0})),g={$exception_message:(null===(l=_[0])||void 0===l?void 0:l.value)||o.message,$exception_type:null===(c=_[0])||void 0===c?void 0:c.type,$exception_level:o.level,$exception_list:p,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:(null===(u=_[0])||void 0===u?void 0:u.value)||o.message,$sentry_exception_type:null===(d=_[0])||void 0===d?void 0:d.type,$sentry_tags:o.tags};var v;return t&&i&&(g.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+o.event_id),n&&(null===(v=e.exceptions)||void 0===v||v.sendExceptionEvent(g)),o}}var ua=class{constructor(e,t,i,s,r,n){this.name=la,this.setupOnce=function(o){o(ca(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}},da=class{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(En.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:e,changeReason:i}),this._currentPageview=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this._setupSessionRotationHandler()}_setupSessionRotationHandler(){var e;this._unsubscribeSessionId=null===(e=this._instance.sessionManager)||void 0===e?void 0:e.onSessionId(this._onSessionIdChange)}destroy(){var e;null===(e=this._unsubscribeSessionId)||void 0===e||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i;const s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==je?void 0:je.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null===(t=this._currentPageview)||void 0===t?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null===(e=this._currentPageview)||void 0===e?void 0:e.pageViewId}}_previousPageViewProperties(e,t){const i=this._currentPageview;if(!i)return{$pageview_id:t};let s={$pageview_id:t,$prev_pageview_id:i.pageViewId};const r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:e,lastScrollY:t,maxScrollY:i,maxContentHeight:n,lastContentY:o,maxContentY:a}=r;if(!(ft(e)||ft(t)||ft(i)||ft(n)||ft(o)||ft(a))){e=Math.ceil(e),t=Math.ceil(t),i=Math.ceil(i),n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a);const r=e>1?qt(t/e,0,1,En):1,l=e>1?qt(i/e,0,1,En):1,c=n>1?qt(o/n,0,1,En):1,u=n>1?qt(a/n,0,1,En):1;s=xn(s,{$prev_pageview_last_scroll:t,$prev_pageview_last_scroll_percentage:r,$prev_pageview_max_scroll:i,$prev_pageview_max_scroll_percentage:l,$prev_pageview_last_content:o,$prev_pageview_last_content_percentage:c,$prev_pageview_max_content:a,$prev_pageview_max_content_percentage:u})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}};const ha=["flags","surveys"],_a={[y]:{exposure:"hidden"},[E]:{exposure:"hidden"},[C]:{exposure:"hidden"},[I]:{exposure:"hidden"},[P]:{exposure:"hidden"},[F]:{exposure:"hidden"},[T]:{exposure:"event"},[R]:{exposure:"hidden"},[B]:{exposure:"hidden"},[M]:{exposure:"event"},[A]:{exposure:"hidden"},[O]:{exposure:"event"},[L]:{exposure:"event"},[D]:{exposure:"event"},[N]:{exposure:"hidden"},[q]:{exposure:"event"},[U]:{exposure:"hidden"},[H]:{exposure:"hidden"},[K]:{exposure:"hidden"},[Q]:{exposure:"event"},[z]:{exposure:"event",shouldSkipFromEventProperties:e=>bt(e)},[J]:{exposure:"event"},[Y]:{exposure:"event"},[Z]:{exposure:"event"},[X]:{exposure:"event"},[ee]:{exposure:"hidden"},[u]:{exposure:"hidden",storageGroup:"flags"},[r]:{exposure:"hidden",storageGroup:"flags"},[s]:{exposure:"hidden"},[n]:{exposure:"hidden",storageGroup:"flags"},[g]:{exposure:"hidden",storageGroup:"flags"},[l]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[c]:{exposure:"hidden",storageGroup:"flags"},[v]:{exposure:"hidden"},[f]:{exposure:"hidden"},[h]:{exposure:"hidden"},[d]:{exposure:"hidden"},[ie]:{exposure:"hidden",storageGroup:"surveys"},[se]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[re]:{exposure:"event"},[ne]:{exposure:"hidden"},[oe]:{exposure:"hidden"},[ae]:{exposure:"hidden"},[le]:{exposure:"hidden"},[ce]:{exposure:"hidden"},[ue]:{exposure:"event"},[de]:{exposure:"event"},[he]:{exposure:"event"},[_e]:{exposure:"event"},[_]:{exposure:"hidden"},[p]:{exposure:"hidden"},[te]:{exposure:"event"},[o]:{exposure:"hidden"},[a]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[pe]:{exposure:"hidden"},[ge]:{exposure:"hidden"},[ve]:{exposure:"hidden"},[fe]:{exposure:"hidden"},[me]:{exposure:"hidden"},[ye]:{exposure:"hidden"},[be]:{exposure:"hidden"},[j]:{exposure:"event"},[W]:{exposure:"event"},[V]:{exposure:"event"},[G]:{exposure:"event"},[Ee]:{exposure:"event"},[Ce]:{exposure:"event"},[ke]:{exposure:"hidden"},[Pe]:{exposure:"hidden"},[xe]:{exposure:"hidden"},[Fe]:{exposure:"hidden"},[Ie]:{exposure:"hidden"},[Te]:{exposure:"hidden"},[Re]:{exposure:"hidden"},[$e]:{exposure:"hidden"},[Me]:{exposure:"hidden"},[Ae]:{exposure:"event"}},pa=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ga=e=>{const t=_a[e];if(t)return t;for(const[t,i]of pa)if(0===e.indexOf(t))return i};function va(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}const fa=()=>{try{return"u">typeof window&&!1!==window.navigator.onLine}catch(e){return!1}},ma=(e,t)=>e>=t&&fa(),ya=(e,t,i,s)=>{if(0===e){if(fa()){const e=t+1;return e===i&&s(),e}return t}return 0},ba=(e,t)=>{try{let i;return JSON.stringify(e,(e,t)=>{var s;return It(t)?(null!==(s=i)&&void 0!==s||(i=new WeakMap),i.has(t)||i.set(t,Rn(t)),i.get(t)):"bigint"==typeof t?t.toString():t},t)}catch(t){return ct(e)}},Sa=e=>{const t=null==Ge?void 0:Ge.createElement("a");return ft(t)?null:(t.href=e,t)},wa=function(e,t){const i=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let s;for(let e=0;i.length>e;e++){const r=i[e].split("=");if(r[0]===t){s=r;break}}if(!_t(s)||2>s.length)return"";{let e=s[1];try{e=decodeURIComponent(e)}catch(t){En.error("Skipping decoding for malformed query param: "+e)}return e.replace(/\+/g," ")}},Ea=function(e,t,i){if(!e||!t||!t.length)return e;const s=e.split("#"),r=s[1],n=(s[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),c=[];for(let e=0;l.length>e;e++){const s=l[e].split("=");_t(s)&&(t.includes(s[0])?c.push(s[0]+"="+i):c.push(l[e]))}let u=a;return null!=o&&(u+="?"+c.join("&")),null!=r&&(u+="#"+r),u},Ca=function(e,t){const i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},ka=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","irclid","_kx"],Pa=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ka],xa="<masked>",Fa=["li_fat_id"];function Ia(e,t,i){if(!Ge)return{};const s=t?[...ka,...i||[]]:[],r=Ta(Ea(Ge.URL,s,xa),e),n=function(){const e={};return Pn(Fa,function(t){const i=Ln(t);e[t]=i||null}),e}();return xn(n,r)}function Ta(e,t){const i=Pa.concat(t||[]),s={};return Pn(i,function(t){const i=wa(e,t);s[t]=i||null}),s}function Ra(e){const t=function(e){return e?0===e.search("https?://(.*)google.([^/?]*)")?"google":0===e.search("https?://(.*)bing.com")?"bing":0===e.search("https?://(.*)yahoo.com")?"yahoo":0===e.search("https?://(.*)duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!bt(t)){s.$search_engine=t;const e=Ge?wa(Ge.referrer,i):"";e.length&&(s.ph_keyword=e)}return s}function $a(){return navigator.language||navigator.userLanguage}function Ma(){const e=$a();return"string"==typeof e?e.split("-")[0]:void 0}const Aa="$direct";function Oa(){return(null==Ge?void 0:Ge.referrer)||Aa}function La(e,t,i=!1){const s=e?[...ka,...t||[]]:[],r=i?es(null==Ke?void 0:Ke.href):null==Ke?void 0:Ke.href,n=null==r?void 0:r.substring(0,1e3);return{r:Oa().substring(0,1e3),u:n?Ea(n,s,xa):void 0}}function Da(e,t=!1){var i;const{r:s,u:r}=e,n=t?es(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==Aa?Aa:null===(i=Sa(s))||void 0===i?void 0:i.host};if(n){o.$current_url=n;const e=Sa(n);o.$host=null==e?void 0:e.host,o.$pathname=null==e?void 0:e.pathname;const t=Ta(n);xn(o,t)}if(s){const e=Ra(s);xn(o,e)}return o}function Na(){try{return(new Date).getTimezoneOffset()}catch(e){return}}const Ba={flags:a,surveys:se},qa=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Ua=e=>`${e}_cookie_identity_change_pending`,Ha=e=>{let t="",i=0;for(const s of e){const e=encodeURIComponent(JSON.stringify(s).slice(1,-1)).length;if(i+e>1e3)break;t+=s,i+=e}return t},za="main",ja=[u,r,n,g,l,a,c,h],Wa=e=>-1!==ja.indexOf(e),Va=[P,F],Ga=e=>-1!==Va.indexOf(e),Ka=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},Qa=e=>{if(!e)return{};const t=JSON.parse(e);return gt(t)?t:{}},Ja=(e,t)=>{Pn(e,(i,s)=>{const r=ga(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]})};var Ya=class{constructor(e,t,i=!0,s=!e.cookieless_mode){if(this._slotState={},this._splitStorageEligible=!1,this._storesIdentityInCookie=!1,this._splitStorage=!1,this._cookieIdentityChangePending=!1,this._cookieSyncSuppressed=!1,this._pendingCrossTabFeatureFlagChanges=new Map,this._storageMigrationInProgress=!1,this._localIdentityChangePending=!1,this._crossTabFeatureFlagIdentityMismatch=!1,this._metaIdentifierChangePending=new Set,this._crossTabFeatureFlagHandlers=new Set,this._config=e,this._ownsSplitStorage=i,this.props={},this._campaign_params_url=void 0,this._name=(e=>{let t="";return e.token&&(t=e.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),e.persistence_name?"ph_"+e.persistence_name:"ph_"+t+"_posthog"})(e),this._disabled=e.disable_persistence||!!t,this._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(s),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&En.info("Persistence loaded",e.persistence,ls({},this.props)),this.update_config(e,e,t),this.save(),je){const e=()=>this.flush();An(je,"beforeunload",e,{capture:!1}),An(je,"pagehide",e,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==je?void 0:je.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){const t=ha.find(t=>e.key===this._groupEntryName(t));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,za)},An(je,"storage",this._onStorage)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([e,t])=>{const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!Wa(e)||!0===i)return;if(!0===t)return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(i||[]);t.forEach(e=>s.add(e)),s.size&&this._setCrossTabFeatureFlagChangesPending(e,s)})}onCrossTabFeatureFlagChange(e){return this._crossTabFeatureFlagHandlers.add(e),()=>this._crossTabFeatureFlagHandlers.delete(e)}destroy(){this._onStorage&&je&&(je.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i=!0){if(this._disabled)return!1;let s,r;try{if(r=Qn._get(e),bt(r)){const e=this._slotWriteState(t);return e.storageValue=null,t!==za&&(e.persisted=!1),!1}s=Qa(r)}catch(e){return!1}const n=t===za?s:Qn._parse(this._name);if(n&&this._hasCrossTabFeatureFlagIdentityMismatch(n))return!1;const o=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===za&&this._splitStorage&&!Ka(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,r),o}_hasCrossTabFeatureFlagIdentityMismatch(e){const t=this.props[b],i=e[b];return!ft(t)&&!ft(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){const r=this._slotWriteState(t);r.storageValue=s,t!==za&&(r.persisted=i);try{r.fingerprint=this._entryFingerprint(e,t)}catch(e){r.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){let s=!1;return ja.forEach(i=>{var r;const n=null===(r=ga(i))||void 0===r?void 0:r.storageGroup;if(t===za&&this._splitStorage&&n||t!==za&&n!==t)return;const o=i in e,a=this._mergePendingCrossTabFeatureFlagChanges(i,o?e[i]:void 0),l=this._pendingCrossTabFeatureFlagChanges.has(i)?i in this.props:o;l===i in this.props&&Ka(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}),s&&i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()),s}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;const e=Qn._get(this._name),t=this._slotWriteState(za);let i,s=!1,r=!1;if(e!==t.storageValue)if(bt(e))t.storageValue=null;else{if(i=Qa(e),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(i),this._crossTabFeatureFlagIdentityMismatch)return!1;r=this._mergeCrossTabFeatureFlagProperties(i,za,!1),!this._splitStorage||Ka(this._partitionProps().main,i)?this._rememberCrossTabStorageFingerprint(i,za,!0,e):t.storageValue=e,s=!0}return this._splitStorage&&ha.forEach(e=>{const t=Qn._get(this._groupEntryName(e)),n=this._slotWriteState(e),o=i||{},a=s&&ja.some(t=>{var i;return(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e&&t in o});if(t===n.storageValue&&!a)return;if(bt(t))return n.storageValue=null,n.persisted=!1,void(a&&(r=this._mergeCrossTabFeatureFlagProperties(o,e,!1)||r));const l=Qa(t);r=this._mergeCrossTabFeatureFlagProperties(l,e,!1)||r,this._rememberCrossTabStorageFingerprint(l,e,!0,t)}),r}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);const i=ga(e);(null==i?void 0:i.volatile)||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||za).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){ja.forEach(e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{const e=Qn._get(this._name),t=Qa(e);this._slotWriteState(za).storageValue=e,ja.forEach(e=>{var i;const s=this._splitStorage?null===(i=ga(e))||void 0===i?void 0:i.storageGroup:void 0,r=s?Qn._get(this._groupEntryName(s)):null;if(s){const e=this._slotWriteState(s);e.storageValue=r,e.persisted=!bt(r)}const n=s&&!bt(r)?Qa(r):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,n[e],this.props[e]):e in n&&this._setCrossTabFeatureFlagChangesPending(e,!0)})}catch(e){}}_mergePendingCrossTabFeatureFlagChanges(e,t){const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!i)return t;if(!0===i)return this.props[e];if("$active_feature_flags"===e){const s=new Set(_t(t)?t:[]),r=new Set(_t(this.props[e])?this.props[e]:[]);return i.forEach(e=>r.has(e)?s.add(e):s.delete(e)),Array.from(s)}const s=gt(t)?ls({},t):{},r=gt(this.props[e])?this.props[e]:{};return i.forEach(e=>{e in r?s[e]=r[e]:delete s[e]}),s}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(!Wa(e))return;const s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0===s)return;let r=t;if(this._splitStorageEligible)try{var n;const t=this._splitStorage?null===(n=ga(e))||void 0===n?void 0:n.storageGroup:void 0,i=t?this._groupEntryName(t):this._name;r=Qa(Qn._get(i))[e]}catch(e){}const o=new Set(s||[]);if("$active_feature_flags"===e){if(!ft(t)&&!_t(t)||!ft(r)&&!_t(r)||!_t(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(t||[]),n=new Set(r||[]),a=new Set(i);new Set([...s,...a]).forEach(e=>{s.has(e)!==a.has(e)&&o.add(e)}),o.forEach(e=>{n.has(e)===a.has(e)&&o.delete(e)})}else{if(!gt(i))return void(Ka(r,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));{if(!ft(t)&&!gt(t)||ft(t)&&vt(i)&&ft(r))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=gt(t)?t:{},n=gt(r)?r:{};new Set([...Object.keys(s),...Object.keys(i)]).forEach(e=>{e in s==e in i&&Ka(s[e],i[e])||o.add(e)}),o.forEach(e=>{e in n==e in i&&Ka(n[e],i[e])&&o.delete(e)})}}o.size?this._setCrossTabFeatureFlagChangesPending(e,o):this._pendingCrossTabFeatureFlagChanges.delete(e)}_saveDebounceMs(){var e;const t=null===(e=this._config)||void 0===e?void 0:e.persistence_save_debounce_ms;return wt(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{const t=to(e,this._config.cookie_persisted_properties||[]),i=so(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=Gn._get(this._name)||void 0;r&&no(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{const e=Gn._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=e?no(this._name,e):void 0,this._lastSeenMainCookieValue=e}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t=!1){if(this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;let i;try{i=Gn._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;const s=no(this._name,i);let c;try{c=eo(JSON.parse(i))}catch(e){return!1}if((Gn._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=i;const p=ro(this._name,i),v=[...Yn,...p.properties],f={};if(Object.keys(c).forEach(e=>{const t=c[e];(ft(t)||bt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t)&&(f[e]=!0,delete c[e])}),vt(c))return!1;const m="distinct_id"in c||"anonymous"===c.$user_state||"identified"===c.$user_state,y=this.props,S=y[b],w=y[pe],C=xn({},y);[...Yn,...e.cookie_persisted_properties||[]].forEach(e=>{if(-1!==v.indexOf(e)&&!(e in c)&&!f[e]&&(m||"distinct_id"!==e&&"$user_state"!==e)){const t=C[e];(p.isValid||-1===Yn.indexOf(e)||!1!==t&&0!==t)&&delete C[e]}}),this.props=xn(C,c),ja.forEach(e=>{const t=e in this.props;e in y===t&&Ka(y[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,y[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))}),!m||"$user_state"in c||"$user_state"in this.props||this._setProp(pe,Le);const k=this.props[b],P=this.props[pe];return!m||k===S&&P===w||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,co._set(Ua(this._name),!0),this._deleteProp(h),this._deleteProp(r),this._deleteProp(u),this._deleteProp(n),this._deleteProp(g),this._deleteProp(l),this._deleteProp(a),this._deleteProp(o),this._deleteProp(_),"anonymous"!==P||"identified"!==w&&"anonymous"!==c.$user_state&&(ft(S)||k===S)||(Ja(this.props,c),this._deleteProp(d)),"identified"===P?this.props.$user_id=k:delete this.props.$user_id,this._deleteProp(E)),!0}consumeCookieIdentityChange(){const e=Ua(this._name),t=this._cookieIdentityChangePending||!!co._get(e);return this._cookieIdentityChangePending=!1,t&&co._remove(e),t}_beginCookieSyncSuppression(e=!1){return!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[za],this._writeNow(!0))}_endCookieSyncSuppression(e=!0){if(this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===qa.indexOf(e.persistence.toLowerCase())&&(En.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((e=[],t=!1,i=()=>!1)=>{const s=[...Yn,...e];return ls(ls({},Qn),{},{_parse(e){try{let n,o={};try{n=Gn._get(e)||void 0,o=n?eo(JSON.parse(n)):{}}catch(e){}const a=JSON.parse(Qn._get(e)||"{}");let l;if(t){const t=ro(e,n),i=[...Yn,...t.properties],c={};Object.keys(o).forEach(e=>{const t=o[e];bt(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t||(c[e]=t)});const u="distinct_id"in c||"anonymous"===c.$user_state||"identified"===c.$user_state;if(Object.keys(c).length>0){var r;const e=a[b],n=null!==(r=a.$user_state)&&void 0!==r?r:Le;s.forEach(e=>{if(-1!==i.indexOf(e)&&!(e in o)&&(u||"distinct_id"!==e&&"$user_state"!==e)){const i=a[e];(t.isValid||-1===Yn.indexOf(e)||!1!==i&&0!==i)&&delete a[e]}}),!u||"$user_state"in o||"$user_state"in a||(a[pe]=Le),!u||("distinct_id"in c?c[b]:a[b])===e&&("$user_state"in c?c[pe]:a[pe])===n||(Jn.forEach(e=>delete a[e]),"identified"===c.$user_state&&"distinct_id"in c?a.$user_id=c[b]:delete a.$user_id,"identified"!==c.$user_state&&(delete a[te],delete a[d]),delete a.__alias)}l=xn(a,c)}else l=xn(o,a);return i()||Qn._set(e,l),l}catch(e){}return null},_set(i,s,r,n,o,a){const l=Qn._set(i,s,void 0,void 0,a);try{const c=to(s,e);if(Object.keys(c).length){if(t){const t=Zn(i),u=so(c,e);if(Gn._set(t,u,r,n,o,a),Gn._get(t)!==JSON.stringify(u)){Gn._remove(t,n);const e=to(s);return Gn._set(i,e,r,n,o,a),l}}Gn._set(i,c,r,n,o,a)}}catch(e){Qn._error(e)}return l},_remove(e,t){try{null==je||je.localStorage.removeItem(e),Gn._remove(e,t),Gn._remove(Zn(e),t)}catch(e){Qn._error(e)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this._disabled);let i,s=!1,r=!1;const n=e.persistence.toLowerCase();return"localstorage"===n&&Qn._is_supported()?(i=Qn,r=!0):"localstorage+cookie"===n&&t._is_supported()?(i=t,r=!0,s=!0):"sessionstorage"===n&&co._is_supported()?i=co:"memory"===n?i=ao:"cookie"===n&&Gn._is_supported()?(i=Gn,s=!0):t._is_supported()?(i=t,r=!0,s=!0):Gn._is_supported()?(i=Gn,s=!0):i=ao,this._splitStorageEligible=r,this._storesIdentityInCookie=s,i}_groupEntryName(e){return`${this._name}__${e}`}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){const e={};return Pn(this.props,(t,i)=>{const s=ga(i);if(!s||"event"===s.exposure){var r;if(null==s||null===(r=s.shouldSkipFromEventProperties)||void 0===r?void 0:r.call(s,t))return;e[i]=t}}),e}load(e=!1){if(this._disabled&&!e)return;const t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?Qn._parse(this._name):null;let s={};if(t)try{s=eo(Gn._parse(this._name)),Pn(s,(e,t)=>{(ft(e)||bt(e)||""===e)&&delete s[t]})}catch(e){}const r=this._storage._parse(this._name);if(r&&(this.props=xn({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,o;const e=null==i?void 0:i[b],t=null!==(n=null==i?void 0:i.$user_state)&&void 0!==n?n:Le,a=r[b],l=null!==(o=r.$user_state)&&void 0!==o?o:Le;if(a!==e||l!==t){this._cookieIdentityChangePending=!0,this._disabled||co._set(Ua(this._name),!0);const i=xn({},this.props);Jn.forEach(e=>delete i[e]),"anonymous"!==l||"identified"!==t&&"anonymous"!==s.$user_state&&(ft(e)||a===e)||(Ja(i,s),delete i[d]),this.props=i;const r=new Set;Jn.forEach(e=>{var t;const i=null===(t=ga(e))||void 0===t?void 0:t.storageGroup;i&&r.add(i)}),r.forEach(e=>{if(this._disabled)return;const t={};Pn(this.props,(i,s)=>{var r;(null===(r=ga(s))||void 0===r?void 0:r.storageGroup)===e&&(t[s]=i)}),vt(t)?(Qn._remove(this._groupEntryName(e)),this._slotState[e]={}):Qn._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})})}}co._get(Ua(this._name))&&(this._cookieIdentityChangePending=!0)}_loadGroupEntries(){for(const e of ha){const t=Qn._parse(this._groupEntryName(e));if(t&&!vt(t)){const i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||xn(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some(t=>{var i;return(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e})}_groupEntryIsStale(e,t){const i=Ba[e];if(!i)return!1;const s=t[i],r=this.props[i];return wt(s)&&wt(r)&&r>s}refreshKey(e){var t;if(this._disabled)return;if(this._metaIdentifierChangePending.has(e))return;const i=this._splitStorage?null===(t=ga(e))||void 0===t?void 0:t.storageGroup:void 0,s=i?Qn._parse(this._groupEntryName(i)):this._storage._parse(this._name);if(s&&e in s)this._setProp(e,s[e],!1);else{if(i){const t=this._storage._parse(this._name);if(t&&e in t)return void this._setProp(e,t[e],!1)}this._deleteProp(e,!1)}}save(){if(this._disabled)return;const e=this._saveDebounceMs();e>0?ft(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout(()=>{this._pendingSaveTimer=void 0,this._writeNow()},e)):this._writeNow()}flush(){ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e=!1){if(this._disabled||this._cookieSyncSuppressed&&!e)return;e||(this.syncCookieProperties(),this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase()||Va.forEach(e=>this.refreshKey(e)));const t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);const i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)return void(this._config.debug&&En.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()));const s=this._writeEntry(this._storage,this._name,this.props,za);"written"===s&&this._rememberCurrentCookieProperties(this.props),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear()),i&&this._crossTabFeatureFlagHandlers.forEach(e=>e())}_writeNowSplit(){const{main:e,groups:t}=this._partitionProps(),i=this._writeEntry(this._storage,this._name,e,za);"written"===i&&this._rememberCurrentCookieProperties(e),"failed"!==i&&(this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear(),ja.forEach(e=>{var t;(null===(t=ga(e))||void 0===t?void 0:t.storageGroup)||this._pendingCrossTabFeatureFlagChanges.delete(e)}));for(const e of ha){var s;const i=t[e];if(vt(i)&&!(null===(s=this._slotState[e])||void 0===s?void 0:s.persisted)){ja.forEach(t=>{var i;(null===(i=ga(t))||void 0===i?void 0:i.storageGroup)===e&&this._pendingCrossTabFeatureFlagChanges.delete(t)});continue}const r=this._writeEntry(Qn,this._groupEntryName(e),i,e);"failed"!==r&&ja.forEach(t=>{const i=ga(t);(null==i?void 0:i.storageGroup)!==e||"written"!==r&&i.volatile||this._pendingCrossTabFeatureFlagChanges.delete(t)})}}_partitionProps(){const e={},t={flags:{},surveys:{}};return Pn(this.props,(i,s)=>{var r;const n=null===(r=ga(s))||void 0===r?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i}),{main:e,groups:t}}_entryFingerprint(e,t){if(t===za)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;const i={};return Pn(e,(e,t)=>{var s;i[t]=(null===(s=ga(t))||void 0===s?void 0:s.volatile)?"__volatile__":e}),JSON.stringify(i)}_writeEntry(e,t,i,s){const r=this._slotWriteState(s);if(s!==za&&!r.dirty&&!ft(r.fingerprint))return"skipped";let n;try{if(n=this._entryFingerprint(i,s),n===r.fingerprint)return r.dirty=!1,"skipped"}catch(e){n=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(r.dirty=!1,s!==za&&(r.persisted=!0),ft(n)||(r.fingerprint=n),this._splitStorageEligible&&(r.storageValue=Qn._get(t)),"written"):(this._config.debug&&En.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this._markAllCrossTabFeatureFlagChangesPending(),ft(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!e&&this._ownsSplitStorage)for(const e of ha)Qn._remove(this._groupEntryName(e));e?delete this._slotState[za]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(gt(e)){this.syncCookieProperties(),ft(t)&&(t="None"),this._expire_days=ft(i)?this._default_expiry:i;let s=!1;if(Pn(e,(e,i)=>{this.props.hasOwnProperty(i)&&this.props[i]!==t||(this._setProp(i,e),s=!0)}),s)return this.save(),!0}return!1}register(e,t){if(gt(e)){this.syncCookieProperties(),this._expire_days=ft(t)?this._default_expiry:t;let i=!1;if(Pn(e,(t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||gt(t)||_t(t))&&(this._setProp(s,t),i=!0)}),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t="string"==typeof e?[e]:e;let i=!1;for(const e of t)e in this.props&&(this._deleteProp(e),i=!0);i&&this.save()}update_campaign_params(){const e=null==Ge?void 0:Ge.URL;if(e===this._campaign_params_url)return;const t=Ia(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!vt(Tn(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}update_search_keyword(){this.register(function(){const e=null==Ge?void 0:Ge.referrer;return e?Ra(e):{}}())}update_referrer_info(){var e;this.register_once({$referrer:Oa(),$referring_domain:(null==Ge?void 0:Ge.referrer)&&(null===(e=Sa(Ge.referrer))||void 0===e?void 0:e.host)||Aa},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=La(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[ye]:this._storesIdentityInCookie?{r:Ha(e.r),u:e.u?Ha(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Pn([me,fe],t=>{const i=this.props[t];i&&Pn(i,function(t,i){e["$initial_"+lt(i)]=t})});const t=this.props[ye];if(t){const i=function(e,t=!1){const i=Da(e,t),s={};return Pn(i,function(e,t){s[`$initial_${lt(t)}`]=e}),s}(t,this._config.disable_capture_url_hashes);xn(e,i)}return e}safe_merge(e){return Pn(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,i){const s=e.persistence!==t.persistence,r=!((e,t)=>{if(e.length!==t.length)return!1;const i=[...e].sort(),s=[...t].sort();return i.every((e,t)=>e===s[t])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),n=s||r,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!i,l=!!this._disabled&&!a;a||this._syncCookieProperties(t,l),this._config=e,!a&&(s||r||o)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._syncCookieProperties(ls(ls({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),l));const c=n||o?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();const u=this._resolveSplitStorage(e),d=n||u!==this._splitStorage,h=!a&&(d||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(l);this._storageMigrationInProgress=d;try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),d){const e=this.props;this.clear(),this._storage=c,this._splitStorage=u,this.props=e,this.save()}else o&&(this._storage=c,a||(delete this._slotState[za],this._writeNow()))}finally{this._storageMigrationInProgress=!1,h&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){const e=this.props[ye];if(!this._storesIdentityInCookie||!gt(e)||"string"!=typeof e.r)return;const t=Ha(e.r),i="string"==typeof e.u?Ha(e.u):e.u;t===e.r&&i===e.u||this._setProp(ye,ls(ls({},e),{},{r:t,u:i}))}set_disabled(e){this._disabled=e,this._disabled?this.remove():this.save()}set_cross_subdomain(e){e!==this._cross_subdomain&&(this._cross_subdomain=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this._secure&&(this._secure=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){const i=this.props.__timers||{};i[e]=t,this._setProp(I,i),this.save()}remove_event_timer(e){const t=this.props.__timers||{},i=t[e];return ft(i)||(delete t[e],this._setProp(I,t),this.save()),i}get_property(e){return this.props[e]}set_property(e,t){this._setProp(e,t),this.save()}_setProp(e,t,i=!0){var s;const r=this.props[e];this.props[e]=t,i&&("distinct_id"!==e&&"$user_state"!==e||r===t||(this._localIdentityChangePending=!0),Ga(e)&&!Ka(r,t)&&this._metaIdentifierChangePending.add(e),this._markPendingCrossTabFeatureFlagChanges(e,r,t),(null===(s=ga(e))||void 0===s?void 0:s.volatile)||this._markGroupDirty(e))}_deleteProp(e,t=!0){delete this.props[e],t&&(Wa(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),Ga(e)&&this._metaIdentifierChangePending.add(e),this._markGroupDirty(e))}_markGroupDirty(e){var t;const i=null===(t=ga(e))||void 0===t?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}};const Za={GZipJS:"gzip-js",Base64:"base64"},Xa={Activation:"events",Cancellation:"cancelEvents"},el={Button:"button",Tab:"tab",Selector:"selector"},tl={TopLeft:"top_left",TopRight:"top_right",TopCenter:"top_center",MiddleLeft:"middle_left",MiddleRight:"middle_right",MiddleCenter:"middle_center",Left:"left",Center:"center",Right:"right",NextToTrigger:"next_to_trigger"},il={Top:"top",Left:"left",Right:"right",Bottom:"bottom"},sl={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},rl={Open:"open",MultipleChoice:"multiple_choice",SingleChoice:"single_choice",Rating:"rating",Link:"link"},nl={NextQuestion:"next_question",End:"end",ResponseBased:"response_based",SpecificQuestion:"specific_question"},ol={Once:"once",Recurring:"recurring",Always:"always"},al={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},ll={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},cl={Popover:"popover",Inline:"inline"};function ul(e){let t=!0;return{dispose(){if(t){t=!1;const i=e();i&&pt(i.then)&&i.then(void 0,()=>{})}}}}const dl={backgroundColor:"#ffffff",textColor:"#1d1f27",buttonColor:"#1d1f27",borderRadius:8,buttonBorderRadius:6,borderColor:"#e5e7eb",fontFamily:"system-ui",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",showOverlay:!0,whiteLabel:!1,dismissOnClickOutside:!0,zIndex:2147483646},hl={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},_l={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},pl=Cn("[RateLimiter]");var gl=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{const t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach(e=>{pl.info(`${e||"events"} is quota limited.`),this.serverLimits[e]=(new Date).getTime()+6e4})}catch(e){return void pl.warn(`could not rate limit - continuing. Error: "${null==e?void 0:e.message}"`,{text:t})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return(null===(e=this.instance.config.rate_limiting)||void 0===e?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null===(e=this.instance.config.rate_limiting)||void 0===e?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var t,i,s;const{captureEventsBurstLimit:r,captureEventsPerSecond:n}=this,o=(new Date).getTime(),a=null!==(t=null===(i=this.instance.persistence)||void 0===i?void 0:i.get_property("$capture_rate_limit"))&&void 0!==t?t:{tokens:r,last:o};a.tokens+=(o-a.last)/1e3*n,a.last=o,a.tokens>r&&(a.tokens=r);const l=1>a.tokens;if(l||e||(a.tokens=Math.max(0,a.tokens-1)),l&&!e){const e=(wt(a.dropped)?a.dropped:0)+1;a.dropped=e,!this.lastEventRateLimited&&this._captureWarning(e)&&(a.dropped=0)}return this.lastEventRateLimited=l,null===(s=this.instance.persistence)||void 0===s||s.set_property("$capture_rate_limit",a),{isRateLimited:l,remainingTokens:a.tokens}}_isPropertyAllowed(e){const t=this.instance.config.property_denylist;return!_t(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&(null==Ke?void 0:Ke.pathname))return`${null!==(e=Ke.origin)&&void 0!==e?e:""}${Ke.pathname}`}_captureWarning(e){var t,i;const{captureEventsBurstLimit:s,captureEventsPerSecond:r}=this,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null===(t=(i=this.instance).get_session_id)||void 0===t?void 0:t.call(i):void 0,a=[`${e} event(s) dropped since the last warning`,n?`triggered on ${n}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${r} events per second and ${s} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()<t}};const vl=Cn("[RemoteConfig]");var fl=class{constructor(e){this._instance=e}get remoteConfig(){var e;return null===(e=tt._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.config}_loadRemoteConfigJs(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.loadExternalDependency)?null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return vl.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void vl.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs(e=>{if(!e)return vl.info("No config found after loading remote JS config. Falling back to JSON."),void this._loadRemoteConfigJSON(e=>{this._onRemoteConfig(e.json,e)});this._onRemoteConfig(e)})}catch(e){vl.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||vl.warn("Failed to fetch remote config from PostHog."):vl.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){vl.error("Error applying remote config",e)}if(!1!==(null==e?void 0:e.hasFeatureFlags)&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var i;null===(i=this._instance.featureFlags)||void 0===i||i.ensureFlagsLoaded()}catch(e){vl.error("Error loading feature flags",e)}}};const ml=["fatal","error","warning","log","info","debug"];var yl=Uint8Array,bl=Uint16Array,Sl=Uint32Array,wl=new yl([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),El=new yl([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Cl=new yl([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),kl=function(e,t){for(var i=new bl(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var r=new Sl(i[30]);for(s=1;30>s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},Pl=kl(wl,2),xl=Pl[1];Pl[0][28]=258,xl[258]=28;for(var Fl=kl(El,0)[1],Il=new bl(32768),Tl=0;32768>Tl;++Tl){var Rl=(43690&Tl)>>>1|(21845&Tl)<<1;Il[Tl]=((65280&(Rl=(61680&(Rl=(52428&Rl)>>>2|(13107&Rl)<<2))>>>4|(3855&Rl)<<4))>>>8|(255&Rl)<<8)>>>1}var $l=function(e,t,i){for(var s=e.length,r=0,n=new bl(t);s>r;++r)++n[e[r]-1];var o,a=new bl(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new bl(1<<t);var l=15-t;for(r=0;s>r;++r)if(e[r])for(var c=r<<4|e[r],u=t-e[r],d=a[e[r]-1]++<<u,h=d|(1<<u)-1;h>=d;++d)o[Il[d]>>>l]=c}else for(o=new bl(s),r=0;s>r;++r)o[r]=Il[a[e[r]-1]++]>>>15-e[r];return o},Ml=new yl(288);for(Tl=0;144>Tl;++Tl)Ml[Tl]=8;for(Tl=144;256>Tl;++Tl)Ml[Tl]=9;for(Tl=256;280>Tl;++Tl)Ml[Tl]=7;for(Tl=280;288>Tl;++Tl)Ml[Tl]=8;var Al=new yl(32);for(Tl=0;32>Tl;++Tl)Al[Tl]=5;var Ol=$l(Ml,9,0),Ll=$l(Al,5,0),Dl=function(e){return(e/8|0)+(7&e&&1)},Nl=function(e,t,i){(null==t||0>t)&&(t=0),(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof bl?bl:e instanceof Sl?Sl:yl)(i-t);return s.set(e.subarray(t,i)),s},Bl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},ql=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},Ul=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new yl(0),0];if(1==r){var o=new yl(i[0].s+1);return o[i[0].s]=1,[o,1]}i.sort(function(e,t){return e.f-t.f}),i.push({s:-1,f:25001});var a=i[0],l=i[1],c=0,u=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=r-1;)a=i[i[d].f>i[c].f?c++:d++],l=i[c!=u&&i[d].f>i[c].f?c++:d++],i[u++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(s=1;r>s;++s)n[s].s>h&&(h=n[s].s);var _=new bl(h+1),p=Hl(i[u-1],_,0);if(p>t){s=0;var g=0,v=p-t,f=1<<v;for(n.sort(function(e,t){return _[t.s]-_[e.s]||e.f-t.f});r>s;++s){var m=n[s].s;if(t>=_[m])break;g+=f-(1<<p-_[m]),_[m]=t}for(g>>>=v;g>0;){var y=n[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=n[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new yl(_),p]},Hl=function(e,t,i){return-1==e.s?Math.max(Hl(e.l,t,i+1),Hl(e.r,t,i+1)):t[e.s]=i},zl=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new bl(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},jl=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},Wl=function(e,t,i){var s=i.length,r=Dl(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},Vl=function(e,t,i,s,r,n,o,a,l,c,u){Bl(t,u++,i),++r[256];for(var d=Ul(r,15),h=d[0],_=d[1],p=Ul(n,15),g=p[0],v=p[1],f=zl(h),m=f[0],y=f[1],b=zl(g),S=b[0],w=b[1],E=new bl(19),C=0;m.length>C;++C)E[31&m[C]]++;for(C=0;S.length>C;++C)E[31&S[C]]++;for(var k=Ul(E,7),P=k[0],x=k[1],F=19;F>4&&!P[Cl[F-1]];--F);var I,T,R,M,A=c+5<<3,O=jl(r,Ml)+jl(n,Al)+o,L=jl(r,h)+jl(n,g)+o+14+3*F+jl(E,P)+(2*E[16]+3*E[17]+7*E[18]);if(O>=A&&L>=A)return Wl(t,u,e.subarray(l,l+c));if(Bl(t,u,1+(O>L)),u+=2,O>L){I=$l(h,_,0),T=h,R=$l(g,v,0),M=g;var D=$l(P,x,0);for(Bl(t,u,y-257),Bl(t,u+5,w-1),Bl(t,u+10,F-4),u+=14,C=0;F>C;++C)Bl(t,u+3*C,P[Cl[C]]);u+=3*F;for(var N=[m,S],B=0;2>B;++B){var q=N[B];for(C=0;q.length>C;++C)Bl(t,u,D[U=31&q[C]]),u+=P[U],U>15&&(Bl(t,u,q[C]>>>5&127),u+=q[C]>>>12)}}else I=Ol,T=Ml,R=Ll,M=Al;for(C=0;a>C;++C)if(s[C]>255){var U;ql(t,u,I[257+(U=s[C]>>>18&31)]),u+=T[U+257],U>7&&(Bl(t,u,s[C]>>>23&31),u+=wl[U]);var H=31&s[C];ql(t,u,R[H]),u+=M[H],H>3&&(ql(t,u,s[C]>>>5&8191),u+=El[H])}else ql(t,u,I[s[C]]),u+=T[s[C]];return ql(t,u,I[256]),u+T[256]},Gl=new Sl([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Kl=new yl(0),Ql=function(){for(var e=new Sl(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),Jl=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function Yl(e,t){void 0===t&&(t={});var i=function(){var e=4294967295;return{p(t){for(var i=e,s=0;t.length>s;++s)i=Ql[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,c,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new yl(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),c=0;if(!t||8>o)for(var u=0;o>=u;u+=65535){var d=u+65535;o>d?c=Wl(l,c,e.subarray(u,d)):(l[u]=n,c=Wl(l,c,e.subarray(u,o)))}else{for(var h=Gl[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,v=new bl(32768),f=new bl(g+1),m=Math.ceil(i/3),y=2*m,b=function(t){return(e[t]^e[t+1]<<m^e[t+2]<<y)&g},S=new Sl(25e3),w=new bl(288),E=new bl(32),C=0,k=0,P=(u=0,0),x=0,F=0;o>u;++u){var I=b(u),T=32767&u,R=f[I];if(v[T]=R,f[I]=T,u>=x){var M=o-u;if((C>7e3||P>24576)&&M>423){c=Vl(e,l,0,S,w,E,k,P,F,u-F,c),P=C=k=0,F=u;for(var A=0;286>A;++A)w[A]=0;for(A=0;30>A;++A)E[A]=0}var O=2,L=0,D=p,N=T-R&32767;if(M>2&&I==b(u-N))for(var B=Math.min(_,M)-1,q=Math.min(32767,u),U=Math.min(258,M);q>=N&&--D&&T!=R;){if(e[u+O]==e[u+O-N]){for(var H=0;U>H&&e[u+H]==e[u+H-N];++H);if(H>O){if(O=H,L=N,H>B)break;var z=Math.min(N,H-2),j=0;for(A=0;z>A;++A){var W=u-N+A+32768&32767,V=W-v[W]+32768&32767;V>j&&(j=V,R=W)}}}N+=(T=R)-(R=v[T])+32768&32767}if(L){S[P++]=268435456|xl[O]<<18|Fl[L];var G=31&xl[O],K=31&Fl[L];k+=wl[G]+El[K],++w[257+G],++E[K],x=u+O,++C}else S[P++]=e[u],++w[e[u]]}}c=Vl(e,l,n,S,w,E,k,P,F,u-F,c),n||(c=Wl(l,c,Kl))}return Nl(a,0,s+Dl(c)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l,!c)),d=u.length;return function(e,t){var i=t.filename;if(e[0]=31,e[1]=139,e[2]=8,e[8]=2>t.level?4:9==t.level?2:0,e[9]=3,0!=t.mtime&&Jl(e,4,Math.floor(new Date(t.mtime||Date.now())/1e3)),i){e[3]=8;for(var s=0;i.length>=s;++s)e[s+10]=i.charCodeAt(s)}}(u,t),Jl(u,d-8,i.d()),Jl(u,d-4,s),u}const Zl=!!Je||!!Qe,Xl=new WeakMap,ec="text/plain";let tc=0,ic=!1;const sc=(e,t)=>{const[i,s]=e.split("#"),[r,n]=i.split("?");if(!n)return e;const o=n.split("&").filter(e=>e.split("=")[0]!==t).join("&");return`${r}${o?`?${o}`:""}${s?`#${s}`:""}`},rc=(e,t,i=!0)=>{var s;const[r,n]=e.split("?"),o=ls({},t),a=null!==(s=null==n?void 0:n.split("&").map(e=>{var t;const[s,r]=e.split("="),n=i&&null!==(t=o[s])&&void 0!==t?t:r;return delete o[s],`${s}=${n}`}))&&void 0!==s?s:[],l=function(e,t="&"){let i,s;const r=[];return Pn(e,function(e,t){ft(e)||ft(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)}),r.join(t)}(o);return l&&a.push(l),a.length>0?`${r}?${a.join("&")}`:r},nc=e=>{if(e._encodedBody)return e._encodedBody;const{data:t,compression:i}=e;if(!t)return;if(i===Za.GZipJS){const e=Yl(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new yl(e.length+(e.length>>>1)),s=0,r=function(e){i[s++]=e},n=0;t>n;++n){if(s+5>i.length){var o=new yl(s+8+(t-n<<1));o.set(i),i=o}var a=e.charCodeAt(n);128>a?r(a):2048>a?(r(192|a>>>6),r(128|63&a)):a>55295&&57344>a?(r(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++n))>>>18),r(128|a>>>12&63),r(128|a>>>6&63),r(128|63&a)):(r(224|a>>>12),r(128|a>>>6&63),r(128|63&a))}return Nl(i,0,s)}(ba(t)),{mtime:0});return{contentType:ec,body:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),estimatedSize:e.byteLength}}if(i===Za.Base64){const e=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))):e}(ba(t)),i=(e=>"data="+encodeURIComponent("string"==typeof e?e:ba(e)))(e);return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const s=ba(t);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}},oc=e=>{const t=()=>"sendBeacon"===e.transport?{url:rc(e.url,{compression:Za.Base64}),encodedBody:nc(ls(ls({},e),{},{compression:Za.Base64,_encodedBody:void 0}))}:{url:sc(e.url,"compression"),encodedBody:nc(ls(ls({},e),{},{compression:void 0,_encodedBody:void 0}))};let i;try{i=nc(e)}catch(i){if(or(e.compression,wa(e.url,"compression")))return En.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return i&&or(e.compression,wa(e.url,"compression"))&&!((s=i.body)instanceof ArrayBuffer?nr(new Uint8Array(s)):ArrayBuffer.isView(s)&&nr(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(ic=!0,t()):{url:e.url,encodedBody:i};var s},ac=e=>{try{return oc(e)}catch(i){var t;return En.error(i),void(null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0,error:i}))}},lc=function(){var e=Lt(function*(e){const t=yield function(e){return hr.apply(this,arguments)}(ba(e.data),i.DEBUG,{rethrow:!0});if(!t)return e;const s=yield t.arrayBuffer();return ls(ls({},e),{},{_encodedBody:{contentType:ec,body:s,estimatedSize:s.byteLength}})});return function(t){return e.apply(this,arguments)}}(),cc=/Failed to fetch|NetworkError|Load failed/i,uc=e=>"TypeError"===(null==e?void 0:e.name)&&cc.test((null==e?void 0:e.message)||""),dc=e=>{try{const t=function(e,t=Date.now()){if("string"!=typeof e||!e)return;const i=e.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){const e=1e3*Math.min(Number(s),300);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;const r=/^\w{3} \w{3} /.test(s)?s+" GMT":s,n=Date.parse(r)-t;return Number.isFinite(n)&&n>0?Math.min(n,Qi):void 0}(e());return ft(t)?void 0:Math.min(t,3e4)}catch(e){return}},hc=e=>{const t=ac(e);if(!t)return;const i=new Je;Xl.set(i,!0);const{url:s,encodedBody:r}=t;i.open(e.method||"GET",s,!0);const{contentType:n,body:o}=null!=r?r:{};Pn(e.headers,function(e,t){i.setRequestHeader(t,e)}),n&&i.setRequestHeader("Content-Type",n),e.timeout&&(i.timeout=e.timeout),i.onreadystatechange=()=>{if(4===i.readyState){var t;const s={statusCode:i.status,text:i.responseText};if(200===i.status)try{s.json=JSON.parse(i.responseText)}catch(e){}null===(t=e.callback)||void 0===t||t.call(e,s,dc(()=>i.getResponseHeader("Retry-After")))}},i.send(o)},_c=e=>{const t=ac(e);if(!t)return;const{url:i,encodedBody:s}=t,{contentType:r,body:n,estimatedSize:o}=null!=s?s:{},a=new Headers;Pn(e.headers,function(e,t){a.append(t,e)}),r&&a.append("Content-Type",r);let l=null,c=!1;if(Ye){const t=new Ye;l={signal:t.signal,timeout:setTimeout(()=>{c=!0;try{t.abort(Xi("AbortError","PostHog request timed out"+((i=e.timeout)?` after ${i}ms`:"")))}catch(e){d(e)}var i},e.timeout)}}let u=!1;const d=t=>{var i;u||(u=!0,c&&"AbortError"===(null==t?void 0:t.name)||uc(t)?En.warn(t):En.error(t),null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))};let h=0;const _=()=>{tc-=h,h=0,l&&clearTimeout(l.timeout)};try{const t=ls({method:(null==e?void 0:e.method)||"GET",headers:a,referrerPolicy:"strict-origin",body:n,signal:null==l?void 0:l.signal},e.fetchOptions),s=null!=o?o:ft(n)?0:void 0;t.keepalive="POST"===t.method&&!e._keepaliveDisabled&&!1!==t.keepalive&&t.body===n&&!ft(s)&&s>=0&&52428.8>tc+s,t.keepalive&&(h=s,tc+=h),Qe(i,t).then(t=>t.text().then(i=>{var s;if(u)return;const r={statusCode:t.status,text:i};if(200===t.status)try{r.json=JSON.parse(i)}catch(e){En.error(e)}u=!0,_(),null===(s=e.callback)||void 0===s||s.call(e,r,dc(()=>t.headers.get("Retry-After")))})).catch(e=>{_(),d(e)}).finally(_)}catch(e){_(),d(e)}},pc=e=>{try{var t;const{url:i,encodedBody:s}=oc(e),{contentType:r,body:n,estimatedSize:o}=null!=s?s:{};if(!n)return;const a=n instanceof Blob?n:new Blob([n],{type:r});if(Ve.sendBeacon(i,a))return;const l=_t(e.data)?e.data:null===(t=e.data)||void 0===t?void 0:t.batch;if(_t(l)&&l.length>1&&(null!=o?o:0)>16384){const t=Math.ceil(l.length/2),i=t=>_t(e.data)?t:ls(ls({},e.data),{},{batch:t});return pc(ls(ls({},e),{},{data:i(l.slice(0,t))})),void pc(ls(ls({},e),{},{data:i(l.slice(t))}))}En.warn(`Beacon of ~${null!=o?o:0} bytes was rejected by the browser, falling back to ${Qe?"fetch":"XHR"}`),Qe?_c(ls(ls({},e),{},{_keepaliveDisabled:!0})):hc(e)}catch(e){En.warn("Beacon send failed",e)}},gc=(e,t,i,s)=>{const r="query"===s?"POST"===t?"sent_at":"_":void 0;return rc(i===Za.GZipJS?sc(e,"compression"):e,ls(ls({},r?{[r]:Date.now().toString()}:{}),i===Za.GZipJS?{}:{compression:i}))},vc=(()=>{const e=[];return Qe&&e.push({transport:"fetch",method:_c}),Je&&e.push({transport:"XHR",method:hc}),(null==Ve?void 0:Ve.sendBeacon)&&e.push({transport:"sendBeacon",method:pc}),e})();let fc=!Zl&&-1===(null==Xe?void 0:Xe.indexOf("MSIE"))&&-1===(null==Xe?void 0:Xe.indexOf("Mozilla"));function mc(e,t,i){var s,r,n;i&&(t=ls(ls({},t),{},{callback:e=>i(e)})),e.__loaded?fc?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&(null===(r=t.callback)||void 0===r||r.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=ls(ls({},e.config.request_headers),t.headers),t.compression="best-available"===t.compression?null!==(s=e.compression)&&void 0!==s?s:t.compressionFallback:t.compression,(ft(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((e,t)=>{var i,s,r;const n=ls(ls({},e),{},{callback:null!=t?t:t=>{var i;return null===(i=e.callback)||void 0===i?void 0:i.call(e,t)}});n.timeout=n.timeout||6e4;const o=null!==(i=n.transport)&&void 0!==i?i:"fetch";"sendBeacon"===o&&ft(n.compression)&&n.data&&(n.compression=Za.Base64),"POST"===n.method&&n.data&&("capture-body"===n.timestampMode?n.data=(e=>{var t,i;const s=(_t(e)?e:[e]).map(e=>ls(ls({},e),e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{})),r=s[0];return{api_key:null!==(t=null==r||null===(i=r.properties)||void 0===i?void 0:i.token)&&void 0!==t?t:null==r?void 0:r.token,batch:s,sent_at:(new Date).toISOString()}})(n.data):"body"===n.timestampMode&&(n.data=((e,t=(new Date).toISOString())=>_t(e)?e.map(e=>ls(ls({},e),{},{sent_at:t})):ls(ls({},e),{},{sent_at:t}))(n.data))),n.url=gc(n.url,n.method,n.compression,n.timestampMode);const a=vc.filter(e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport)),l=null!==(s=null===(r=function(e,t){for(let i=0;e.length>i;i++)if(t(e[i]))return e[i]}(a,e=>e.transport===o))||void 0===r?void 0:r.method)&&void 0!==s?s:a[0].method;if(!l)throw new Error("No available transport method");const c=e=>{try{l(e)}catch(e){var t;uc(e)?En.warn(e):En.error(e),null===(t=n.callback)||void 0===t||t.call(n,{statusCode:0,error:e})}};"sendBeacon"!==o&&!n.preferSyncCompression&&n.data&&n.compression===Za.GZipJS&&Ze&&"undefined"!=typeof Promise&&!ic?lc(n).then(e=>{c(e)}).catch(t=>{if(ar(t))return ic=!0,void c(ls(ls({},n),{},{compression:void 0,url:gc(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;const t="name"in e?String(e.name):"";return ar(e)||t===rr})(t)&&(ic=!0),c(n)}):c(n)})(t,(s,r)=>{var n,o,a;e.rateLimiter.checkForLimiting(s),400>s.statusCode||null===(n=(o=e.config).on_request_error)||void 0===n||n.call(o,s),i?i(s,r):null===(a=t.callback)||void 0===a||a.call(t,s)})):t.fireCallbackOnDrop&&(null===(n=t.callback)||void 0===n||n.call(t,{statusCode:0}))}var yc=class{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=qt((null==t?void 0:t.flush_interval_ms)||3e3,250,5e3,En.createLogger("flush interval"),3e3),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();const e=this._queue.length>0?this._formatQueue():{},t=Object.values(e);[...t.filter(e=>0===e.url.indexOf("/e")),...t.filter(e=>0!==e.url.indexOf("/e"))].map(e=>{this._sendRequestSafely(ls(ls({},e),{},{callback:void 0}),"sendBeacon")})}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){this._isPaused||(this._flushTimeout=setTimeout(()=>{this._clearFlushTimeout(),this._flush()},this._flushTimeoutMs))}_flush(){if(this._queue.length>0){const e=this._formatQueue();for(const t in e)this._sendRequestSafely(e[t])}}_sendRequestSafely(e,t){try{this._sendRequest(e,t)}catch(e){En.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){const e={},t={};Pn(this._queue,i=>{var s;const r=i,n=((r?r.batchKey:null)||r.url)+(r.batchGroup?`:${r.batchGroup}`:"");ft(e[n])&&(e[n]=ls(ls({},r),{},{data:[],callback:void 0,fireCallbackOnDrop:void 0}),t[n]=[]),null===(s=e[n].data)||void 0===s||s.push(r.data),r.callback&&t[n].push(r.callback)});for(const i in t){const s=t[i];s.length&&(e[i].callback=e=>{for(const t of s)t(e)})}return this._queue=[],e}};const bc=["retriesPerformedSoFar"];var Sc=class{constructor(e){this._instance=e,this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._queue=[],this._areWeOnline=!0,this.resume()}resume(){if(!ft(je)&&"onLine"in je.navigator){if(this._areWeOnline=je.navigator.onLine,this._onlineListener)return;this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},An(je,"online",this._onlineListener),An(je,"offline",this._offlineListener)}}get length(){return this._queue.length}retriableRequest(e,t){let{retriesPerformedSoFar:i}=e,s=_r(e,bc);Et(i)&&(s.url=rc(s.url,{retry_count:i})),mc(this._instance,t?ls(ls({},s),{},{transport:t}):s,(e,t)=>{var r;if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=i?i:0))return void this._enqueue(ls({retriesPerformedSoFar:i},s),t);0===e.statusCode&&En.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${null!=i?i:0} retries.`)}null===(r=s.callback)||void 0===r||r.call(s,e)})}_enqueue(e,t){const i=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=i+1;const s=Math.max(function(e){const t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=(Math.random()-.5)*(s-i);return Math.ceil(s+r)}(i),null!=t?t:0),r=Date.now()+s;this._queue.push({retryAt:r,requestOptions:e});let n=`Enqueued failed request for retry in ${s}`;navigator.onLine||(n+=" (Browser is offline)"),En.warn(n),this._isPolling||(this._isPolling=!0,this._poll())}_poll(){if(this._poller&&clearTimeout(this._poller),0===this._queue.length)return this._isPolling=!1,void(this._poller=void 0);this._poller=setTimeout(()=>{this._areWeOnline&&this._queue.length>0&&this._flush(),this._poll()},this._pollIntervalMs)}_flush(){const e=Date.now(),t=[],i=this._queue.filter(i=>e>i.retryAt||(t.push(i),!1));if(this._queue=t,i.length>0)for(const{requestOptions:e}of i)this.retriableRequest(e)}unload(){this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,ft(je)||(this._onlineListener&&(je.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(je.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0));for(const{requestOptions:e}of this._queue)try{this._instance._send_request(ls(ls({},e),{},{callback:_t(e.data)?void 0:e.callback,transport:"sendBeacon"}))}catch(e){En.error(e)}this._queue=[]}},wc=class{constructor(e){this._instance=e,this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});const r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)}}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){const e=this._context;return this._context=void 0,setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){An(je,"scroll",this._updateScrollData,{capture:!0}),An(je,"scrollend",this._updateScrollData,{capture:!0}),An(je,"resize",this._updateScrollData)}scrollElement(){if(this._scrollRoot){const t=_t(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(const i of t){var e;const t=null==je||null===(e=je.document)||void 0===e?void 0:e.querySelector(i);if(t)return t}return}var t;return null==je||null===(t=je.document)||void 0===t?void 0:t.documentElement}_scrollPosition(e){var t,i;const s="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){const e=this.scrollElement();return e&&e[s]||0}return je?"y"===e?je.scrollY||je.pageYOffset||(null===(t=je.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.scrollTop)||0:je.scrollX||je.pageXOffset||(null===(i=je.document)||void 0===i||null===(i=i.documentElement)||void 0===i?void 0:i.scrollLeft)||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}};const Ec=e=>La(null==e?void 0:e.config.mask_personal_data_properties,null==e?void 0:e.config.custom_personal_data_properties,null==e?void 0:e.config.disable_capture_url_hashes);var Cc=class{constructor(e,t,i,s){this._onSessionIdCallback=e=>{const t=this._getStored();if(t&&t.sessionId===e)return;const i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[ge]:i})},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Ec,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[ge]}getSetOnceProps(){var e;const t=null===(e=this._getStored())||void 0===e?void 0:e.props;return t?"r"in t?Da(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return Pn(Tn(this.getSetOnceProps()),(t,i)=>{"$current_url"===i&&(i="url"),e[`$session_entry_${lt(i)}`]=t}),e}},kc=class{on(e,t){return this._events[e]||(this._events[e]=[]),this._events[e].push(t),()=>{this._events[e]=this._events[e].filter(e=>e!==t)}}emit(e,t){for(const i of this._events[e]||[])i(t);for(const i of this._events["*"]||[])i(e,t)}constructor(){this._events={}}};const Pc=Cn("[SessionId]"),xc=864e5;var Fc=class{on(e,t){return this._eventEmitter.on(e,t)}constructor(e,t,i){var s;if(this._lastPersistedActivityTimestamp=null,this._lastCookieSyncTimestamp=null,this._sessionIdChangedHandlers=[],this._beforeUnloadListener=void 0,this._destroyed=!1,this._eventEmitter=new kc,this._sessionHasBeenIdleTooLong=(e,t)=>!(!Et(e)||!Et(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if("always"===e.config.cookieless_mode)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this._config=e.config,this._persistence=e.persistence,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._pendingBootstrapSession=void 0,this._sessionActivityTimestamp=null,this._sessionIdGenerator=t||Hn,this._windowIdGenerator=i||Hn;const r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*qt(this._config.session_idle_timeout_seconds||1800,60,36e3,Pc.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){const e=co._parse(this._window_id_storage_key),t=co._parse(this._primary_window_exists_storage_key);e&&!t?this._windowId=e:co._remove(this._window_id_storage_key),co._set(this._primary_window_exists_storage_key,!0)}(null===(s=this._config.bootstrap)||void 0===s?void 0:s.sessionID)&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return ft(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),()=>{this._sessionIdChangedHandlers=this._sessionIdChangedHandlers.filter(t=>t!==e)}}_canUseSessionStorage(){return"memory"!==this._config.persistence&&!this._persistence._disabled&&co._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&co._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?co._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){const t=this._lastPersistedActivityTimestamp;return!bt(t)&&!bt(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){const s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[K]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e;const t=null===(e=this._config)||void 0===e?void 0:e.persistence_save_debounce_ms;return Et(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(K):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(bt(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this._lastPersistedActivityTimestamp)return;this._refreshSessionIdFromStorage();const[,t,i]=this._getSessionId();t===this._sessionId&&i===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[K]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}_freshestActivityTimestamp(){const[e]=this._getSessionId(),t=Et(e)?e:0,i=Et(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){const e=this._persistence.props[K];return _t(e)&&2===e.length&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this._lastPersistedActivityTimestamp=null,this._pendingBootstrapSession=void 0,clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._setSessionId(null,null,null)}setBootstrapSessionId(e,t=!1){const i=((e,t=(new Date).getTime())=>{try{const i=(e=>{const t=e.replace(/-/g,"");if(32!==t.length)throw new Error("Not a valid UUID");if("7"!==t[12])throw new Error("Not a UUIDv7");return parseInt(t.substring(0,12),16)})(e);return i>t+6e4?void Pc.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void Pc.error("Invalid sessionID in bootstrap",e)}})(e);return!ft(i)&&(t?this._pendingBootstrapSession={sessionId:e,sessionStartTimestamp:i}:this._setSessionId(e,(new Date).getTime(),i),!0)}destroy(){this._destroyed=!0,this._flushPendingActivityTimestamp(),clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=void 0,this._beforeUnloadListener&&je&&(je.removeEventListener(Be,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&co._remove(this._primary_window_exists_storage_key)},An(je,Be,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,t=null,i=!1){if("always"===this._config.cookieless_mode)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(bt(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null===(n=(o=this._persistence).syncCookieProperties)||void 0===n||n.call(o),this._lastCookieSyncTimestamp=s}let[,a,l]=this._getSessionId();const c=!ft(r)&&a!==r,u=this._freshestActivityTimestamp();let d=this._getWindowId();const h=this._pendingBootstrapSession,_=!!h&&(h.sessionStartTimestamp>s+6e4||s-h.sessionStartTimestamp>xc),p=h?_:Et(l)&&Math.abs(s-l)>xc;let g=!1,v=c,f=!a||!!h;const m=a;let y=!f&&!e&&this._sessionHasBeenIdleTooLong(s,u);if(y&&(y=this._isSessionIdleAfterCrossTabRefresh(s),y||Pc.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,l]=this._getSessionId(),y||(f=!a||!!h)),f||y||p){v=!1;const e=h&&!_;a=e?h.sessionId:this._sessionIdGenerator(),d=this._windowIdGenerator(),Pc.info("new session ID assigned",{sessionId:a,windowId:d,bootstrapped:!!e,changeReason:{noSessionId:f,activityTimeout:y,sessionPastMaximumLength:p}}),l=e?h.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,g=!0}else d||(d=this._windowIdGenerator(),g=!0),v=v||a!==m,v&&(Pc.info("adopted cross-tab session id",{sessionId:a,windowId:d}),g=!0);const b=Et(u)&&e&&!p?u:s,S=Et(l)?l:(new Date).getTime();this._setWindowId(d),this._setSessionId(a,b,S),e||this._resetIdleTimer();const w={noSessionId:f,activityTimeout:y,sessionPastMaximumLength:p,crossTabAdoption:v};return g&&this._sessionIdChangedHandlers.forEach(e=>e(a,d,w)),{sessionId:a,windowId:d,sessionStartTimestamp:S,changeReason:g?w:void 0,lastActivityTimestamp:u}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout(()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){const e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()},1.1*this.sessionTimeoutMs))}};const Ic=function(e,t){if(!e)return!1;const i=e.userAgent;if(i&&Bt(i,t))return!0;try{const i=null==e?void 0:e.userAgentData;if((null==i?void 0:i.brands)&&i.brands.some(e=>Bt(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver};function Tc(){return(Tc=Lt(function*(){const e=null==Ve?void 0:Ve.userAgentData;if(null==e?void 0:e.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return mt(i)&&i.length>0?i:void 0}catch(e){return void En.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function Rc(e,t){let i=`$survey_${t}/${e.id}`;return e.current_iteration&&e.current_iteration>0&&(i=`$survey_${t}/${e.id}/${e.current_iteration}`),i}function $c(e){var t;return!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length)}const Mc=(e,t)=>{if(!(e=>{try{new RegExp(e)}catch(e){return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch(e){return!1}},Ac=e=>e.toLowerCase(),Oc={exact:(e,t)=>t.some(t=>e.some(e=>t===e)),is_not:(e,t)=>t.every(t=>e.every(e=>t!==e)),regex:(e,t)=>t.some(t=>e.some(e=>Mc(t,e))),not_regex:(e,t)=>t.every(t=>e.every(e=>!Mc(t,e))),icontains:(e,t)=>t.map(Ac).some(t=>e.map(Ac).some(e=>t.includes(e))),not_icontains:(e,t)=>t.map(Ac).every(t=>e.map(Ac).every(e=>!t.includes(e))),gt:(e,t)=>t.some(t=>{const i=parseFloat(t);return!isNaN(i)&&e.some(e=>i>parseFloat(e))}),lt:(e,t)=>t.some(t=>{const i=parseFloat(t);return!isNaN(i)&&e.some(e=>i<parseFloat(e))})};function Lc(e,t){return!e||Object.entries(e).every(([e,i])=>{const s=null==t?void 0:t[e];if(null==s)return!1;const r=Oc[i.operator];return!!r&&r(i.values.map(String),[String(s)])})}function Dc(e,t,i){return ba({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}const Nc="custom",Bc="i.posthog.com",qc=/^\/static\//,Uc=["/s/","/e/","/i/"];var Hc=class{constructor(e){this._regionCache={},this.instance=e}get apiHost(){const e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){const e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e;let t=null===(e=this.instance.config.ui_host)||void 0===e?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace(`.${Bc}`,".posthog.com")),"https://app.posthog.com"===t?"https://us.posthog.com":t}get region(){return this._regionCache[this.apiHost]||(this._regionCache[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":Nc),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(!qc.test(e))return;const t=this.instance.config.asset_host;return"string"==typeof t&&t.trim().replace(/\/$/,"")||void 0}_urlKey(e){const t=Sa(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;let s=i;const r=this.instance.config.rewriteRequestPath;if(r){var n;const e=(null===(n=Sa(i))||void 0===n?void 0:n.href)||i;s=r(new URL(e)).toString()}if(r&&"api"===e&&Uc.some(e=>0===t.indexOf(e))){const e=this._urlKey(s);if(e){const t=this.apiHost;let i=this._ingestionEndpoints;(null==i?void 0:i.apiHost)===t&&i.rewriteRequestPath===r||(i={apiHost:t,rewriteRequestPath:r,urls:new Set},this._ingestionEndpoints=i),i.urls.add(e)}}return s}isIngestionEndpoint(e){const t=this._ingestionEndpoints,i=this._urlKey(e);return(null==t?void 0:t.apiHost)===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!i&&t.urls.has(i)}endpointFor(e,t=""){if(t&&(t="/"===t[0]?t:`/${t}`),"ui"===e)return this._prepareEndpoint(e,t,this.uiHost+t);if("flags"===e)return this._prepareEndpoint(e,t,this.flagsApiHost+t);if("assets"===e){const i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,`${i}${t}`)}if(this.region===Nc)return this._prepareEndpoint(e,t,this.apiHost+t);const i=Bc+t;switch(e){case"assets":return this._prepareEndpoint(e,t,`https://${this.region}-assets.${i}`);case"api":return this._prepareEndpoint(e,t,`https://${this.region}.${i}`)}}};const zc=Cn("[Surveys]"),jc=e=>{try{const t=(e=>((e,t)=>`seenSurvey_${function(e){return e.current_iteration&&e.current_iteration>0?`${e.id}_${e.current_iteration}`:e.id}(t)}`)(0,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){zc.error("Failed to persist survey seen state",e)}},Wc=[sl.Popover,sl.Widget,sl.API],Vc={ignoreConditions:!1,ignoreDelay:!1,displayType:cl.Popover},Gc=Cn("[PostHog ExternalIntegrations]"),Kc={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var Qc=class{constructor(e){this._instance=e}_loadScript(e,t){var i,s;null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,e,e=>{if(e)return Gc.error("failed to load script",e);t()})}startIfEnabledOrStop(){var e;for(const[r,n]of Object.entries(null!==(e=this._instance.config.integrations)&&void 0!==e?e:{})){var t,i,s;n&&!(null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.integrations)||void 0===t?void 0:t[r])&&this._loadScript(Kc[r],()=>{var e;null===(e=tt.__PosthogExtensions__)||void 0===e||null===(e=e.integrations)||void 0===e||null===(e=e[r])||void 0===e||e.start(this._instance)}),!n&&(null===(i=tt.__PosthogExtensions__)||void 0===i||null===(i=i.integrations)||void 0===i?void 0:i[r])&&(null===(s=tt.__PosthogExtensions__)||void 0===s||null===(s=s.integrations)||void 0===s||null===(s=s[r])||void 0===s||s.stop())}}};const Jc="autocapture",Yc="featureFlags",Zc="logs",Xc="surveys";var eu=class{constructor(e){this._instance=e}initialize(){}get(e){const t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);const i={};for(const s of e){const e=null==t?void 0:t.get_property(s);ft(e)||(i[s]=e)}return i}set(e,t){var i;null===(i=this._instance.persistence)||void 0===i||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null===(t=this._instance.persistence)||void 0===t||t.unregister(e)}},tu=class{constructor(e){this.instance=e,this._logger=En,this.kv=new eu(e),this.onEvent=e=>ul(this.instance._addCaptureHook((t,i)=>{if(i)try{e({event:t,properties:i.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}})),this.onRemoteConfig=e=>{const t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on("extensionsRemoteConfig",t);return this.instance._lastRemoteConfig&&t(this.instance._lastRemoteConfig),ul(i)}}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property("$device_id"))&&void 0!==e?e:this.distinctId}get deviceId(){const e=this.instance.get_property(S);return"string"==typeof e?e:void 0}get library(){return{name:i.LIB_NAME,version:i.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null===(t=this.instance.persistence)||void 0===t?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r;const n=null===(e=this.instance.sessionManager)||void 0===e?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==n?void 0:n.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==n?void 0:n.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==n?void 0:n.sessionStartTimestamp)&&void 0!==s?s:0,lastActivityTimestamp:null!==(r=null==n?void 0:n.lastActivityTimestamp)&&void 0!==r?r:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return pt(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get projectToken(){return this.instance.config.token}getExtension(e){let t;switch(e){case Yc:case"featureFlagsCommon":t=this.instance.featureFlags;break;case Zc:t=this.instance.logs;break;case Xc:t=this.instance.surveys;break;case Jc:t=this.instance.autocapture}return t}capture(e,t,i){i?this.instance.capture(e,t,{timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce}):this.instance.capture(e,t)}registerDynamicEventProperties(e){return ul(this.instance._registerExtensionEventProperties(e))}sendRequest(e){var t=this;return Lt(function*(e,i={}){var s;const r=null!==(s=i.target)&&void 0!==s?s:"api",n=t.instance.requestRouter.endpointFor(r,e),o="api"===r&&"/i/v1/logs"===e,a={method:i.method,url:i.query?rc(n,i.query):n,data:i.body,headers:i.headers,timeout:i.timeoutMs,fireCallbackOnDrop:!0,transport:i.transport,compression:i.compression,compressionFallback:"flags"===i.target&&"best-available"===i.compression?st.Base64:void 0,timestampMode:i.sentAt};return o&&(a.batchKey="logs"),"sendBeacon"===i.transport?(t.instance._send_request(a),{statusCode:202}):new Promise(e=>{a.callback=e,t.instance._send_request(a)})}).apply(this,arguments)}};const iu={};let su=0;const ru=()=>{},nu='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',ou="Surveys module not available",au="sanitize_properties is deprecated. Use before_send instead",lu="Invalid value for property_denylist config: ",cu=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],uu=["$feature_flag_called","$$heatmap","$snapshot"],du=e=>"$"===e.charAt(0)&&!ot(uu,e),hu=/^[A-Za-z0-9_-]{1,400}$/,_u=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,pu=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,gu=["token","distinct_id",we],vu="posthog",fu=e=>{const t={};return e&&"unset"!==e?("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0),t):t},mu=e=>{var t;return ls({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Mn(null==Ge?void 0:Ge.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ru,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:null!=e?e:"unset",__preview_deferred_init_extensions:!1,__preview_replay_sync_fetch:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:Ke&&mt(null==Ke?void 0:Ke.search)&&-1!==Ke.search.indexOf("__posthog_debug=true")||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:"https:"===(null==je||null===(t=je.location)||void 0===t?void 0:t.protocol),ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(e){En.error("Bad HTTP status: "+e.statusCode+" "+e.text)},get_device_id:e=>e,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Ne,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:ru},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:To,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:fu(e),external_scripts_inject_target:e&&e>="2026-01-30"?"head":"body",internal_or_test_user_hostname:e&&e>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:e&&e>="2026-05-30"?250:0,split_storage:!(!e||"2026-05-30">e),detect_google_search_app:!(!e||"2026-05-30">e),disable_capture_url_hashes:!(!e||"2026-06-25">e),cookieWinsOnConflict:!(!e||"unset"===e||"2026-08-29">e)}))(e))},yu=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],bu=e=>{const t={};for(const[i,s]of yu)ft(e[i])||(t[s]=e[i]);const i=xn({},t,e),s=e.__preview_external_dependency_versioned_paths;return ft(s)||(ft(e.strict_script_versioning)&&(i.strict_script_versioning=!!s),mt(s)&&ft(e.asset_host)&&(i.asset_host=s)),_t(e.property_blacklist)&&(ft(e.property_denylist)?i.property_denylist=e.property_blacklist:_t(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:En.error(lu+e.property_denylist)),i};var Su=class{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){En.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},wu=class e{_removeExtension(e){if(!e)return;const t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}_replaceExtension(e,t){var i;return this._removeExtension(e),this._extensions.push(t),null===(i=t.initialize)||void 0===i||i.call(t),t}_inCookielessMode(){return"always"===this.config.cookieless_mode||"on_reject"===this.config.cookieless_mode&&this.consent.isRejected()}_warnIfVolatileIdentityWithoutStableId(){if(this._hasWarnedAboutVolatileIdentity)return;if(this.config.reuseAnonymousId)return;if(this.config.segment)return;if(this._inCookielessMode())return;const e="memory"===this.config.persistence||"sessionStorage"===this.config.persistence;if(!e&&!this.config.disable_persistence)return;if(this._hasStableInitialDistinctId)return;let t,i,s;e?(t=`persistence is set to '${this.config.persistence}'`,i="memory"===this.config.persistence?"on every page load":"for every new browser tab or window",s="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(t="persistence is disabled (disable_persistence is true)",i="on every page load",s="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this._hasWarnedAboutVolatileIdentity=!0,console.warn("[PostHog.js]",`${t} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${i}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${s}`)}_syncCookielessIdentity(){const e=this.persistence;if(!e||this._isConsentTransition)return;if(this._inCookielessMode())return void("on_reject"===this.config.cookieless_mode&&"$posthog_cookieless"!==this.get_distinct_id()&&(this._sync_opt_out_with_persistence(),this._enterCookielessMode()));if("$posthog_cookieless"!==this.get_distinct_id())return;this._is_persistence_disabled()||e.load(!0);const t=this.get_distinct_id();if(!t||"$posthog_cookieless"===t){const t=this.config.get_device_id(Hn());this.register({distinct_id:t,$device_id:t}),e.set_property(pe,Le)}this._sync_opt_out_with_persistence()}get decideEndpointWasHit(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var t;this._isPageUnloading=!1,this._isShutdown=!1,this.webPerformance=new Su,this._personProcessingSetOncePropertiesSent=!1,this.version=i.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new kc,this._extensions=[],this._extensionEventPropertyProducers=[],this._replayDebugPropertiesPaused=!1,this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._isConsentTransition=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=mu(),this.SentryIntegration=ua,this.sentryIntegration=e=>function(e,t){const i=ca(e,t);return{name:la,processEvent:e=>i(e)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this._initialPageviewCaptured=!1,this._visibilityStateListener=null,this._initialPersonProfilesConfig=null,this._cachedPersonProperties=null,this.scrollManager=new wc(this),this.pageViewManager=new da(this),this.rateLimiter=new gl(this),this.requestRouter=new Hc(this),this.consent=new uo(this),this.externalIntegrations=new Qc(this);const s=null!==(t=e.__defaultExtensionClasses)&&void 0!==t?t:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(e,t,i)=>{const s=mt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{const s=mt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",e=>En.info(`send "${null==e?void 0:e.event}"`,e))}init(t,i,s){if(s&&s!==vu){var r;const n=null!==(r=iu[s])&&void 0!==r?r:new e;return n._init(t,i,s),iu[s]=n,iu[vu][s]=n,n}return this._init(t,i,s)}_init(e,t={},s){var r,n,o;const a=mt(e)?e.trim():"";if(!a)return En.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var l;if(this.__loaded)return a!==(null===(l=this.config)||void 0===l?void 0:l.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=mu(t.defaults),t.debug=this._checkLocalStorageForDebug(t.debug),this._originalUserConfig=t,this._triggered_notifs=[],t.person_profiles?this._initialPersonProfilesConfig=t.person_profiles:t.process_person&&(this._initialPersonProfilesConfig=t.process_person);const c=mu(t.defaults),u=bu(t),d=xn({},c,u,{name:s,token:a});gt(c.rageclick)&>(u.rageclick)&&(d.rageclick=xn({},c.rageclick,u.rageclick)),gt(c.session_recording)&>(u.session_recording)&&(d.session_recording=xn({},c.session_recording,u.session_recording)),this.set_config(d),this.config.on_xhr_error&&En.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:Za.GZipJS;const h=this._is_persistence_disabled(),_=!this._inCookielessMode();if(this.persistence=new Ya(this.config,h,!0,_),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Ya(ls(ls({},this.config),{},{persistence:"sessionStorage"}),h,!1,_),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!h&&co._is_supported()){const e=co._parse(this._sessionRegisteredPropertiesStorageKey);_t(e)&&e.forEach(e=>{mt(e)&&this._sessionRegisteredPropKeys.add(e)})}else co._remove(this._sessionRegisteredPropertiesStorageKey);const p=ls({},this.persistence.props),g=ls({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new yc((e,t)=>this._send_retriable_request(e,t),this.config.request_queue_config),this._retryQueue=new Sc(this),this.__request_queue=[];const v=this._inCookielessMode();v||(this.sessionManager=new Fc(this),this.sessionPropsManager=new Cc(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((e,t,i)=>{((null==i?void 0:i.activityTimeout)||(null==i?void 0:i.sessionPastMaximumLength)||(null==i?void 0:i.crossTabAdoption))&&this._clearSessionRegisteredProps()})),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(En.info("Deferring extension initialization to improve startup performance"),this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._initExtensions(v)},0)):(En.info("Initializing extensions synchronously"),this._initExtensions(v)),i.DEBUG=i.DEBUG||this.config.debug,i.DEBUG&&En.info("Starting in debug mode",{this:this,config:t,thisC:ls({},this.config),p:p,s:g}),this.config.identity_distinct_id&&!(null===(r=t.bootstrap)||void 0===r?void 0:r.distinctID)&&(t.bootstrap=ls(ls({},t.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const f=null===(n=t.bootstrap)||void 0===n?void 0:n.distinctID;if(this._hasStableInitialDistinctId=!!f&&!yt(f),null===(o=t.bootstrap)||void 0===o?void 0:o.distinctID){const e=t.bootstrap.distinctID,i=this.get_distinct_id(),s=this.persistence.get_property(pe);if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"anonymous"===s)this.identify(e);else if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"identified"===s)En.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const i=this.config.get_device_id(Hn()),s=t.bootstrap.isIdentifiedID?i:e;this.persistence.set_property(pe,t.bootstrap.isIdentifiedID?De:Le),this.register({distinct_id:e,$device_id:s})}}if(v)this.register_once({distinct_id:Se,$device_id:null},"");else if(!this.get_distinct_id()){const e=this.config.get_device_id(Hn());this.register_once({distinct_id:e,$device_id:e},""),this.persistence.set_property(pe,Le)}return An(je,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),An(je,"pageshow",()=>{var e;this._isPageUnloading=!1,this._isShutdown||null===(e=this._retryQueue)||void 0===e||e.resume()}),t.segment?aa(this,()=>this._loaded()):this._loaded(),pt(this.config._onCapture)&&this.config._onCapture!==ru&&(En.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",e=>this.config._onCapture(e.event,e))),this.config.ip&&En.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Tc.apply(this,arguments)}().then(e=>{e&&this.register({[w]:e})}).catch(ru),this}_isSharedExtension(e){const t=e;return mt(t.name)&&pt(t.setup)}_enrollExtension(e,t){var i=this;this._isSharedExtension(e)?t.push(Lt(function*(){try{yield e.setup(i._getBrowserClientAdapter())}catch(i){En.error(`Failed to set up extension "${e.name}"`,i);try{var t;yield null===(t=e.dispose)||void 0===t?void 0:t.call(e)}catch(t){En.error(`Failed to dispose extension "${e.name}"`,t)}}})):this._extensions.push(e)}_enrollFeatureFlags(){var t,i,s,r=this;const n=null!==(t=null===(i=this.config.__extensionClasses)||void 0===i?void 0:i.featureFlags)&&void 0!==t?t:null===(s=e.__defaultExtensionClasses)||void 0===s?void 0:s.featureFlags;var o,a,l;if(n)if(this.featureFlags&&this.featureFlags instanceof n||(null===(o=this._featureFlagsReloadingUnsubscribe)||void 0===o||o.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new n(this)),pt(this.featureFlags.onReloading)&&pt(this.featureFlags.setup)){if(!this._featureFlagsReloadingUnsubscribe){this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading(()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)});const e=this.featureFlags;Lt(function*(){try{yield e.setup(r._getBrowserClientAdapter())}catch(t){En.error("Failed to set up feature flags",t);const i=r._featureFlagsReloadingUnsubscribe;r._featureFlagsReloadingUnsubscribe=void 0;try{null==i||i()}catch(e){En.error("Failed to unsubscribe feature flag reloading",e)}try{yield e.dispose()}catch(e){En.error("Failed to dispose feature flags",e)}}})()}}else null===(a=(l=this.featureFlags).initialize)||void 0===a||a.call(l)}_initExtensions(t){const i=performance.now(),s=ls(ls({},e.__defaultExtensionClasses),this.config.__extensionClasses),r=[];var n,o,a,l,c,u,d,h;s.exceptions&&this._extensions.push(this.exceptions=null!==(n=this.exceptions)&&void 0!==n?n:new s.exceptions(this)),s.historyAutocapture&&this._extensions.push(this.historyAutocapture=new s.historyAutocapture(this)),s.tracingHeaders&&this._extensions.push(this.tracingHeaders=new s.tracingHeaders(this)),s.siteApps&&this._extensions.push(this.siteApps=new s.siteApps(this)),s.sessionRecording&&!t&&this._extensions.push(this.sessionRecording=new s.sessionRecording(this)),this.config.disable_scroll_properties||r.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),s.autocapture&&this._enrollExtension(this.autocapture=new s.autocapture(this),r),s.surveys&&this._enrollExtension(this.surveys=null!==(o=this.surveys)&&void 0!==o?o:new s.surveys(this),r),s.logs&&this._enrollExtension(this.logs=null!==(a=this.logs)&&void 0!==a?a:new s.logs(this),r),s.metrics&&this._extensions.push(this.metrics=null!==(l=this.metrics)&&void 0!==l?l:new s.metrics(this)),s.conversations&&this._extensions.push(this.conversations=null!==(c=this.conversations)&&void 0!==c?c:new s.conversations(this)),s.productTours&&this._extensions.push(this.productTours=new s.productTours(this)),s.heatmaps&&this._extensions.push(this.heatmaps=new s.heatmaps(this)),s.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new s.webVitalsAutocapture(this)),s.exceptionObserver&&this._extensions.push(this.exceptionObserver=new s.exceptionObserver(this)),s.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new s.deadClicksAutocapture(this,ra)),s.toolbar&&this._extensions.push(this.toolbar=null!==(u=this.toolbar)&&void 0!==u?u:new s.toolbar(this)),s.experiments&&this._extensions.push(this.experiments=null!==(d=this.experiments)&&void 0!==d?d:new s.experiments(this)),s.webMCP&&this._extensions.push(this.webMCP=null!==(h=this.webMCP)&&void 0!==h?h:new s.webMCP(this)),this._extensions.forEach(e=>{e.initialize&&r.push(()=>{var t;null===(t=e.initialize)||void 0===t||t.call(e)})}),r.push(()=>{if(this._pendingRemoteConfig){const e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach(t=>{var i;return null===(i=t.onRemoteConfig)||void 0===i?void 0:i.call(t,e)})}}),this._processInitTaskQueue(r,i)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void(this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._processInitTaskQueue(e,t)},0));const i=e.shift();if(i)try{i()}catch(e){En.error("Error initializing extension:",e)}}const i=Math.round(performance.now()-t);this.register_for_session({[Ee]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ce]:i}),this.config.__preview_deferred_init_extensions&&En.info(`PostHog extensions initialized (${i}ms)`)}_onRemoteConfig(e){if(!Ge||!Ge.body)return En.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this._onRemoteConfig(e)},500);if(this.config.__preview_deferred_init_extensions&&(this._pendingRemoteConfig=e),this._lastRemoteConfig=e,this.compression=void 0,e.ok){var t;const i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ot(i.supportedCompression,Za.GZipJS)?Za.GZipJS:ot(i.supportedCompression,Za.Base64)?Za.Base64:void 0),(null===(t=i.analytics)||void 0===t?void 0:t.endpoint)&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:Ne}),this._internalEventEmitter.emit("extensionsRemoteConfig",e),this._extensions.forEach(t=>{var i;return null===(i=t.onRemoteConfig)||void 0===i?void 0:i.call(t,e)})}_loaded(){try{this.config.loaded(this)}catch(e){En.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&(null==Ke?void 0:Ke.hostname)){const e=Ke.hostname,t=this.config.internal_or_test_user_hostname;("string"==typeof t?e===t:t.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this._inCookielessMode())&&this._captureInitialPageview()},1),this._remoteConfigLoader=new fl(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null===(e=this._requestQueue)||void 0===e||e.enable())}_dom_loaded(){this.is_capturing()&&kn(this.__request_queue,e=>this._send_retriable_request(e)),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r,n;this._isPageUnloading=!0,null===(e=this.surveys)||void 0===e||null===(t=e.handlePageUnload)||void 0===t||t.call(e),null===(i=this.metrics)||void 0===i||i.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(Ue),null===(s=this.logs)||void 0===s||s.flushLogs("sendBeacon"),null===(r=this._requestQueue)||void 0===r||r.unload(),null===(n=this._retryQueue)||void 0===n||n.unload()):this._shouldCapturePageleave()&&this.capture(Ue,null,{transport:"sendBeacon"})}_send_request(e){mc(this,e)}_send_retriable_request(e,t){this._retryQueue?this._retryQueue.retriableRequest(e,t):this._send_request(t?ls(ls({},e),{},{transport:t}):e)}_execute_array(e){su++;try{let t;const i=[],s=[],r=[];kn(e,e=>{if(e)if(t=e[0],_t(t))r.push(e);else if(pt(e))try{e.call(this)}catch(t){En.error("Error executing queued PostHog call",e,t)}else _t(e)&&"alias"===t?i.push(e):_t(e)&&-1!==t.indexOf("capture")&&pt(this[t])?r.push(e):s.push(e)});const n=function(e,t){kn(e,function(e){try{if(_t(e[0])){let i=t;Pn(e,function(e){i=i[e[0]].apply(i,e.slice(1))})}else t[e[0]].apply(t,e.slice(1))}catch(t){En.error("Error executing queued PostHog call",e,t)}})};n(i,this),n(s,this),n(r,this)}finally{su--}}push(t){if(su>0&&_t(t)&&mt(t[0])){const i=e.prototype[t[0]];return void(pt(i)&&i.apply(this,t.slice(1)))}this._execute_array([t])}get _facebookClickIdChannel(){return{property:k,persistenceKey:P,cookieName:"_fbc",pattern:_u,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[P]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(P)}}}get _facebookBrowserIdChannel(){return{property:x,persistenceKey:F,cookieName:"_fbp",pattern:pu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[F]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(F)}}}_getPersistedMetaIdentifier(e){var t;const i=null===(t=this.persistence)||void 0===t?void 0:t.get_property(e.persistenceKey);return mt(i)&&e.pattern.test(i)?{value:i,delivered:!1}:gt(i)&&mt(i.value)&&e.pattern.test(i.value)?{value:i.value,delivered:!0===i.delivered}:void 0}_storeMetaIdentifier(e,t,i){return t===(null==i?void 0:i.value)?{value:t,pending:!i.delivered}:(e.register(t,!1),{value:t,pending:!0})}_readMetaCookie(e){if(!this.config.save_campaign_params||this._inCookielessMode())return;const t=Ln(e.cookieName);return mt(t)&&e.pattern.test(t)?t:void 0}_updateFacebookClickId(e,t,i,s){if(!this.persistence)return;const r=this._facebookClickIdChannel;this.persistence.refreshKey(r.persistenceKey);const n=this._getPersistedMetaIdentifier(r);if(s)return void r.unregister();if(i)return mt(t)&&_u.test(t)?this._storeMetaIdentifier(r,t,n):void r.unregister();const o=mt(e)&&hu.test(e)?e:void 0,a=this._readMetaCookie(r);return a&&((e,t,i)=>{const s=e.split(".");if(t)return s[3]===t;if(!i)return!0;const r=i.value.split(".");return s[3]===r[3]||Number(s[2])>Number(r[2])})(a,o,n)?this._storeMetaIdentifier(r,a,n):o?(null==n?void 0:n.value.split(".")[3])===o?{value:n.value,pending:!n.delivered}:this._storeMetaIdentifier(r,`fb.1.${Date.now()}.${o}`,n):n?{value:n.value,pending:!n.delivered}:void 0}_updateFacebookBrowserId(e,t,i){if(!this.persistence)return;const s=this._facebookBrowserIdChannel;this.persistence.refreshKey(s.persistenceKey);const r=this._getPersistedMetaIdentifier(s);if(i)return void s.unregister();if(t)return mt(e)&&pu.test(e)?this._storeMetaIdentifier(s,e,r):void s.unregister();const n=this._readMetaCookie(s);return n?this._storeMetaIdentifier(s,n,r):r?{value:r.value,pending:!r.delivered}:void 0}_markMetaIdentifierDelivered(e,t){if(!this.persistence)return;this.persistence.refreshKey(e.persistenceKey);const i=this._getPersistedMetaIdentifier(e);(null==i?void 0:i.value)!==t||i.delivered||e.register(t,!0)}capture(e,t,i){var s,r;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue))return void En.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(ft(e)||!mt(e))return void En.error("No event name provided to posthog.capture");if(this._syncCookielessIdentity(),"$snapshot"===e&&this._inCookielessMode())return;const n=!this.config.opt_out_useragent_filter&&this._is_bot();if(n&&!this.config.__preview_capture_bot_pageviews)return;const o=(null==i?void 0:i.skip_client_rate_limiting)?void 0:this.rateLimiter.clientRateLimitContext();if(null==o?void 0:o.isRateLimited)return void En.critical("This capture call is ignored due to client rate limiting.");let a;(null==t?void 0:t.$current_url)&&!mt(null==t?void 0:t.$current_url)&&(En.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),null==t||delete t.$current_url),"$exception"!==e||(null==i?void 0:i._originatedFromCaptureException)||En.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(a=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const l=new Date,c=(null==i?void 0:i.timestamp)||l,u=Zi(null==i?void 0:i.uuid,Hn);let d={uuid:u,event:e,properties:this.calculateEventProperties(e,t||{},c,u)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&n&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),o&&(d.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens);const h="$feature_flag_called"===e&&!1===d.properties.$feature_flag_has_experiment&&!0===this.get_property("$minimal_flag_called_events");(null==i?void 0:i.$set)&&!h&&(d.$set=null==i?void 0:i.$set);const _=gt(null==t?void 0:t.$set)?t.$set:void 0,p=_t(null==t?void 0:t.$unset)?t.$unset:[],g=(null==i?void 0:i.$unset)||[],v=e=>{var t;const s=!!(null==i?void 0:i.$set)&&e in i.$set;return{hasProvided:s||!!_&&e in _,provided:s?null==i||null===(t=i.$set)||void 0===t?void 0:t[e]:null==_?void 0:_[e],unset:-1!==p.indexOf(e)||-1!==g.indexOf(e)}},f=v(k),m=v(x),y=[{channel:this._facebookClickIdChannel,hasProvided:f.hasProvided,update:this._updateFacebookClickId(null==a?void 0:a.fbclid,f.provided,f.hasProvided,f.unset)},{channel:this._facebookBrowserIdChannel,hasProvided:m.hasProvided,update:this._updateFacebookBrowserId(m.provided,m.hasProvided,m.unset)}];for(const{channel:e,hasProvided:t,update:i}of y)i&&!0===d.properties.$process_person_profile&&i.pending&&!t&&!h&&(d.$set=ls({[e.property]:i.value},d.$set));const b=null==i?void 0:i.$unset;b&&(d.$unset=b);const S=h?void 0:this._calculate_set_once_properties(null==i?void 0:i.$set_once,e!==ze,e===He);if(S&&(d.$set_once=S),(null==i?void 0:i._noTruncate)||(w=this.config.properties_string_max_length,d=function(e,t){const i=new Set;return function e(s,r){if(s!==Object(s))return t?t(s):s;if(i.has(s))return;let n;if(i.add(s),_t(s))n=[],kn(s,t=>{n.push(e(t))});else{const t={};Pn(It(s)?Rn(s):s,(s,r)=>{i.has(s)||(t[r]=e(s,r))}),n=t}return n}(e)}(d,e=>mt(e)?e.slice(0,w):e)),d.timestamp=c,ft(null==i?void 0:i.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=l),h&&(d.properties=((e,t=[])=>{const i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return sr.forEach(s),t.forEach(s),i})(d.properties,gu)),e===al.DISMISSED||e===al.SENT){const i=null==t?void 0:t[ll.SURVEY_ID],s=null==t?void 0:t[ll.SURVEY_ITERATION];jc({id:i,current_iteration:s}),d.$set=ls(ls({},d.$set),{},{[Rc({id:i,current_iteration:s},e===al.SENT?"responded":"dismissed")]:!0})}else e===al.SHOWN&&(d.$set=ls(ls({},d.$set),{},{[ll.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));var w;if(e===hl.SHOWN){const e=null==t?void 0:t[_l.TOUR_TYPE];e&&(d.$set=ls(ls({},d.$set),{},{[`${_l.TOUR_LAST_SEEN_DATE}/${e}`]:(new Date).toISOString()}))}const E=ls(ls({},d.properties.$set),d.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!St(this.config.before_send)){const e=this._runBeforeSend(d);if(!e)return;d=e,d.uuid=Zi(d.uuid,Hn)}this.sessionRecording&&!this._replayDebugPropertiesPaused&&du(e)&&(this._replayDebugPropertiesPaused=!0,setTimeout(()=>this._replayDebugPropertiesPaused=!1,3e4));const C=y.filter(({channel:e,update:t})=>{var i,s,r;const n=null!==(i=null===(s=d.$set)||void 0===s?void 0:s[e.property])&&void 0!==i?i:gt(null===(r=d.properties)||void 0===r?void 0:r.$set)?d.properties.$set[e.property]:void 0;return(null==t?void 0:t.pending)&&n===t.value});this._internalEventEmitter.emit("eventCaptured",d);const P=null!==(s=null==i?void 0:i._url)&&void 0!==s?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),F="recordings"===(null==i?void 0:i._batchKey)||/\/s\/(?:\?|$)/.test(P),I=ls(ls(ls({method:"POST",url:P,data:d,compression:"best-available",preferSyncCompression:null==i?void 0:i.send_instantly,timestampMode:F?"body":"capture-body",batchKey:null==i?void 0:i._batchKey},F&&(null===(r=d.properties)||void 0===r?void 0:r.$session_id)?{batchGroup:d.properties.$session_id+(d.properties.$window_id?`-${d.properties.$window_id}`:"")}:{}),(null==i?void 0:i.transport)?{transport:i.transport}:{}),C.length?{fireCallbackOnDrop:!0,callback:e=>{if(e.statusCode>=200&&300>e.statusCode)for(const{channel:e,update:t}of C)this._markMetaIdentifierDelivered(e,t.value)}}:{});if(!this.config.request_batching||i&&!(null==i?void 0:i._batchKey)||(null==i?void 0:i.send_instantly)){var T;let e;!I.transport&&!I.callback&&vt(null!==(T=this.config.request_headers)&&void 0!==T?T:{})&&this._isPageUnloading&&(e="sendBeacon"),this._send_retriable_request(I,e)}else this._requestQueue.enqueue(I);return d}_addCaptureHook(e){return this.on("eventCaptured",t=>e(t.event,t))}getExtension(e){var t;return null===(t=this._browserClientAdapter)||void 0===t?void 0:t.getExtension(e)}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new tu(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);let t=!0;return()=>{if(!t)return;t=!1;const i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}_processCookieIdentityChange(e=!0){var t,i,s;return!!(null===(t=this.persistence)||void 0===t?void 0:t.consumeCookieIdentityChange())&&(this._cachedPersonProperties=null,"anonymous"===this.persistence.get_property("$user_state")&&(null===(s=this.sessionPersistence)||void 0===s||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null===(i=this.featureFlags)||void 0===i||i.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,i,s,r,n){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return i;this._syncCookielessIdentity(),this.persistence.syncCookieProperties(),this._processCookieIdentityChange();const o=n?void 0:this.persistence.remove_event_timer(e);let a=ls({},i);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this._inCookielessMode()&&(a[we]=!0),"$snapshot"===e){const e=ls(ls({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=e.distinct_id,(!mt(a.distinct_id)&&!wt(a.distinct_id)||yt(a.distinct_id))&&En.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const l=function(e,i,s,r=!1){var n,o,a,l;if(!Xe)return{};const c=e?[...ka,...i||[]]:[],[u,d]=qi(Xe),[h,_]=function(e){for(let t=0;ji.length>t;t++){const[i,s,r]=ji[t],n=e.match(i);if(n){const t=r&&e.match(r)||n;return[s,(null==t?void 0:t[1])||""]}}return["",""]}(Xe),p=function(){const e="u">typeof navigator?navigator:void 0;return(null==e?void 0:e.brave)?{brave:!0}:{}}(),g={};ft(s)||(g.detectGoogleSearchApp=s);const v={},f=null===(n=navigator)||void 0===n||null===(n=n.userAgentData)||void 0===n?void 0:n.platform,m=null===(o=navigator)||void 0===o?void 0:o.maxTouchPoints,y=null==je||null===(a=je.screen)||void 0===a?void 0:a.width,b=null==je||null===(l=je.screen)||void 0===l?void 0:l.height,S=null==je?void 0:je.devicePixelRatio;ft(f)||(v.userAgentDataPlatform=f),ft(m)||(v.maxTouchPoints=m),ft(y)||(v.screenWidth=y),ft(b)||(v.screenHeight=b),ft(S)||(v.devicePixelRatio=S);const w=xn(Tn({$os:u,$os_version:d,$browser:Li(Xe,navigator.vendor,p,g),$webview_app:h,$webview_app_version:_,$device:Ui(Xe),$device_type:Hi(Xe,v),$timezone:va(),$timezone_offset:Na()}),{$current_url:Ea(r?es(null==Ke?void 0:Ke.href):null==Ke?void 0:Ke.href,c,xa),$host:null==Ke?void 0:Ke.host,$pathname:null==Ke?void 0:Ke.pathname,$raw_user_agent:Xe.length>1e3?Xe.substring(0,997)+"...":Xe,$browser_version:Ni(Xe,navigator.vendor,p,g),$browser_language:$a(),$browser_language_prefix:Ma(),$screen_height:null==je?void 0:je.screen.height,$screen_width:null==je?void 0:je.screen.width,$viewport_height:null==je?void 0:je.innerHeight,$viewport_width:null==je?void 0:je.innerWidth,$lib:t.LIB_NAME,$lib_version:t.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return t.SDK_DIST_CHANNEL&&(w.$sdk_dist_channel=t.SDK_DIST_CHANNEL),w}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:e,windowId:t}=this.sessionManager.checkAndGetSessionAndWindowId(n,s.getTime(),!0);a.$session_id=e,a.$window_id=t}this.sessionPropsManager&&xn(a,this.sessionPropsManager.getSessionProps());try{var c;if(this.sessionRecording){const t=this.sessionRecording.sdkDebugProperties,i=!this._replayDebugPropertiesPaused&&du(e);for(const e in t)(i||ot(cu,e))&&(a[e]=t[e])}a.$sdk_debug_retry_queue_size=null===(c=this._retryQueue)||void 0===c?void 0:c.length}catch(e){a.$sdk_debug_error_capturing_properties=String(e)}let u;if(this.requestRouter.region===Nc&&(a.$lib_custom_api_host=this.config.api_host),u="$pageview"!==e||n?"$pageleave"!==e||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,r),a=xn(a,u),"$pageview"===e&&Ge&&(a.title=Ge.title),!ft(o)){const e=s.getTime()-o;a.$duration=parseFloat((e/1e3).toFixed(3))}Xe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const d=this.persistence.properties(),h=this.sessionPersistence.properties(),_=a.$groups,p=d.$groups;gt(_)&&!vt(_)&&(a.$groups=ls(ls({},gt(p)?p:{}),_)),Pn(["$referrer","$referring_domain"],e=>{e in d&&delete h[e]});const g={};if(this._extensionEventPropertyProducers.length>0)for(const e of this._extensionEventPropertyProducers.slice())try{xn(g,e())}catch(e){En.error("Failed to produce browser extension event properties",e)}a=xn({},l,d,h,ls(ls({},g),a)),a.$is_identified=this._isIdentified(),_t(this.config.property_denylist)?Pn(this.config.property_denylist,function(e){delete a[e]}):En.error(lu+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const v=this.config.sanitize_properties;v&&(En.error(au),a=v(a,e));const f=this._hasPersonProcessing();return a.$process_person_profile=f,f&&!n&&this._requirePersonProcessing("_calculate_event_properties"),a}_calculate_set_once_properties(e,t=!0,i=!1){var s;if(!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;const r=this.persistence.get_initial_props(),n=null===(s=this.sessionPropsManager)||void 0===s?void 0:s.getSetOnceProps();let o=xn({},r,n||{},e||{});const a=this.config.sanitize_properties;return a&&(En.error(au),o=a(o,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),vt(o)?void 0:o}register(e,t){var i;null===(i=this.persistence)||void 0===i||i.register(e,t)}register_once(e,t,i){var s;null===(s=this.persistence)||void 0===s||s.register_once(e,t,i)}register_for_session(e){var t,i;null===(t=this.persistence)||void 0===t||t.syncCookieProperties(),this._processCookieIdentityChange(),null===(i=this.sessionPersistence)||void 0===i||i.register(e),Object.keys(e).forEach(e=>this._sessionRegisteredPropKeys.add(e)),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null===(t=this.persistence)||void 0===t||t.unregister(e)}unregister_for_session(e){var t;null===(t=this.sessionPersistence)||void 0===t||t.unregister(e),this._sessionRegisteredPropKeys.delete(e),this._persistSessionRegisteredPropKeys()}_register_single(e,t){this.register({[e]:t})}_clearSessionRegisteredProps(){this._sessionRegisteredPropKeys.forEach(e=>{var t;null===(t=this.sessionPersistence)||void 0===t||t.unregister(e)}),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(!this._sessionRegisteredPropertiesStorageKey)return;if("memory"===this.config.persistence||(null===(e=this.sessionPersistence)||void 0===e?void 0:e._disabled)||!co._is_supported())return void co._remove(this._sessionRegisteredPropertiesStorageKey);const t=[];this._sessionRegisteredPropKeys.forEach(e=>t.push(e)),t.length>0?co._set(this._sessionRegisteredPropertiesStorageKey,t):co._remove(this._sessionRegisteredPropertiesStorageKey)}getFeatureFlag(e,t){var i;return null===(i=this.featureFlags)||void 0===i?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null===(t=this.featureFlags)||void 0===t?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null===(i=this.featureFlags)||void 0===i?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null===(t=this.featureFlags)||void 0===t?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null===(s=this.featureFlags)||void 0===s?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null===(e=this.featureFlags)||void 0===e||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null===(s=this.featureFlags)||void 0===s||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null===(s=this.featureFlags)||void 0===s||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t=!1,i){var s;return null===(s=this.featureFlags)||void 0===s?void 0:s.getEarlyAccessFeatures(e,t,i)}on(e,t){return this._internalEventEmitter.on(e,t)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:ou}),()=>{})}onSessionId(e){var t,i;return null!==(t=null===(i=this.sessionManager)||void 0===i?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t=!1){this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:ou})}getActiveMatchingSurveys(e,t=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:ou})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:ou}),()=>{})}renderSurvey(e,t){var i;null===(i=this.surveys)||void 0===i||i.renderSurvey(e,t)}displaySurvey(e,t=Vc){var i;null===(i=this.surveys)||void 0===i||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null===(t=this.surveys)||void 0===t||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null===(i=this.surveys)||void 0===i?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:ou}}canRenderSurveyAsync(e,t=!1){var i,s;return null!==(i=null===(s=this.surveys)||void 0===s?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:ou})}_validateIdentifyId(e){return!e||yt(e)?(En.critical("Unique user id has not been set in posthog.identify"),!1):"$posthog_cookieless"===e?(En.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(En.critical(`The string "${e}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(e,t,i){if(!this.__loaded||!this.persistence)return En.uninitializedWarning("posthog.identify");if(wt(e)&&(e=e.toString(),En.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this._validateIdentifyId(e))return;if(!this._requirePersonProcessing("posthog.identify"))return;this._syncCookielessIdentity();const s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression();let a=!1;try{const s=this.get_distinct_id();this.register({$user_id:e}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:s},""),e!==s&&e!==this.get_property("__alias")&&(this.unregister(E),this.register({distinct_id:e}));const o=(this.persistence.get_property("$user_state")||"anonymous")===Le,c=e!==s,u=!c&&o;if(c&&o){var l;const r=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:s};this.persistence.set_property(pe,De),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$identify",r,{$set:t||{},$set_once:i||{}})&&(this._cachedPersonProperties=Dc(e,t,i)),null===(l=this.featureFlags)||void 0===l||l.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:s)}else if(u){this.persistence.set_property(pe,De);const s=t||{},r=i||{};this.setPersonPropertiesForFlags({$set:s,$set_once:r},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:s,$set_once:r})&&(this._cachedPersonProperties=Dc(e,t,i))}else(t||i)&&this.setPersonProperties(t,i);c||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(_)):u&&(t||i)&&this.reloadFeatureFlags(),a=!0}finally{o&&this.persistence._endCookieSyncSuppression(a)}}setPersonProperties(e,t){if(!e&&!t)return;if(!this._requirePersonProcessing("posthog.setPersonProperties"))return;const i=Dc(this.get_distinct_id(),e,t);this._cachedPersonProperties!==i?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:t||{}},!0),this.capture("$set",{$set:e||{},$set_once:t||{}})&&(this._cachedPersonProperties=i)):En.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var t;const i=(_t(e)?e:[e]).filter(e=>mt(e)&&e.length>0);0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null===(t=this.featureFlags)||void 0===t||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,i){var s;if(!e||!t)return void En.error("posthog.group requires a group type and group key");null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange();const r=this.getGroups(),n=r[e]!==t;if(n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:ls(ls({},r),{},{[e]:t})}),(n||i)&&this._hasPersonProcessing()){const s={$group_type:e,$group_key:t};i&&(s.$group_set=i),this.capture(ze,s)}i&&this.setGroupPropertiesForFlags({[e]:i}),n&&!i&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t=!0){var i;null===(i=this.featureFlags)||void 0===i||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e=!0){var t;null===(t=this.featureFlags)||void 0===t||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t=!0){var i;this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null===(i=this.featureFlags)||void 0===i||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null===(t=this.featureFlags)||void 0===t||t.resetGroupPropertiesForFlags(e)}reset(e){const t=Ct(e)?e:null==e?void 0:e.resetDeviceID,i=Ct(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t=!1,i){var s,r,n,o,a,l;if(En.info("reset"),!this.__loaded)return En.uninitializedWarning("posthog.reset");const c=null==i?void 0:i.sessionID;this.config.bootstrap=i||(null===(s=this._originalUserConfig)||void 0===s?void 0:s.bootstrap)||{},null===(r=this.featureFlags)||void 0===r||null===(n=r.updateConfig)||void 0===n||n.call(r,this.config,this._shouldDisableFlags());const u=this.get_property(S),d=this.get_property(w),h=this.get_property(U);null===(o=this.sessionRecording)||void 0===o||o.flushBeforeIdentityReset();const _=this.is_capturing();t||this.consent.reset(),t||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const p=null===(a=this.persistence)||void 0===a||null===(l=a._beginCookieSyncSuppression)||void 0===l?void 0:l.call(a),g=this._isConsentTransition;this._isConsentTransition=g||t;let v=!1;try{var f,m,y,b,E,C,k,P,x,F,I,T,R;if(null===(f=this.persistence)||void 0===f||f.clear(),null===(m=this.sessionPersistence)||void 0===m||m.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),ft(h)||null===(F=this.persistence)||void 0===F||F.register({$session_recording_remote_config:h}),null===(y=this.surveys)||void 0===y||y.reset(),null===(b=this.featureFlags)||void 0===b||b.reset(),null===(E=this.conversations)||void 0===E||E.reset(),null===(C=this.logs)||void 0===C||C.reset(),null===(k=this.metrics)||void 0===k||k.reset(),null===(P=this.persistence)||void 0===P||P.set_property("$user_state","anonymous"),null===(x=this.sessionManager)||void 0===x||x.resetSessionId(),this._cachedPersonProperties=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:Se,$device_id:null},"");else{const t=this.config.get_device_id(Hn());this.register_once({distinct_id:t,$device_id:e?t:u},""),e||ft(d)||this.register({[w]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),i)if(i.distinctID&&!this._inCookielessMode()&&(null===(R=this.persistence)||void 0===R||R.set_property("$user_state",i.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:i.distinctID})),null===(I=this.featureFlags)||void 0===I||I.initialize(),!St(c)&&!(null===(T=this.sessionManager)||void 0===T?void 0:T.setBootstrapSessionId(c,!0))){const e=ls({},i);delete e.sessionID,this.config.bootstrap=e}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,v=!0}finally{var M,A;this._isConsentTransition=g,p&&(null===(M=this.persistence)||void 0===M||null===(A=M._endCookieSyncSuppression)||void 0===A||A.call(M,v))}this.reloadFeatureFlags()}shutdown(e){var t=this;return Lt(function*(){if(!t.__loaded)return void En.uninitializedWarning("posthog.shutdown");t._isShutdown=!0,clearTimeout(t._extensionInitTimeout),t._extensionInitTimeout=void 0;const e=t._featureFlagsReloadingUnsubscribe;t._featureFlagsReloadingUnsubscribe=void 0;for(const i of[()=>{var e;return null===(e=t.sessionRecording)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.logs)||void 0===e?void 0:e.flushLogs("sendBeacon")},()=>{var e;return null===(e=t.metrics)||void 0===e?void 0:e.flush("sendBeacon")},()=>{var e;return null===(e=t.metrics)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.logs)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.surveys)||void 0===e?void 0:e.dispose()},()=>{var e;return null===(e=t.autocapture)||void 0===e?void 0:e.dispose()},()=>null==e?void 0:e(),()=>{var e;return null===(e=t._requestQueue)||void 0===e?void 0:e.unload()},()=>{var e;return null===(e=t._retryQueue)||void 0===e?void 0:e.unload()},()=>{var e;return null===(e=t.featureFlags)||void 0===e?void 0:e.destroy()},()=>{var e;return null===(e=t.persistence)||void 0===e?void 0:e.destroy()},()=>{var e;return null===(e=t.sessionPersistence)||void 0===e?void 0:e.destroy()}])try{const e=i();e&&pt(e.then)&&e.then(void 0,e=>{En.error("Error during shutdown",e)})}catch(e){En.error("Error during shutdown",e)}})()}setIdentity(e,t){var i;delete this.config.identity_claims,this.config.identity_distinct_id=e,this.config.identity_hash=t,this.alias(e),null===(i=this.conversations)||void 0===i||i._onIdentityChanged()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,null===(e=this.conversations)||void 0===e||e._onIdentityCleared()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,t;return null!==(e=null===(t=this.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";const{sessionId:t,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let s=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${t}`);if((null==e?void 0:e.withTimestamp)&&i){var r;const t=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+=`?t=${Math.max(Math.floor(((new Date).getTime()-i)/1e3)-t,0)}`}return s}alias(e,t){return e===this.get_property("$people_distinct_id")?(En.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(ft(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(E,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(En.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const t=ls({},this.config);if(gt(e)){var s,r,n,o,a,l,c,u,d,h,_,p,g,v;xn(this.config,bu(e));const S=this._is_persistence_disabled();if(this.persistence){const e="sessionStorage"===this.config.persistence||"memory"===this.config.persistence;var f,m;if(e&&this.sessionPersistence!==this.persistence&&(null===(f=this.sessionPersistence)||void 0===f||f.remove(),null===(m=this.sessionPersistence)||void 0===m||m.destroy()),this.persistence.update_config(this.config,t,S),e)this.sessionPersistence=this.persistence;else if(this.sessionPersistence===this.persistence)this.sessionPersistence=new Ya(ls(ls({},this.config),{},{persistence:"sessionStorage"}),S,!1);else{var y;null===(y=this.sessionPersistence)||void 0===y||y.update_config(ls(ls({},this.config),{},{persistence:"sessionStorage"}),ls(ls({},t),{},{persistence:"sessionStorage"}),S)}}const w=this._checkLocalStorageForDebug(this.config.debug);var b;Ct(w)&&(this.config.debug=w),Ct(this.config.debug)&&(this.config.debug?(i.DEBUG=!0,Qn._is_supported()&&Qn._set("ph_debug",!0),En.info("set_config",{config:e,oldConfig:t,newConfig:ls({},this.config)})):(i.DEBUG=!1,Qn._is_supported()&&Qn._remove("ph_debug"))),null===(s=this.featureFlags)||void 0===s||null===(r=s.updateConfig)||void 0===r||r.call(s,this.config,this._shouldDisableFlags()),null===(n=this.exceptionObserver)||void 0===n||n.onConfigChange(),null===(o=this.exceptions)||void 0===o||o.onConfigChange(),null===(a=this.metrics)||void 0===a||a.onConfigChange(),null===(l=this.webMCP)||void 0===l||l.startIfEnabled(),null===(c=this.sessionRecording)||void 0===c||c.startIfEnabledOrStop(),null===(u=this.tracingHeaders)||void 0===u||u.startIfEnabledOrStop(),null===(d=this.autocapture)||void 0===d||d.startIfEnabled(),null===(h=this.heatmaps)||void 0===h||h.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null===(b=this.historyAutocapture)||void 0===b||b.startIfEnabledOrStop()),null===(_=this.exceptionObserver)||void 0===_||_.startIfEnabledOrStop(),null===(p=this.deadClicksAutocapture)||void 0===p||p.startIfEnabledOrStop(),null===(g=this.surveys)||void 0===g||g.loadIfEnabled(),this._sync_opt_out_with_persistence(),null===(v=this.externalIntegrations)||void 0===v||v.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&aa(this,ru,!1)}}_overrideSDKInfo(e,t){i.LIB_NAME=e,i.LIB_VERSION=t}startSessionRecording(e){const t=!0===e,i={sampling:t||!!(null==e?void 0:e.sampling),linked_flag:t||!!(null==e?void 0:e.linked_flag),url_trigger:t||!!(null==e?void 0:e.url_trigger),event_trigger:t||!!(null==e?void 0:e.event_trigger)};var s,r,n,o,a;Object.values(i).some(Boolean)&&(null===(s=this.sessionManager)||void 0===s||s.checkAndGetSessionAndWindowId(),i.sampling&&(null===(r=this.sessionRecording)||void 0===r||r.overrideSampling()),i.linked_flag&&(null===(n=this.sessionRecording)||void 0===n||n.overrideLinkedFlag()),i.url_trigger&&(null===(o=this.sessionRecording)||void 0===o||o.overrideTrigger("url")),i.event_trigger&&(null===(a=this.sessionRecording)||void 0===a||a.overrideTrigger("event")));this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!!(null===(e=this.sessionRecording)||void 0===e?void 0:e.started)}captureException(e,t){try{if(!this.exceptions)return;const i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(ls(ls({},i),t))}catch(e){return}}addExceptionStep(e,t){var i;null===(i=this.exceptions)||void 0===i||i.addExceptionStep(e,t)}captureLog(e){var t;null===(t=this.logs)||void 0===t||t.captureLog(e)}get logger(){var t,i;return null!==(t=null===(i=this.logs)||void 0===i?void 0:i.logger)&&void 0!==t?t:e._noopLogger}startExceptionAutocapture(e){this.set_config({capture_exceptions:null==e||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var t,i;return null!==(t=null===(i=this.toolbar)||void 0===i?void 0:i.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null===(t=this.persistence)||void 0===t?void 0:t.props[e]}getSessionProperty(e){var t;return null===(t=this.sessionPersistence)||void 0===t?void 0:t.props[e]}toString(){var e;let t=null!==(e=this.config.name)&&void 0!==e?e:vu;return t!==vu&&(t="posthog."+t),t}_isIdentified(){var e,t;return"identified"===(null===(e=this.persistence)||void 0===e?void 0:e.get_property("$user_state"))||"identified"===(null===(t=this.sessionPersistence)||void 0===t?void 0:t.get_property("$user_state"))}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||"identified_only"===this.config.person_profiles&&!this._isIdentified()&&vt(this.getGroups())&&!(null===(e=this.persistence)||void 0===e||null===(e=e.props)||void 0===e?void 0:e.__alias)&&!(null===(t=this.persistence)||void 0===t||null===(t=t.props)||void 0===t?void 0:t.$epp))}_shouldCapturePageleave(){return!0===this.config.capture_pageleave||"if_capture_pageview"===this.config.capture_pageleave&&!!this.config.capture_pageview}createPersonProfile(){this._hasPersonProcessing()||this._requirePersonProcessing("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this._requirePersonProcessing("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}_requirePersonProcessing(e){return"never"===this.config.person_profiles?(En.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(be,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;const e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&"on_reject"!==this.config.cookieless_mode)}_sync_opt_out_with_persistence(){var e,t;const i=this._is_persistence_disabled();var s,r,n;return this.is_capturing()||null===(s=this.logs)||void 0===s||s._onOptOut(),(null===(e=this.persistence)||void 0===e?void 0:e._disabled)!==i&&(null===(r=this.persistence)||void 0===r||r.set_disabled(i)),(null===(t=this.sessionPersistence)||void 0===t?void 0:t._disabled)!==i&&(null===(n=this.sessionPersistence)||void 0===n||n.set_disabled(i)),this._persistSessionRegisteredPropKeys(),i}opt_in_capturing(t){var i;if("always"!==this.config.cookieless_mode){if(this._inCookielessMode()){var s,r,n,o,a,l;null===(s=this.sessionRecording)||void 0===s||s.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null===(r=this.sessionManager)||void 0===r||r.destroy(),null===(n=this.pageViewManager)||void 0===n||n.destroy(),this.sessionManager=new Fc(this),this.pageViewManager=new da(this),this.persistence&&(this.sessionPropsManager=new Cc(this,this.sessionManager,this.persistence));const t=null!==(o=null===(a=this.config.__extensionClasses)||void 0===a?void 0:a.sessionRecording)&&void 0!==o?o:null===(l=e.__defaultExtensionClasses)||void 0===l?void 0:l.sessionRecording;var c,u;t&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new t(this)),this._lastRemoteConfig&&(null===(c=this.sessionRecording)||void 0===c||null===(u=c.onRemoteConfig)||void 0===u||u.call(c,this._lastRemoteConfig)))}var d,h;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null===(i=this.sessionRecording)||void 0===i||i.startIfEnabledOrStop(),"on_reject"==this.config.cookieless_mode&&(null===(d=this.surveys)||void 0===d||d.loadIfEnabled()),(ft(null==t?void 0:t.captureEventName)||(null==t?void 0:t.captureEventName))&&this.capture(null!==(h=null==t?void 0:t.captureEventName)&&void 0!==h?h:"$opt_in",null==t?void 0:t.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}else En.warn(nu)}opt_out_capturing(){"always"!==this.config.cookieless_mode?(this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),"on_reject"===this.config.cookieless_mode&&this._enterCookielessMode()):En.warn(nu)}_enterCookielessMode(){var e,t;const i=this.sessionRecording;null==i||i.dispose({discardBufferedEvents:!0}),"$posthog_cookieless"!==this.get_distinct_id()&&this._reset(!0,!0),this.register({distinct_id:Se,$device_id:null}),this._removeExtension(i),this.sessionRecording=void 0,null===(e=this.sessionManager)||void 0===e||e.destroy(),null===(t=this.pageViewManager)||void 0===t||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in()}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return!this._isConsentTransition&&("always"===this.config.cookieless_mode||("on_reject"===this.config.cookieless_mode?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing()))}clear_opt_in_out_capturing(){this.consent.reset(),this._sync_opt_out_with_persistence()}_is_bot(){return Ve?Ic(Ve,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Ge&&("visible"===Ge.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(qe,{title:Ge.title},{send_instantly:!0}),this._visibilityStateListener&&(Ge.removeEventListener(m,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),An(Ge,m,this._visibilityStateListener)))}debug(e){!1===e?(null==je||je.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==je||je.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}_shouldDisableFlags(){const e=this._originalUserConfig||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:!1!==this.config.advanced_disable_flags?!!this.config.advanced_disable_flags:!0===this.config.advanced_disable_decide?(En.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){const n=t in e&&!St(e[t]),o=i in e&&!St(e[i]);return n?e[t]:!!o&&(r&&r.warn(`Config field '${i}' is deprecated. Please use '${t}' instead. The old field will be removed in a future major version.`),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,En)}_runBeforeSend(e){var t;if(St(this.config.before_send))return e;const i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Pt),s=_t(this.config.before_send)?this.config.before_send:[this.config.before_send];let r=e;for(const t of s)try{if(r=t(r),St(r)){const t=`Event '${e.event}' was rejected in beforeSend function`;return kt(e.event)?En.warn(`${t}. This can cause unexpected behavior.`):En.info(t),null}r.properties&&!vt(r.properties)||En.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(t){return En.error(`Error in beforeSend function for event '${e.event}':`,t),null}for(const t of i)if(r.properties&&St(r.properties[t]))return En.warn(`Event '${e.event}' had its '${t}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return r}getPageViewId(){var e;return null===(e=this.pageViewManager._currentPageview)||void 0===e?void 0:e.pageViewId}captureTraceFeedback(e,t){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:t})}captureTraceMetric(e,t,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:t,$ai_metric_value:String(i)})}_checkLocalStorageForDebug(e){const t=Ct(e)&&!e,i=Qn._is_supported()&&"true"===Qn._get("ph_debug");return!t&&(!!i||e)}};wu.__defaultExtensionClasses={},wu._noopLogger=(()=>{const e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),function(e,t){for(let i=0;t.length>i;i++)e.prototype[t[i]]=In(e.prototype[t[i]])}(wu,["identify"]);var Eu=class{constructor(e){this.disabled=!1===e;const t=gt(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,i){if(this.disabled)return!1;const s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)<this.thresholdPx&&this.timeoutMs>i-s.timestamp){if(this.clicks.push({x:e,y:t,timestamp:i}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:i}];return!1}};const Cu="$copy_autocapture",ku=Cn("[AutoCapture]");function Pu(e,t){return t.length>e?t.slice(0,e)+"...":t}function xu(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do{t=t.previousSibling}while(t&&!po(t));return t}function Fu(e,{e:t,maskAllElementAttributes:i,maskAllText:s,elementAttributeIgnoreList:r,elementsChainAsString:n,disableCaptureUrlHashes:o}){var a,l;if(!po(e))return{props:{}};const c=[e],u=new Set([e]);let d=e;for(;d.parentNode&&!go(d,"body")&&1e3>c.length;){if(fo(d.parentNode)){const e=d.parentNode.host;if(u.has(e))break;u.add(e),c.push(e),d=e;continue}if(!po(d.parentNode))break;if(u.has(d.parentNode))break;u.add(d.parentNode),c.push(d.parentNode),d=d.parentNode}const h="click"===t.type&&"http://www.w3.org/2000/svg"===e.namespaceURI?c.findIndex(e=>go(e,"button")||go(e,"a")):-1;h>0&&(s=s||c.slice(0,h+1).some(e=>!Ho(e)||zo(e)));const _=[],p={};let g,v=!1,f=!1;if(Pn(c,e=>{const t=Ho(e);if(go(e,"a")&&!i&&!(null==r?void 0:r.includes("href"))){const i=e.getAttribute("href");v=!!(t&&i&&Yo(i))&&(o?es(i):i)}ot(bo(e),"ph-no-capture")&&(f=!0),_.push(function(e,t,i,s,r=!1){const n=e.tagName.toLowerCase(),o={tag_name:n};Co.indexOf(n)>-1&&!i&&(o.$el_text="a"===n.toLowerCase()||"button"===n.toLowerCase()?Pu(1024,Zo(e)):Pu(1024,wo(e)));const a=bo(e);t||(null==s?void 0:s.includes("class"))||0>=a.length||(o.classes=a.filter(function(e){return""!==e})),Pn(e.attributes,function(i){var n;if((!zo(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&!(null==s?void 0:s.includes(i.name))&&!t&&Yo(i.value)&&(!mt(n=i.name)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){let e=i.value;"class"===i.name&&(e=mo(e).join(" ")),o["attr__"+i.name]=Pu(1024,"href"===i.name&&r?es(e):e)}});let l=1,c=1,u=e;for(;u=xu(u);)l++,u.tagName===e.tagName&&c++;return o.nth_child=l,o.nth_of_type=c,o}(e,i,s,r,o)),Pn(function(e){if(!Ho(e))return{};const t={};return Pn(e.attributes,function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){const i=e.name.replace("data-ph-capture-attribute-",""),s=e.value;i&&s&&Yo(s)&&(t[i]=s)}}),t}(e),(e,t)=>{({}).hasOwnProperty.call(p,t)||(p[t]=e)})}),f)return{props:{},explicitNoCapture:f};if(h>0&&(e=c[h],_.splice(0,h)),s||(_[0].$el_text=go(e,"a")||go(e,"button")?Zo(e):wo(e)),v){var m,y;_[0].attr__href=v;const e=null===(m=Sa(v))||void 0===m?void 0:m.host,t=null==je||null===(y=je.location)||void 0===y?void 0:y.host;e&&t&&e!==t&&(g=v)}return{props:xn((S=t.type,{$event_type:S,$ce_version:1}),n?{}:{$elements:_},{$elements_chain:(b=_,_t(b)?function(e){return e.map(e=>{var t,i;let s="";if(e.tag_name&&(s+=e.tag_name),e.attr_class){e.attr_class.sort();for(const t of e.attr_class)s+=`.${t.replace(/"/g,"")}`}const r=ls(ls(ls(ls({},e.text?{text:e.text}:{}),{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(i=e.nth_of_type)&&void 0!==i?i:0},e.href?{href:e.href}:{}),e.attr_id?{attr_id:e.attr_id}:{}),e.attributes),n={};return Fn(r).sort(([e],[t])=>function(e,t){return t>e?-1:e>t?1:0}(e,t)).forEach(([e,t])=>n[ea(e.toString())]=ea(t.toString())),s+=":",s+=Fn(n).map(([e,t])=>`${e}="${t}"`).join(""),s}).join(";")}(function(e){return e.map(e=>{var t,i;const s={text:null===(t=e.$el_text)||void 0===t?void 0:t.slice(0,400),tag_name:e.tag_name,href:null===(i=e.attr__href)||void 0===i?void 0:i.slice(0,2048),attr_class:ta(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Fn(e).filter(([e])=>0===e.indexOf("attr__")).forEach(([e,t])=>s.attributes[e]=t),s})}(b)):"")},(null===(a=_[0])||void 0===a?void 0:a.$el_text)?{$el_text:null===(l=_[0])||void 0===l?void 0:l.$el_text}:{},g&&"click"===t.type?{$external_click_url:g}:{},p),target:e};var b,S}var Iu=class{_clearPointer(){this._pointerDown=void 0,clearTimeout(this._pointerExpiry),this._pointerExpiry=void 0}_isExcludedPointerTarget(e){var t;if(!Ho(e))return!0;const i=null!==(t=this._refreshConfig().css_selector_ignorelist)&&void 0!==t?t:Fo,s=new Set;let r=e;for(;r;){if(s.size>=1e3||s.has(r))return!0;s.add(r);const e=r,t=bo(e);if(ot(t,"ph-no-capture")||ot(t,"ph-sensitive")||zo(e)||i.some(t=>ko(e,t)))return!0;const n=r.parentNode;r=fo(n)?n.host:n&&po(n)?n:null}return!1}_trackPointer(e){if(!this.isEnabled||"pointercancel"===e.type)return void this._clearPointer();if("pointerdown"===e.type){this._clearPointer();const i=Eo(e);var t;return void(e.isPrimary&&0===e.button&&!e.ctrlKey&&i&&po(i)&&(this._pointerDown={target:i,excluded:this._isExcludedPointerTarget(i),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:null===(t=this._client)||void 0===t?void 0:t.distinctId}))}const i=this._pointerDown;i&&(e.pointerId!==i.id||Math.abs(e.clientX-i.x)>5||Math.abs(e.clientY-i.y)>5?this._clearPointer():"pointerup"===e.type&&(i.released=!0,this._pointerExpiry=setTimeout(()=>this._clearPointer(),0)))}_recoverClickTarget(e){var t;const i=this._pointerDown;this._clearPointer();const s=Eo(e);if((null==i?void 0:i.released)&&i.target.isConnected&&i.distinctId===(null===(t=this._client)||void 0===t?void 0:t.distinctId)&&e.pointerId===i.id&&(e.detail>0||"touch"===e.pointerType||"pen"===e.pointerType)&&0===e.button&&5>=Math.abs(e.clientX-i.x)&&5>=Math.abs(e.clientY-i.y)&&s&&(go(s,"html")||go(s,"body"))){var r;if(i.excluded)return null;const e=null!==(r=this._refreshConfig().css_selector_ignorelist)&&void 0!==r?r:Fo;return[s,null==Ge?void 0:Ge.documentElement,null==Ge?void 0:Ge.body].some(t=>{if(!t)return!1;const i=bo(t);return ot(i,"ph-no-capture")||ot(i,"ph-sensitive")||!Ho(t)||zo(t)||e.some(e=>ko(t,e))})?null:i.target}}constructor(e){this._configSource=e,this.name=Jc,this._initialized=!1,this._isDisabledServerSide=null,this._hasReceivedConfigResponse=!1,this._elementSelectorsByOwner=new Map,this._elementsChainAsString=!1,this._config={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this._disposed=!1,this._configSource.refresh(this._config),this.rageclicks=new Eu(this._config.rageclick),this._elementSelectors=null}setup(e){this._compileUrlPatterns(),this._client=e;const t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.startIfEnabled())}dispose(){var e;this._disposed||(this._disposed=!0,this._client=void 0,null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,this._elementSelectorsByOwner.clear(),this._elementSelectors=null,this._removeDomEventHandlers())}_refreshConfig(){return this._configSource.refresh(this._config),this._config}_compileUrlPatterns(){var e,t;return this._refreshConfig(),this._config.url_allowlist=null===(e=this._config.url_allowlist)||void 0===e?void 0:e.map(e=>new RegExp(e)),this._config.url_ignorelist=null===(t=this._config.url_ignorelist)||void 0===t?void 0:t.map(e=>new RegExp(e)),this._config}_addDomEventHandlers(){if(!this.isBrowserSupported())return void ku.info("Disabling Automatic Event Collection because this browser is not supported");if(!je||!Ge)return;const e=this._domEventHandler=e=>{e=e||(null==je?void 0:je.event);try{if("blur"===e.type)return void this._clearPointer();if(0===e.type.indexOf("pointer"))return void this._trackPointer(e);const t="click"===e.type?this._recoverClickTarget(e):void 0;if(bt(t))return;this._captureEvent(e,"$autocapture",t)}catch(e){ku.error("Failed to capture event",e)}};if(An(je,"blur",e),An(Ge,"submit",e,{capture:!0}),An(Ge,"change",e,{capture:!0}),An(Ge,"click",e,{capture:!0}),Pn(["pointerdown","pointermove","pointerup","pointercancel"],t=>{An(Ge,t,e,{capture:!0})}),this._refreshConfig().capture_copied_text){const e=this._copiedTextHandler=e=>{e=e||(null==je?void 0:je.event);try{this._captureEvent(e,Cu)}catch(e){ku.error("Failed to capture clipboard event",e)}};An(Ge,"copy",e,{capture:!0}),An(Ge,"cut",e,{capture:!0}),An(Ge,"paste",e,{capture:!0})}}_removeDomEventHandlers(){this._clearPointer(),this._domEventHandler&&(null==je||je.removeEventListener("blur",this._domEventHandler),Pn(["pointerdown","pointermove","pointerup","pointercancel"],e=>{null==Ge||Ge.removeEventListener(e,this._domEventHandler,!0)}),null==Ge||Ge.removeEventListener("submit",this._domEventHandler,!0),null==Ge||Ge.removeEventListener("change",this._domEventHandler,!0),null==Ge||Ge.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==Ge||Ge.removeEventListener("copy",this._copiedTextHandler,!0),null==Ge||Ge.removeEventListener("cut",this._copiedTextHandler,!0),null==Ge||Ge.removeEventListener("paste",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._initialized=!1}startIfEnabled(){this.isEnabled||this._clearPointer(),!this._disposed&&this._client&&this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){if(this._disposed)return;if(this._hasReceivedConfigResponse=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString);const i=t.autocapture_opt_out;var s;Ct(i)&&(null===(s=this._client)||void 0===s||s.kv.set("$autocapture_disabled_server_side",i),this._isDisabledServerSide=i),this.startIfEnabled()}setElementSelectors(e,t=this){if(this._disposed)return;e.size?this._elementSelectorsByOwner.set(t,new Set(e)):this._elementSelectorsByOwner.delete(t);const i=new Set;this._elementSelectorsByOwner.forEach(e=>{e.forEach(e=>i.add(e))}),this._elementSelectors=i}getElementSelectors(e,t){var i;const s=[];return null===(i=this._elementSelectors)||void 0===i||i.forEach(i=>{const r=null==Ge?void 0:Ge.querySelectorAll(i);null==r||r.forEach(r=>{e!==r&&t!==r||ot(s,i)||s.push(i)})}),s}get isEnabled(){var e,t;if(this._disposed)return!1;const i=null===(e=this._client)||void 0===e?void 0:e.kv.get(T),s=this._isDisabledServerSide,r=this._refreshConfig();if(!r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse)return!1;const n=r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(bt(s)&&!Ct(i)&&!n)return!1;const o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!r.enabled&&!o}_captureEvent(e,t="$autocapture",i){if(!this.isEnabled)return void this._clearPointer();let s=i||Eo(e);vo(s)&&(s=s.parentNode||null);const r=this._compileUrlPatterns();var n;"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&r.rageclick&&(null===(n=this.rageclicks)||void 0===n?void 0:n.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime()))&&Bo(s,r.rageclick)&&this._captureEvent(e,"$rageclick",i);const o=t===Cu,a=o?ls(ls({},r),{},{dom_event_allowlist:void 0}):r;if(s&&function(e,t,i,s,r,n){var o;if(!je||qo(e))return!1;if((null==i?void 0:i.url_allowlist)&&!yo(i.url_allowlist,n))return!1;if((null==i?void 0:i.url_ignorelist)&&yo(i.url_ignorelist,n))return!1;if(null==i?void 0:i.dom_event_allowlist){const e=i.dom_event_allowlist;if(e&&!e.some(e=>t.type===e))return!1}const{parentIsUsefulElement:a,targetElementList:l}=Uo(e,s);if(!function(e,t){const i=null==t?void 0:t.element_allowlist;if(ft(i))return!0;for(const t of e)if(i.some(e=>t.tagName.toLowerCase()===e))return!0;return!1}(l,i))return!1;if(!Po(l,null==i?void 0:i.css_selector_allowlist))return!1;if(Po(l,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Fo))return!1;try{const i=je.getComputedStyle(e);if(i&&"pointer"===i.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}const c=e.tagName.toLowerCase();switch(c){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return a?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(Co.indexOf(c)>-1||"true"===e.getAttribute("contenteditable"))}}(s,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:r.getCurrentUrl}})){var l;const{props:i,explicitNoCapture:n,target:o}=Fu(s,{e:e,maskAllElementAttributes:r.maskAllElementAttributes,maskAllText:r.maskAllText,elementAttributeIgnoreList:r.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:r.disableCaptureUrlHashes});if(n)return!1;const a=this.getElementSelectors(s,o);if(a&&a.length>0&&(i.$element_selectors=a),t===Cu){const t=e.type||"clipboard";if("paste"!==t){var c,u;const e=null==je||null===(c=je.getSelection())||void 0===c?void 0:c.toString(),t=So(e);if(!t)return!1;i.$selected_content=t,i.$clipboard_text_length=null!==(u=null==e?void 0:e.length)&&void 0!==u?u:0}i.$copy_type=t}return null===(l=this._client)||void 0===l||l.capture(t,i),!0}}isBrowserSupported(){return pt(null==Ge?void 0:Ge.querySelectorAll)}},Tu=class{constructor(e){this._instance=e}refresh(e){const t=this._instance.config,i=gt(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==i?void 0:i.url_allowlist,e.url_ignorelist=null==i?void 0:i.url_ignorelist,e.dom_event_allowlist=null==i?void 0:i.dom_event_allowlist,e.element_allowlist=null==i?void 0:i.element_allowlist,e.css_selector_allowlist=null==i?void 0:i.css_selector_allowlist,e.css_selector_ignorelist=null==i?void 0:i.css_selector_ignorelist,e.element_attribute_ignorelist=null==i?void 0:i.element_attribute_ignorelist,e.capture_copied_text=null==i?void 0:i.capture_copied_text}};const Ru=Cn("[ExceptionAutocapture]"),$u=()=>{},Mu=e=>{var t;if(pt(e))return null!==(t=e.__posthog_layer__)&&void 0!==t?t:e.__rrweb_layer__};function Au(e,t,i){try{if(!(t in e))return $u;const s={next:e[t]},r=i(function(...e){return s.next.apply(this,e)});return pt(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=r,()=>{if(e[t]===r)return void(e[t]=s.next);let i=e[t],n=Mu(i);for(;n;){if(n.next===r)return void(n.next=s.next);i=n.next,n=Mu(i)}}}catch(e){return $u}}const Ou=Cn("[TracingHeaders]"),Lu=Cn("[Web Vitals]"),Du=9e5,Nu=["CLS","FCP","INP","LCP"],Bu=["INP","LCP"],qu=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Uu="disabled",Hu="lazy_loading",zu=Cn("[SessionRecording]"),ju=[ke,Pe,xe,Fe,Ie,Te,Re,$e,Me],Wu=Cn("[Heatmaps]");function Vu(e){return gt(e)&&"clientX"in e&&"clientY"in e&&wt(e.clientX)&&wt(e.clientY)}const Gu=Cn("[Product Tours]"),Ku=e=>{var t;return!e.config.disable_product_tours&&!!(null===(t=e.persistence)||void 0===t?void 0:t.get_property(N))},Qu=["$set_once","$set"],Ju=Cn("[SiteApps]"),Yu="Error while initializing PostHog app with config id ",Zu=(e,t)=>(null==e?void 0:e.then)?e.then(t):t(e),Xu="SDK is not enabled or survey functionality is not yet loaded",ed="Disabled. Not loading surveys.";var td=class{constructor(e,t){this._configSource=e,this._initialClientState=t,this.name=Xc,this._surveyEventReceiver=null,this._surveyManager=null,this._isInitializingSurveys=!1,this._surveyInitializationFailed=!1,this._surveyCallbacks=[],this._activeMatchingSurveyCallbacks=[],this._getSurveysInFlightPromise=null,this._lastSurveyRefreshFailedAt=null,this._disposed=!1,this._renderTimeouts=new Set,this.onRemoteConfig=e=>{if(this._disposed)return;if(this._config.disableSurveys)return;if(!e.ok)return this._surveyInitializationFailed=!0,this._notifyActiveMatchingSurveyCallbacks({isLoaded:!1,error:"Remote config unavailable. Not loading surveys."}),zc.warn("Remote config unavailable. Not loading surveys.");const t=e.config.surveys;if(St(t))return zc.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=Ct(t)?t:t.length>0,zc.info(`flags response received, isSurveysEnabled: ${this._isSurveysEnabled}`),this.loadIfEnabled()},this._notifyActiveMatchingSurveyCallbacks=e=>{this._activeMatchingSurveyCallbacks.slice().forEach(t=>this._notifyActiveMatchingSurveyCallback(t,e))}}setup(e){if(!this._disposed)return this._initializingClient=e,Zu(e.kv.initialize(),()=>{if(this._initializingClient!==e||this._disposed)return;this._initializingClient=void 0,this._client=e;const t=e.onRemoteConfig(this.onRemoteConfig);this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.loadIfEnabled())})}dispose(){var e,t,i,s,r;this._disposed||(this._disposed=!0,this._initializingClient=void 0,this._client=void 0,null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,null===(t=this._surveyEventReceiver)||void 0===t||t.dispose(),this._surveyEventReceiver=null,null===(i=this._surveyManager)||void 0===i||null===(s=i.dispose)||void 0===s||s.call(i),this._surveyManager=null,this._surveyCallbacks=[],this._activeMatchingSurveyCallbacks.forEach(e=>{e.active=!1}),this._activeMatchingSurveyCallbacks=[],null===(r=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===r||r.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0,this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach(e=>clearTimeout(e)),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}initialize(){this.loadIfEnabled()}reset(){var e,t;null===(e=this._surveyManager)||void 0===e||null===(t=e.clearInMemoryInProgressSurveyState)||void 0===t||t.call(e);try{var i;null===(i=this._surveyEventReceiver)||void 0===i||i.reset(),localStorage.removeItem("lastSeenSurveyDate");const e=[];for(let t=0;t<localStorage.length;t++){const i=localStorage.key(t);((null==i?void 0:i.startsWith("seenSurvey_"))||(null==i?void 0:i.startsWith("inProgressSurvey_")))&&e.push(i)}e.forEach(e=>localStorage.removeItem(e))}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}loadIfEnabled(){if(this._disposed||!this._client)return;const e=this._config;if(this._surveyManager)return;if(this._isInitializingSurveys)return void zc.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void zc.info(ed);if(e.cookielessMode&&this._configSource.isOptedOut())return void zc.info("Not loading surveys in cookieless mode without consent.");const t=this._configSource.getExtensions();if(!t)return void this._handleSurveyLoadError("PostHog Extensions not found.");if(ft(this._isSurveysEnabled)&&!e.advancedEnableSurveys)return;const i=this._isSurveysEnabled||e.advancedEnableSurveys;this._isInitializingSurveys=!0,this._surveyInitializationFailed=!1;try{const e=t.generateSurveys;if(e)return this._completeSurveyInitialization(e,i),void(this._isInitializingSurveys=!1);const s=t.loadExternalDependency;if(!s)return this._handleSurveyLoadError(Oe),void(this._isInitializingSurveys=!1);s(e=>{try{if(this._disposed)return;const t=this._configSource.getExtensions();e||!(null==t?void 0:t.generateSurveys)?this._handleSurveyLoadError("Could not load surveys script",e):this._completeSurveyInitialization(t.generateSurveys,i)}finally{this._isInitializingSurveys=!1}})}catch(e){throw this._isInitializingSurveys=!1,this._handleSurveyLoadError("Error initializing surveys",e),e}}_completeSurveyInitialization(e,t){var i,s;if(this._disposed)return;this._surveyManager=e(t),this._surveyEventReceiver=this._configSource.createEventReceiver(this._notifyActiveMatchingSurveyCallbacks);const r=null===(i=null!==(s=this._client)&&void 0!==s?s:this._initialClientState)||void 0===i?void 0:i.kv.get(ie);r&&this._registerEventOrActionBasedSurveys(r),zc.info("Surveys loaded successfully"),this._startActiveMatchingSurveyConditions(),this._notifyActiveMatchingSurveyCallbacks(),this._notifySurveyCallbacks({isLoaded:!0})}_handleSurveyLoadError(e,t){this._surveyInitializationFailed=!0,zc.error(e,t),this._notifyActiveMatchingSurveyCallbacks({isLoaded:!1,error:e}),this._notifySurveyCallbacks({isLoaded:!1,error:e})}onSurveysLoaded(e){return this._surveyCallbacks.push(e),this._surveyManager&&this._notifySurveyCallbacks({isLoaded:!0}),()=>{this._surveyCallbacks=this._surveyCallbacks.filter(t=>t!==e)}}getSurveys(e,t=!1){var i;const s=null!==(i=this._client)&&void 0!==i?i:this._initialClientState;if(!s||this._disposed)return;if(this._config.disableSurveys)return zc.info(ed),e([]);const r=s.kv.get(ie);if(r&&!t)return e(r,{isLoaded:!0}),void(this._shouldBackgroundRefreshSurveys()&&this.getSurveys(()=>{},!0));if(this._getSurveysInFlightPromise)return void this._getSurveysInFlightPromise.then(({surveys:t,context:i})=>{this._disposed||e(t,i)}).catch(e=>zc.error("Error in survey callback",e));const n=this._sendSurveysRequest("/api/surveys/",{method:"GET",query:{token:s.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then(e=>{try{return this._handleSurveyResponse(s,e)}catch(e){return zc.error("Error processing surveys response",e),this._handleSurveyResponse(s,{statusCode:0,error:e})}},e=>this._handleSurveyResponse(s,{statusCode:0,error:e}));this._getSurveysInFlightPromise=n;const o=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then(t=>{o(),this._disposed||(this._notifyActiveMatchingSurveyCallbacks(t.context),e(t.surveys,t.context))},o).catch(e=>zc.error("Error in survey callback",e))}_sendSurveysRequest(e,t){const i=this._client;return i?i.sendRequest(e,t):new Promise(e=>e({statusCode:0,error:new Error(Xu)}))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Xu}};const i=t.statusCode;if(200!==i||!t.json){const e=`Surveys API could not be loaded, status: ${i}`;return 0!==i?zc.error(e):t.error||zc.warn(e),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:e}}}this._lastSurveyRefreshFailedAt=null;const s=t.json.surveys||[];return e.kv.set({[ie]:s,[se]:Date.now()}),this._registerEventOrActionBasedSurveys(s),{surveys:s,context:{isLoaded:!0}}}_registerEventOrActionBasedSurveys(e){var t;const i=e.filter(e=>function(e){return!(!e.start_date||e.end_date)}(e)&&($c(e)||function(e){var t;return!!(null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length)}(e)));null===(t=this._surveyEventReceiver)||void 0===t||t.replace(i)}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e,t;const i=null===(e=null!==(t=this._client)&&void 0!==t?t:this._initialClientState)||void 0===e?void 0:e.kv.get(se);return wt(i)&&Date.now()-i>3e5}_isSurveyRefreshBackingOff(){return wt(this._lastSurveyRefreshFailedAt)&&3e5>Date.now()-this._lastSurveyRefreshFailedAt}markSurveyAsSeen(e,t){var i;const s={id:e,current_iteration:null!==(i=null==t?void 0:t.iteration)&&void 0!==i?i:null};jc(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}_notifySurveyCallbacks(e){for(const t of this._surveyCallbacks)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){zc.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t=!1){if(!St(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);zc.warn("init was not called")}onActiveMatchingSurveysChanged(e){var t,i;if(this._disposed)return()=>{};const s={callback:e,active:!0,revision:0};this._activeMatchingSurveyCallbacks.push(s),this._startActiveMatchingSurveyConditions();const r=null===(t=null!==(i=this._client)&&void 0!==i?i:this._initialClientState)||void 0===t?void 0:t.kv.get(ie);return this._config.disableSurveys||!this._surveyManager&&this._surveyInitializationFailed&&!this._isInitializingSurveys||!r&&!St(this._lastSurveyRefreshFailedAt)&&!this._getSurveysInFlightPromise?this._notifyActiveMatchingSurveyCallback(s,{isLoaded:!1}):this._surveyManager&&this._notifyActiveMatchingSurveyCallback(s),()=>{var e;s.active=!1,this._activeMatchingSurveyCallbacks=this._activeMatchingSurveyCallbacks.filter(e=>e!==s),0===this._activeMatchingSurveyCallbacks.length&&(null===(e=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===e||e.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0)}}_startActiveMatchingSurveyConditions(){var e,t,i;this._surveyManager&&this._activeMatchingSurveyCallbacks.length>0&&(null!==(e=this._activeMatchingSurveyConditionsUnsubscribe)&&void 0!==e||(this._activeMatchingSurveyConditionsUnsubscribe=null===(t=(i=this._configSource).onMatchingConditionsChanged)||void 0===t?void 0:t.call(i,this._notifyActiveMatchingSurveyCallbacks)))}_notifyActiveMatchingSurveyCallback(e,t){if(this._disposed||!e.active)return;const i=++e.revision,s=s=>{if(!this._disposed&&e.active&&i===e.revision)try{const i=null!=t?t:{isLoaded:!0},r=JSON.stringify([s,i]);if(r===e.lastResult)return;e.lastResult=r,e.callback(s,i)}catch(e){zc.error("Error in active matching surveys callback",e)}};try{t&&!t.isLoaded?s([]):this.getActiveMatchingSurveys(s)}catch(e){zc.error("Error in active matching surveys callback",e)}}_getSurveyById(e){let t=null;return this.getSurveys(i=>{var s;t=null!==(s=i.find(t=>t.id===e))&&void 0!==s?s:null}),t}_checkSurveyEligibility(e){if(St(this._surveyManager))return{eligible:!1,reason:Xu};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){if(!this._configSource.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(St(this._surveyManager))return{eligible:!1,reason:Xu};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(St(this._surveyManager))return zc.warn("init was not called"),{visible:!1,disabledReason:Xu};const t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return St(this._surveyManager)?(zc.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Xu})):new Promise(i=>{this.getSurveys(t=>{var s;const r=null!==(s=t.find(t=>t.id===e))&&void 0!==s?s:null;if(r){const e=this._checkSurveyRenderability(r);i({visible:e.eligible,disabledReason:e.reason})}else i({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,i){var s;if(!this._configSource.isCapturing())return;if(St(this._surveyManager))return void zc.warn("init was not called");const r="string"==typeof e?this._getSurveyById(e):e;if(!(null==r?void 0:r.id))return void zc.warn("Survey not found");if(!Wc.includes(r.type))return void zc.warn(`Surveys of type ${r.type} cannot be rendered in the app`);const n=null==Ge?void 0:Ge.querySelector(t);if(n){if(null===(s=r.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds){zc.info(`Rendering survey ${r.id} with delay of ${r.appearance.surveyPopupDelaySeconds} seconds`);const e=setTimeout(()=>{var t,s;this._renderTimeouts.delete(e),!this._disposed&&this._configSource.isCapturing()&&(zc.info(`Rendering survey ${r.id} with delay of ${null===(t=r.appearance)||void 0===t?void 0:t.surveyPopupDelaySeconds} seconds`),null===(s=this._surveyManager)||void 0===s||s.renderSurvey(r,n,i),zc.info(`Survey ${r.id} rendered`))},1e3*r.appearance.surveyPopupDelaySeconds);return void this._renderTimeouts.add(e)}this._surveyManager.renderSurvey(r,n,i)}else zc.warn("Survey element not found")}displaySurvey(e,t){var i;if(!this._configSource.isCapturing())return;if(St(this._surveyManager))return void zc.warn("init was not called");const s=this._getSurveyById(e);if(!s)return void zc.warn("Survey not found");let r=s;if((null===(i=s.appearance)||void 0===i?void 0:i.surveyPopupDelaySeconds)&&t.ignoreDelay&&(r=ls(ls({},s),{},{appearance:ls(ls({},s.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==cl.Popover&&t.initialResponses&&zc.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){const e=this._checkSurveyEligibility(s);if(!e.eligible)return void zc.warn("Survey is not eligible to be displayed: ",e.reason)}t.displayType!==cl.Inline?this._surveyManager.handlePopoverSurvey(r,t):this.renderSurvey(r,t.selector,t.properties)}cancelPendingSurvey(e){St(this._surveyManager)?zc.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e,t;null===(e=this._surveyManager)||void 0===e||null===(t=e.handlePageUnload)||void 0===t||t.call(e)}};function id(e,t,i){if(St(e))return!1;switch(i){case"exact":return e===t;case"contains":{const i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(e)}case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}var sd=class{constructor(e){this._instance=e,this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new kc,this._checkStep=(e,t)=>this._checkStepEvent(e,t)&&this._checkStepUrl(e,t)&&this._checkStepElement(e,t)&&this._checkStepProperties(e,t),this._checkStepEvent=(e,t)=>!(null==t?void 0:t.event)||(null==e?void 0:e.event)===(null==t?void 0:t.event)}init(){var e,t;ft(null===(e=this._instance)||void 0===e?void 0:e._addCaptureHook)||(this._captureHookUnsubscribe=null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook((e,t)=>{this.on(e,t)}))}dispose(){var e,t;null===(e=this._captureHookUnsubscribe)||void 0===e||e.call(this),this._captureHookUnsubscribe=void 0,null===(t=this._instance)||void 0===t||null===(t=t.autocapture)||void 0===t||t.setElementSelectors(new Set,this),this._debugEventEmitter=new kc}register(e){var t,i;if(!ft(null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook)&&(e.forEach(e=>{var t;this._actionRegistry.add(e),null===(t=e.steps)||void 0===t||t.forEach(e=>{this._actionEvents.add((null==e?void 0:e.event)||"")})}),null===(i=this._instance)||void 0===i?void 0:i.autocapture)){const e=new Set;this._actionRegistry.forEach(t=>{var i;null===(i=t.steps)||void 0===i||i.forEach(t=>{(null==t?void 0:t.selector)&&e.add(t.selector)})}),this._instance.autocapture.setElementSelectors(e,this)}}replace(e){this._actionRegistry.clear(),this._actionEvents.clear(),this.register(e)}on(e,t){null!=t&&0!=e.length&&(this._actionEvents.has(e)||this._actionEvents.has(t.event))&&this._actionRegistry.forEach(e=>{this._checkAction(t,e)&&this._debugEventEmitter.emit("actionCaptured",e.name)})}_addActionHook(e){this.onAction("actionCaptured",t=>e(t))}_checkAction(e,t){if(null==(null==t?void 0:t.steps))return!1;for(const i of t.steps)if(this._checkStep(e,i))return!0;return!1}onAction(e,t){return this._debugEventEmitter.on(e,t)}_checkStepUrl(e,t){if(null==t?void 0:t.url){var i;const s=null==e||null===(i=e.properties)||void 0===i?void 0:i.$current_url;if(!s||"string"!=typeof s)return!1;if(!id(s,t.url,t.url_matching||"contains"))return!1}return!0}_checkStepElement(e,t){return!!this._checkStepHref(e,t)&&!!this._checkStepText(e,t)&&!!this._checkStepSelector(e,t)}_checkStepHref(e,t){var i;if(!(null==t?void 0:t.href))return!0;const s=this._getElementsList(e);if(s.length>0)return s.some(e=>id(e.href,t.href,t.href_matching||"exact"));const r=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!r&&id(function(e){const t=e.match(/(?::|")href="(.*?)"/);return t?t[1]:""}(r),t.href,t.href_matching||"exact")}_checkStepText(e,t){var i;if(!(null==t?void 0:t.text))return!0;const s=this._getElementsList(e);if(s.length>0)return s.some(e=>id(e.text,t.text,t.text_matching||"exact")||id(e.$el_text,t.text,t.text_matching||"exact"));const r=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!r&&(n=function(e){const t=[],i=/(?::|")text="(.*?)"/g;let s;for(;!St(s=i.exec(e));)t.includes(s[1])||t.push(s[1]);return t}(r),o=t.text,a=t.text_matching||"exact",n.some(e=>id(e,o,a)));var n,o,a}_checkStepSelector(e,t){var i,s;if(!(null==t?void 0:t.selector))return!0;const r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$element_selectors;if(null==r?void 0:r.includes(t.selector))return!0;const n=(null==e||null===(s=e.properties)||void 0===s?void 0:s.$elements_chain)||"";if(t.selector_regex&&n)try{return new RegExp(t.selector_regex).test(n)}catch(e){return!1}return!1}_getElementsList(e){var t;return null==(null==e||null===(t=e.properties)||void 0===t?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}_checkStepProperties(e,t){return!(null==t?void 0:t.properties)||0===t.properties.length||Lc(t.properties.reduce((e,t)=>{const i=_t(t.value)?t.value.map(String):null!=t.value?[String(t.value)]:[];return e[t.key]={values:i,operator:t.operator||"exact"},e},{}),null==e?void 0:e.properties)}},rd=class{constructor(e,t){var i,s;this._pendingActivatedItems=[],this._instance=e,this._onActivationChanged=t,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map,this._sessionIdUnsubscribe=null===(i=this._instance)||void 0===i||null===(s=i.onSessionId)||void 0===s?void 0:s.call(i,e=>this._onSessionIdChanged(e))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Lc(e.propertyFilters,null==t?void 0:t.properties)}_buildEventToItemMap(e,t){const i=new Map;return e.forEach(e=>{var s;null===(s=e.conditions)||void 0===s||null===(s=s[t])||void 0===s||null===(s=s.values)||void 0===s||s.forEach(t=>{if(null==t?void 0:t.name){const s=i.get(t.name)||[];s.push(e.id),i.set(t.name,s)}})}),i}_getMatchingItems(e,t,i){const s=(i===Xa.Activation?this._eventToItems:this._cancelEventToItems).get(e);let r=[];return this._getItems(e=>{r=e.filter(e=>null==s?void 0:s.includes(e.id))}),r.filter(s=>{var r;const n=null===(r=s.conditions)||void 0===r||null===(r=r[i])||void 0===r||null===(r=r.values)||void 0===r?void 0:r.find(t=>t.name===e);return this._doesEventMatchFilter(n,t)})}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){var i;ft(null===(i=this._instance)||void 0===i?void 0:i._addCaptureHook)||(this._setupEventBasedItems(e,t),this._setupActionBasedItems(e,t))}_setupActionBasedItems(e,t){const i=e.filter(e=>{var t;return null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length});var s;if(t&&this._actionToItems.clear(),0===i.length)return void(t&&(null===(s=this._actionMatcher)||void 0===s||s.replace([])));this._actionMatcher||(this._actionMatcher=new sd(this._instance),this._actionMatcher.init(),this._actionMatcher._addActionHook(e=>this.onAction(e)));const r=[];i.forEach(e=>{var t;null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||t.values.forEach(t=>{if(r.push(t),t.name){var i;const s=null!==(i=this._actionToItems.get(t.name))&&void 0!==i?i:[];s.includes(e.id)||s.push(e.id),this._actionToItems.set(t.name,s)}})}),t?this._actionMatcher.replace(r):this._actionMatcher.register(r)}_mergeItemMaps(e,t){t.forEach((t,i)=>{var s;const r=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach(e=>{r.includes(e)||r.push(e)}),e.set(i,r)})}_setupEventBasedItems(e,t){var i,s;const r=e.filter(e=>{var t,i;return(null===(t=e.conditions)||void 0===t?void 0:t.events)&&(null===(i=e.conditions)||void 0===i||null===(i=i.events)||void 0===i||null===(i=i.values)||void 0===i?void 0:i.length)>0}),n=e.filter(e=>{var t,i;return(null===(t=e.conditions)||void 0===t?void 0:t.cancelEvents)&&(null===(i=e.conditions)||void 0===i||null===(i=i.cancelEvents)||void 0===i||null===(i=i.values)||void 0===i?void 0:i.length)>0}),o=this._buildEventToItemMap(e,Xa.Activation),a=this._buildEventToItemMap(e,Xa.Cancellation);t?(this._eventToItems=o,this._cancelEventToItems=a):(this._mergeItemMaps(this._eventToItems,o),this._mergeItemMaps(this._cancelEventToItems,a)),(0!==r.length||0!==n.length||e.some(e=>{var t;return null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||null===(t=t.values)||void 0===t?void 0:t.length}))&&(null!==(i=this._captureHookUnsubscribe)&&void 0!==i||(this._captureHookUnsubscribe=null===(s=this._instance)||void 0===s?void 0:s._addCaptureHook((e,t)=>{this.onEvent(e,t)})))}onEvent(e,t){var i,s;const r=this._getLogger(),n=(null==t||null===(i=t.properties)||void 0===i?void 0:i.$survey_id)||(null==t||null===(s=t.properties)||void 0===s?void 0:s.$product_tour_id);if(n&&this.getActivatedIds().includes(n)){const i=this._activationOutcome(e,n,t);if("consume"===i)return r.info("event consumed activated item, removing it",{event:e,itemId:n}),void this._deactivateItems([n]);if("persist"===i)return r.info("shown item promoted to persisted activation",{event:e,itemId:n}),this._persistActivation(n),void this._clearActivationTimestamps([n])}if(this._cancelEventToItems.has(e)){const i=this._getMatchingItems(e,t,Xa.Cancellation);i.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:i.map(e=>e.id)}),this._deactivateItems(i.map(e=>e.id)),i.forEach(e=>this._cancelPendingItem(e.id)))}if(!this._eventToItems.has(e))return;r.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});const o=this._getMatchingItems(e,t,Xa.Activation);this._activateItems(o.map(e=>e.id))}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){var t,i;if(0===e.length)return;const s=!!(null===(t=this._instance)||void 0===t||null===(i=t.get_session_id)||void 0===i?void 0:i.call(t)),r=[];for(const t of e)s&&this._shouldPersistArmedActivation(t)?this._persistActivation(t)&&this._recordActivationTimestamp(t):r.push(t);r.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...r])]),this._getLogger().info("updating activated items",{activatedItems:this.getActivatedIds()}),this._notifyActivationChanged()}_persistActivation(e){this._pendingActivatedItems=this._pendingActivatedItems.filter(t=>t!==e);const t=this._getPersistedActivatedIds();return!t.includes(e)&&(this._setActivatedItems([...t,e]),this._stampActivationSession(),!0)}_deactivateItems(e){const t=new Set(e);this._pendingActivatedItems=this._pendingActivatedItems.filter(e=>!t.has(e));const i=this._getRawPersistedActivatedIds(),s=i.filter(e=>!t.has(e));s.length!==i.length&&(this._setActivatedItems(s),0===s.length&&this._clearActivationSession()),this._clearActivationTimestamps(e),this._notifyActivationChanged()}_notifyActivationChanged(){try{var e;null===(e=this._onActivationChanged)||void 0===e||e.call(this)}catch(e){this._getLogger().error("Error while handling activated items change",e)}}_getRawActivationTimestamps(){var e;const t=this._getActivationTimestampsKey();if(!t)return{};const i=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[t];return i&&"object"==typeof i?i:{}}_recordActivationTimestamp(e){if(!this._getActivationTimestampsKey())return;const t=this._getRawActivationTimestamps();this._writeActivationTimestamps(ls(ls({},t),{},{[e]:Date.now()}))}_clearActivationTimestamps(e){if(!this._getActivationTimestampsKey())return;const t=this._getRawActivationTimestamps(),i={};let s=!1;for(const[r,n]of Object.entries(t))e.includes(r)?s=!0:i[r]=n;s&&(vt(i)?this._clearActivationTimestampsStore():this._writeActivationTimestamps(i))}_clearAllActivationTimestamps(){this._getActivationTimestampsKey()&&this._clearActivationTimestampsStore()}getActivationTimestamp(e){if(!this._getPersistedActivatedIds().includes(e))return;const t=this._getRawActivationTimestamps()[e];return wt(t)?t:void 0}_getRawPersistedActivatedIds(){var e;const t=this._getActivatedKey();return(null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[t])||[]}_getPersistedActivatedIds(){var e,t,i;const s=this._getRawPersistedActivatedIds();if(0===s.length)return[];const r=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.props[this._getActivatedSessionKey()],n=null===(t=this._instance)||void 0===t||null===(i=t.get_session_id)||void 0===i?void 0:i.call(t);return n&&r===n?s:[]}_stampActivationSession(){var e,t;const i=null===(e=this._instance)||void 0===e||null===(t=e.get_session_id)||void 0===t?void 0:t.call(e);i&&this._setActivatedSession(i)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){var t;const i=null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t?void 0:t.props[this._getActivatedSessionKey()];if(i&&i!==e){const e=this._getRawPersistedActivatedIds(),t=this._getRawActivationTimestamps();e.length>0&&(this._setActivatedItems([]),e.filter(e=>wt(t[e])).forEach(e=>this._cancelPendingItem(e))),this._clearActivationSession(),this._clearAllActivationTimestamps(),e.length>0&&this._notifyActivationChanged()}}getActivatedIds(){return[...new Set([...this._getPersistedActivatedIds(),...this._pendingActivatedItems])].filter(e=>!this._isItemPermanentlyIneligible(e))}dispose(){var e,t,i;null===(e=this._sessionIdUnsubscribe)||void 0===e||e.call(this),this._sessionIdUnsubscribe=void 0,null===(t=this._captureHookUnsubscribe)||void 0===t||t.call(this),this._captureHookUnsubscribe=void 0,null===(i=this._actionMatcher)||void 0===i||i.dispose(),this._actionMatcher=void 0}reset(){this._pendingActivatedItems=[],this._getRawPersistedActivatedIds().length>0&&this._setActivatedItems([]),this._clearActivationSession(),this._clearAllActivationTimestamps(),this._notifyActivationChanged()}getEventToItemsMap(){return this._eventToItems}_getActionMatcher(){return this._actionMatcher}},nd=class extends rd{constructor(e,t){super(e,t)}_getActivatedKey(){return re}_getActivatedSessionKey(){return ne}_getActivationTimestampsKey(){return oe}_writeActivationTimestamps(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated_timestamps:e})}_clearActivationTimestampsStore(){var e;null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e||e.unregister("$surveys_activated_timestamps")}_shouldPersistArmedActivation(e){var t;let i;this._getItems(t=>{i=t.find(t=>t.id===e)});const s=null==i||null===(t=i.appearance)||void 0===t?void 0:t.surveyPopupDelaySeconds;return wt(s)&&s>0}_getShownEventName(){return al.SHOWN}_getItems(e){var t;null===(t=this._instance)||void 0===t||t.getSurveys(e)}_cancelPendingItem(e){var t;null===(t=this._instance)||void 0===t||t.cancelPendingSurvey(e)}_getLogger(){return zc}_setActivatedItems(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated:e})}_setActivatedSession(e){var t;null===(t=this._instance)||void 0===t||null===(t=t.persistence)||void 0===t||t.register({$surveys_activated_session:e})}_clearActivatedSession(){var e;null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e||e.unregister("$surveys_activated_session")}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t,i){var s;if(e===al.SENT&&!1===(null==i||null===(s=i.properties)||void 0===s?void 0:s.$survey_completed))return"ignore";let r;return this._getItems(e=>{r=e.find(e=>e.id===t)}),!r||function(e){var t;return $c(e)&&!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t?void 0:t.repeatedActivation)||"always"===e.schedule}(r)?e===al.SHOWN?"consume":"ignore":e===al.SHOWN?"persist":e===al.DISMISSED||e===al.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},od=class{constructor(e){this._instance=e}initialize(){}get(e){if("string"==typeof e)return this._instance.get_property(e);const t={};for(const i of e){const e=this._instance.get_property(i);ft(e)||(t[i]=e)}return t}set(e,t){this._instance.register("string"==typeof e?{[e]:t}:e)}remove(e){"string"!=typeof e?e.forEach(e=>this._instance.unregister(e)):this._instance.unregister(e)}},ad=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=null==tt?void 0:tt.__PosthogExtensions__;if(!e)return;const{generateSurveys:t,loadExternalDependency:i}=e;return{generateSurveys:t?e=>t(this._instance,e):void 0,loadExternalDependency:i?e=>i(this._instance,"surveys",e):void 0}}createEventReceiver(e){return new nd(this._instance,e)}onMatchingConditionsChanged(e){const t=this._instance._addCaptureHook(t=>{"$pageview"!==t&&t!==al.SHOWN&&t!==al.DISMISSED&&t!==al.SENT||e()}),i=()=>e();An(je,"PHSurveyShown",i);let s=!1;const r=this._instance.onFeatureFlags(()=>{s&&e()});return s=!0,()=>{s=!1,t(),r(),null==je||je.removeEventListener("PHSurveyShown",i)}}};const ld=(null==je?void 0:je.location)?Ca(je.location.hash,"__posthog")||Ca(location.hash,"state"):null,cd="_postHogToolbarParams",ud=Cn("[Toolbar]"),dd=Cn("[FeatureFlags]"),hd=Cn("[FeatureFlags]",{debugEnabled:!0}),_d="\" failed. Feature flags didn't load in time.",pd=[502,504],gd=["click","keydown","wheel","touchstart","pointerdown"],vd="connection_error",fd=e=>{const t={};for(let i=0;e.length>i;i++)t[e[i]]=!0;return t},md=e=>{const t={};for(const[i,s]of Fn(e||{}))s&&(t[i]=s);return t};var yd=class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=dd,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._reloadingHandlers=[],this._pendingReloads=new Set,this._activeReloads=new Set,this._hasLoadedFlags=!1,this._requestInFlight=!1,this._requestGeneration=0,this._reloadingDisabled=!1,this._additionalReloadRequested=!1,this._flagsLoadedFromRemote=!1,this._staleCacheRefreshTriggered=!1,this._consecutiveStatusZeroFailures=0,this._hadUserInteraction=!1,this._onOnline=()=>{const e=this._hasStatusZeroCircuitBreakerTripped();this._consecutiveStatusZeroFailures=0,e&&this.reloadFeatureFlags()},this._refreshIfDue=()=>{var e,t;const i=this._refreshIntervalMs,s=null!==(e=this._dueRefreshIntervalMs)&&void 0!==e?e:i;ft(i)||ft(s)||this._config.remoteRequestsDisabled||!this._document||"hidden"===this._document.visibilityState||Date.now()-(null!==(t=this._lastRefreshAt)&&void 0!==t?t:0)<s||(this._dueRefreshIntervalMs=this._hadUserInteraction||!this._config.idleRefreshBackoff?i:Math.min(2*s,36e5),this._hadUserInteraction=!1,this.reloadFeatureFlags(),this._scheduleNextRefresh())},this._onUserInteraction=()=>{this._hadUserInteraction&&this._dueRefreshIntervalMs===this._refreshIntervalMs||this._resumeConfiguredInterval()},this._onVisibilityChange=()=>{var e;"visible"===(null===(e=this._document)||void 0===e?void 0:e.visibilityState)&&this._resumeConfiguredInterval()},this._configSource=e}get _crossTabPersistence(){}_onConfigUpdated(){this._client&&this._syncAutomaticRefresh()}setup(e){try{this._window=typeof window>"u"?void 0:window,this._document=typeof document>"u"?void 0:document}catch(e){this._window=void 0,this._document=void 0}return this._initializingClient=e,this._logger=e.logger.createLogger("[FeatureFlags]"),Zu(e.kv.initialize(),()=>{this._initializingClient===e&&(this._initializingClient=void 0,this._client=e,this._finishSetup(e))})}_finishSetup(e){var t;if(this._client===e)return this._window&&An(this._window,"online",this._onOnline),this._syncAutomaticRefresh(),this._dynamicProperties=e.registerDynamicEventProperties(()=>this._isCacheStale()?this._baseEventProperties:this._eventPropertiesWithFlagValues),this._crossTabPersistenceUnsubscribe=null===(t=this._crossTabPersistence)||void 0===t?void 0:t.onCrossTabFeatureFlagChange(()=>{this._clearBootstrapState(),this._rebuildEventProperties(),this._fireFeatureFlagsCallbacks()}),this._rebuildEventProperties(),this.initialize()}_resumeConfiguredInterval(){this._hadUserInteraction=!0,this._dueRefreshIntervalMs=this._refreshIntervalMs,this._refreshIfDue()}_syncAutomaticRefresh(){var e;const t=this._config.refreshIntervalMs,i=!this._config.remoteRequestsDisabled&&this._document&&!ft(t)&&t>0?t:void 0;this._config.idleRefreshBackoff||(this._dueRefreshIntervalMs=i),i!==this._refreshIntervalMs&&(this._stopAutomaticRefresh(),ft(i)||(this._refreshIntervalMs=i,this._dueRefreshIntervalMs=i,this._scheduleNextRefresh(),(null===(e=this._document)||void 0===e?void 0:e.addEventListener)&&(An(this._document,m,this._onVisibilityChange),kn(gd,e=>{An(this._document,e,this._onUserInteraction,{capture:!0})}))))}_scheduleNextRefresh(){ft(this._refreshIntervalMs)||(ft(this._refreshInterval)||clearInterval(this._refreshInterval),this._lastRefreshAt=Date.now(),this._refreshInterval=setInterval(this._refreshIfDue,this._refreshIntervalMs))}_stopAutomaticRefresh(){var e,t;ft(this._refreshInterval)||(clearInterval(this._refreshInterval),this._refreshInterval=void 0,null===(e=this._document)||void 0===e||null===(t=e.removeEventListener)||void 0===t||t.call(e,"visibilitychange",this._onVisibilityChange),kn(gd,e=>{var t,i;null===(t=this._document)||void 0===t||null===(i=t.removeEventListener)||void 0===i||i.call(t,e,this._onUserInteraction,{capture:!0})})),this._refreshIntervalMs=void 0,this._dueRefreshIntervalMs=void 0,this._hadUserInteraction=!1,this._lastRefreshAt=void 0}destroy(){this._dispose()}dispose(){this._dispose()}_dispose(){var e,t,i;this._stopAutomaticRefresh(),this._requestGeneration++,this._additionalReloadRequested=!1,this._initializingClient=void 0,this._settleReloads(this._pendingReloads,"cancelled"),this._settleReloads(this._activeReloads,"cancelled"),this._client&&(this._clearDebouncer(),null===(e=this._dynamicProperties)||void 0===e||e.dispose(),this._dynamicProperties=void 0,null===(t=this._crossTabPersistenceUnsubscribe)||void 0===t||t.call(this),this._crossTabPersistenceUnsubscribe=void 0,this._reloadingHandlers=[],null===(i=this._window)||void 0===i||i.removeEventListener("online",this._onOnline),this._client=void 0)}get _config(){return this._configSource.get()}_prop(e){var t;return this._bootstrapState&&e in this._bootstrapState?this._bootstrapState[e]:null===(t=this._client)||void 0===t?void 0:t.kv.get(e)}_clearBootstrapState(){return!!this._bootstrapState&&(this._bootstrapState=void 0,!0)}_fallBackToPersistedFlags(){var e;return!ft(null===(e=this._client)||void 0===e?void 0:e.kv.get("$enabled_feature_flags"))&&this._clearBootstrapState()}_set(e){this._persist(()=>{var t;return null===(t=this._client)||void 0===t?void 0:t.kv.set(e)})}_markCrossTabFeatureFlagSnapshot(e,t,i){if(!this._crossTabPersistence||!e.$enabled_feature_flags)return;const s=this._prop("$enabled_feature_flags")||{},o=e.$enabled_feature_flags||{},d=t.flags||t.featureFlags,h=t.flags?Object.entries(t.flags).filter(([,e])=>!(null==e?void 0:e.failed)).map(([e])=>e):[],_=!!t.errorsWhileComputingFlags&&!!t.flags,p=_?h:i&&!_t(d)?Object.keys(d||{}):Array.from(new Set([...Object.keys(s),...Object.keys(o)])),v=this._prop("$feature_flag_payloads")||{},f=e.$feature_flag_payloads||{},m=_||i?p:Array.from(new Set([...Object.keys(v),...Object.keys(f)])),y=!_&&!i,b=!!y||p,S=!!y||m,w={[r]:b,[u]:b,[g]:S};e.$feature_flag_details&&(w[n]=b);for(const t of[l,a,c])ft(e[t])||(w[t]=!0);this._crossTabPersistence.markCrossTabFeatureFlagChanges(w)}_remove(e){this._persist(()=>{var t;return null===(t=this._client)||void 0===t?void 0:t.kv.remove(e)})}_persist(e){try{e()}catch(e){this._logger.error("Failed to update feature flag persistence",e)}}_rebuildEventProperties(){const e={};for(const t of[r,g,l,v]){const i=this._prop(t);ft(i)||(e[t]=i)}this._baseEventProperties=e;const t=ls({},e),i=this._prop(u);if(i)for(const[e,s]of Object.entries(i))t[`$feature/${e}`]=s;this._eventPropertiesWithFlagValues=t}_isCacheStale(){const e=this._config.cacheTtlMs;if(!e||0>=e)return!1;const t=this._prop(a);return"number"!=typeof t||Date.now()-t>e}_checkAndTriggerStaleRefresh(){return!!this._isCacheStale()&&(this._staleCacheRefreshTriggered||this._requestInFlight||(this._staleCacheRefreshTriggered=!0,this._logger.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_getValidEvaluationEnvironments(){const e=this._config.evaluationContexts;return(null==e?void 0:e.length)?e.filter(e=>{const t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid evaluation context found:",e,"Expected non-empty string"),t}):[]}_getValidFlagKeys(){const e=this._config.flagKeys;if(!ft(e))return e.filter(e=>{const t=e&&"string"==typeof e&&e.trim().length>0;return t||this._logger.error("Invalid flag key found:",e,"Expected non-empty string"),t})}initialize(){var e,t;const i=this._config,s=null!==(e=null===(t=i.bootstrap)||void 0===t?void 0:t.featureFlags)&&void 0!==e?e:{};if(Object.keys(s).length){var r,n;const e=null!==(r=null===(n=i.bootstrap)||void 0===n?void 0:n.featureFlagPayloads)&&void 0!==r?r:{},t=Object.keys(s).filter(e=>!ft(s[e])).reduce((e,t)=>(e[t]=s[t],e),{}),o=Object.keys(e).filter(e=>t[e]).reduce((t,i)=>(t[i]=e[i],t),{});return this._receivedFeatureFlags({featureFlags:t,featureFlagPayloads:o},void 0,{persist:!1})}}updateFlags(e,t,i){var s,r;const n=(null==i?void 0:i.merge)&&null!==(s=this._prop("$enabled_feature_flags"))&&void 0!==s?s:{},o=(null==i?void 0:i.merge)&&null!==(r=this._prop("$feature_flag_payloads"))&&void 0!==r?r:{},a=ls(ls({},n),e),l=ls(ls({},o),t),c={};for(const[e,t]of Object.entries(a))c[e]={key:e,enabled:tr(t),variant:ir(t),reason:void 0,metadata:ft(null==l?void 0:l[e])?void 0:{id:0,version:void 0,description:void 0,payload:l[e]}};this._receivedFeatureFlags({flags:c})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this._prop(n),t=this._prop(v),i=this._prop(f);if(!i&&!t)return e||{};const s=xn({},e||{}),r=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(const e of r){var o,a;const r=s[e],n=null==t?void 0:t[e],l=ft(n)?null!==(o=null==r?void 0:r.enabled)&&void 0!==o&&o:!!n,c=ft(n)?null==r?void 0:r.variant:"string"==typeof n?n:void 0,u=null==i?void 0:i[e],d=ls(ls({},r),{},{enabled:l,variant:l?null!=c?c:null==r?void 0:r.variant:void 0});l!==(null==r?void 0:r.enabled)&&(d.original_enabled=null==r?void 0:r.enabled),c!==(null==r?void 0:r.variant)&&(d.original_variant=null==r?void 0:r.variant),u&&(d.metadata=ls(ls({},null==r?void 0:r.metadata),{},{payload:u,original_payload:null==r||null===(a=r.metadata)||void 0===a?void 0:a.payload})),s[e]=d}return this._override_warning||(this._logger.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:s}),this._override_warning=!0),s}getAllFeatureFlags(){const e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map(i=>{const s=e[i];return{key:i,enabled:tr(s),variant:ir(s),payload:er(t[i])}})}getFlagVariants(){const e=this._prop(u),t=this._prop(v);if(!t)return e||{};const i=xn({},e||{}),s=Object.keys(t);for(let e=0;s.length>e;e++)i[s[e]]=t[s[e]];return this._override_warning||(this._logger.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this._override_warning=!0),i}getFlagPayloads(){const e=this._prop(g),t=this._prop(f);if(!t)return e||{};const i=xn({},e||{}),s=Object.keys(t);for(let e=0;s.length>e;e++)i[s[e]]=t[s[e]];return this._override_warning||(this._logger.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this._override_warning=!0),i}reloadFeatureFlags(){this._reloadingDisabled||this._config.featureFlagsDisabled||this._hasStatusZeroCircuitBreakerTripped()||(this._requestInFlight&&(this._additionalReloadRequested=!0),this._reloadDebouncer||(this._reloadingHandlers.slice().forEach(e=>{try{e()}catch(e){this._logger.error("Error while running feature flags reloading callback",e)}}),this._reloadDebouncer=setTimeout(()=>{this._callFlagsEndpoint()},5)))}reloadFeatureFlagsAsync(){return!this._client||this._reloadingDisabled||this._config.featureFlagsDisabled||this._config.remoteRequestsDisabled||this._hasStatusZeroCircuitBreakerTripped()?Promise.resolve({status:"skipped"}):new Promise(e=>{this._pendingReloads.add(e),this.reloadFeatureFlags()})}_settleReloads(e,t){e.forEach(e=>e({status:t})),e.clear()}_clearDebouncer(){clearTimeout(this._reloadDebouncer),this._reloadDebouncer=void 0}onReloading(e){return this._reloadingHandlers.push(e),()=>{this._reloadingHandlers=this._reloadingHandlers.filter(t=>t!==e)}}ensureFlagsLoaded(){this._hasLoadedFlags||this._requestInFlight||this._reloadDebouncer||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this._reloadingDisabled=e}resetFlagCallReported(){this._remove(_)}_callFlagsEndpoint(e){var t;this._clearDebouncer();const i=this._client;if(!i||this._config.remoteRequestsDisabled||this._hasStatusZeroCircuitBreakerTripped())return void this._settleReloads(this._pendingReloads,"skipped");if(this._requestInFlight)return void(this._additionalReloadRequested=!0);const s={token:i.projectToken,distinct_id:i.distinctId,groups:i.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:ls(ls(ls({},i.initialPersonProperties),this._prop("$stored_person_properties")||{}),{},{$lib:i.library.name,$lib_version:i.library.version}),group_properties:this._prop(d),timezone:va()};ft(i.deviceId)||(s.$device_id=i.deviceId),((null==e?void 0:e.disableFlags)||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);const r=this._getValidEvaluationEnvironments();r.length&&(s.evaluation_contexts=r);const n=this._getValidFlagKeys();ft(n)||(s.flag_keys=n);const a=this._config.onlyEvaluateSurveyFeatureFlags,l="/flags/?v=2"+(a?"&only_evaluate_survey_feature_flags=true":""),c=this._requestGeneration,u=this._pendingReloads;this._pendingReloads=new Set,this._activeReloads=u,this._requestInFlight=!0;const h=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},_=e=>{var t,i;const r=null!==(t=e.json)&&void 0!==t?t:{},n=200!==e.statusCode;if(this._requestInFlight=!1,c!==this._requestGeneration)return void h();if(this._trackStatusZeroReachability(e.statusCode),n||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),s.disable_flags&&!this._additionalReloadRequested)return void this._settleReloads(u,"skipped");this._flagsLoadedFromRemote=!n;const l=[];e.error?l.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?vd:"unknown_error"):200!==e.statusCode&&l.push(`api_error_${e.statusCode}`),r.errorsWhileComputingFlags&&l.push("errors_while_computing_flags");const d=!!(null===(i=r.quotaLimited)||void 0===i?void 0:i.includes("feature_flags"));d&&l.push("quota_limited"),this._set({[o]:l}),d?this._logger.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this._receivedFeatureFlags(r,n,{partialResponse:a}),this._settleReloads(u,s.disable_flags?"skipped":l.length||!r.flags&&!r.featureFlags?"error":"loaded"),h()},p=e=>{this._requestInFlight=!1,c===this._requestGeneration?(this._set({[o]:[vd]}),this._logger.error("Feature flag request failed",e),this._fallBackToPersistedFlags()&&this._fireFeatureFlagsCallbacks(!0),this._settleReloads(u,"error"),h()):h()};let g=null!==(t=this._config.requestMaxRetries)&&void 0!==t?t:1;const v=()=>g>0&&c===this._requestGeneration,f=()=>{if(c!==this._requestGeneration||!this._client||this._config.remoteRequestsDisabled)return this._requestInFlight=!1,this._settleReloads(u,"skipped"),void h();try{i.sendRequest(l,{target:"flags",method:"POST",body:s,compression:this._config.compression,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then(e=>{if((e=>pd.includes(e.statusCode)||(e=>0===e.statusCode&&e.error instanceof Error&&"AbortError"===e.error.name)(e))(e)&&v())return g--,void setTimeout(f,500);_(e)}).catch(p)}catch(e){p(e)}};f()}_hasStatusZeroCircuitBreakerTripped(){return ma(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=ya(e,this._consecutiveStatusZeroFailures,3,()=>this._logger.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(e,t={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return void this._logger.warn('getFeatureFlag for key "'+e+_d);if(this._checkAndTriggerStaleRefresh())return;const s=this.getFeatureFlagResult(e,t);return null!==(i=null==s?void 0:s.variant)&&void 0!==i?i:null==s?void 0:s.enabled}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){const t=this.getFeatureFlagResult(e,{send_event:!1});return null==t?void 0:t.payload}getFeatureFlagResult(e,t={}){if(t.fresh&&!this._flagsLoadedFromRemote)return;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return void this._logger.warn('getFeatureFlagResult for key "'+e+_d);if(this._checkAndTriggerStaleRefresh())return;const i=this.getFlagVariants(),s=e in i,r=i[e],n=this.getFlagPayloads()[e],o=String(r),a=this._prop("$feature_flag_request_id")||void 0,l=this._prop("$feature_flag_evaluated_at")||void 0;let c,u=this._prop("$flag_call_reported")||{};if(this._config.deduplicateCallsPerSession){var d;const e=null===(d=this._client)||void 0===d||null===(d=d.session)||void 0===d?void 0:d.sessionId,t=this._prop(p);e&&e!==t&&(u={},c=e)}if(!t.send_event&&"send_event"in t)c&&this._set({[_]:u,[p]:c});else if(e in u&&u[e].includes(o))c&&this._set({[_]:u,[p]:c});else{var h,g,v,f,m,y,b,S,w,E,C,k,P;_t(u[e])?u[e].push(o):u[e]=[o],this._set(ls({[_]:u},c?{[p]:c}:{}));const t=this.getFeatureFlagDetails(e),i=[...null!==(h=this._prop("$feature_flag_errors"))&&void 0!==h?h:[]];ft(r)&&i.push("flag_missing");const s={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:null!=n?n:null,$feature_flag_request_id:a,$feature_flag_evaluated_at:l,$feature_flag_bootstrapped_response:null!==(g=null===(v=this._config.bootstrap)||void 0===v||null===(v=v.featureFlags)||void 0===v?void 0:v[e])&&void 0!==g?g:null,$feature_flag_bootstrapped_payload:null!==(f=null===(m=this._config.bootstrap)||void 0===m||null===(m=m.featureFlagPayloads)||void 0===m?void 0:m[e])&&void 0!==f?f:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};ft(null==t||null===(y=t.metadata)||void 0===y?void 0:y.has_experiment)||(s.$feature_flag_has_experiment=t.metadata.has_experiment),ft(null==t||null===(b=t.metadata)||void 0===b?void 0:b.version)||(s.$feature_flag_version=t.metadata.version);const d=null!==(S=null==t||null===(w=t.reason)||void 0===w?void 0:w.description)&&void 0!==S?S:null==t||null===(E=t.reason)||void 0===E?void 0:E.code;d&&(s.$feature_flag_reason=d),(null==t||null===(C=t.metadata)||void 0===C?void 0:C.id)&&(s.$feature_flag_id=t.metadata.id),ft(null==t?void 0:t.original_variant)&&ft(null==t?void 0:t.original_enabled)||(s.$feature_flag_original_response=ft(t.original_variant)?t.original_enabled:t.original_variant),(null==t||null===(k=t.metadata)||void 0===k?void 0:k.original_payload)&&(s.$feature_flag_original_payload=null==t||null===(P=t.metadata)||void 0===P?void 0:P.original_payload),i.length&&(s.$feature_flag_error=i.join(",")),this._captureFeatureFlagCalled(s)}return s?{key:e,enabled:!!r,variant:"string"==typeof r?r:void 0,payload:er(n)}:void 0}_captureFeatureFlagCalled(e){try{var t;null===(t=this._client)||void 0===t||t.capture("$feature_flag_called",e)}catch(e){this._logger.error("Failed to capture feature flag call",e)}}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,t){var i=this;return Lt(function*(){const s=i._client;if(!s)return;const r={distinct_id:s.distinctId,token:s.projectToken,person_properties:{$lib:s.library.name,$lib_version:s.library.version}},n=i._getValidEvaluationEnvironments();n.length&&(r.evaluation_contexts=n);const o=i._getValidFlagKeys();let a;ft(o)||(r.flag_keys=o);try{var l;const t=null===(l=(yield s.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:i._config.compression,sentAt:"body",timeoutMs:i._config.requestTimeoutMs})).json)||void 0===l?void 0:l.featureFlagPayloads;a=(null==t?void 0:t[e])||void 0}catch(e){return void i._logger.error("Remote config feature flag request failed",e)}try{t(a)}catch(e){i._logger.error("Remote config feature flag callback failed",e)}})()}isFeatureEnabled(e,t={}){if(t.fresh&&!this._flagsLoadedFromRemote)return t.defaultValue;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return this._logger.warn('isFeatureEnabled for key "'+e+_d),t.defaultValue;const i=this.getFeatureFlag(e,t);return ft(i)?t.defaultValue:!!i}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,i){this._receivedFeatureFlags(e,t,i)}_receivedFeatureFlags(e,t,i){if(!this._client)return;this._hasLoadedFlags=!0;const s=((e,t={},i={},s={},o,d=dd)=>{const h=((e,t)=>{const i=e.flags;if(i){const t=Object.fromEntries(Object.keys(i).map(e=>{var t;return[e,null!==(t=i[e].variant)&&void 0!==t?t:i[e].enabled]})),s=Object.fromEntries(Object.keys(i).filter(e=>i[e].enabled).filter(e=>{var t;return!ft(null===(t=i[e].metadata)||void 0===t?void 0:t.payload)}).map(e=>{var t;return[e,null===(t=i[e].metadata)||void 0===t?void 0:t.payload]}));return ls(ls({},e),{},{featureFlags:t,featureFlagPayloads:s})}return e.featureFlags&&t.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e})(e,d),_=h.flags,p=h.featureFlags,v=h.featureFlagPayloads;if(!p)return;const f=e.requestId,m=e.evaluatedAt;if(_t(p)){d.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const e={};if(p)for(let t=0;p.length>t;t++)e[p[t]]=!0;return{[r]:p,[u]:e,[c]:!1}}let y=p,b=v,S=_;if(null==o?void 0:o.partialResponse){const e=Object.keys(y),r=b||{};y=ls(ls({},t),y),b=ls(ls({},i),r),e.forEach(e=>{e in r||null==b||delete b[e]}),S=ls(ls({},s),S)}else if(e.errorsWhileComputingFlags)if(_){const e=new Set(Object.keys(_).filter(e=>{var t;return!(null===(t=_[e])||void 0===t?void 0:t.failed)}));y=ls(ls({},t),Object.fromEntries(Object.entries(y).filter(([t])=>e.has(t))));const r=Object.fromEntries(Object.entries(b||{}).filter(([t])=>e.has(t)));b=ls(ls({},i),r),e.forEach(e=>{e in r||null==b||delete b[e]}),S=ls(ls({},s),Object.fromEntries(Object.entries(S||{}).filter(([t])=>e.has(t))))}else y=ls(ls({},t),y),b=ls(ls({},i),b),S=ls(ls({},s),S);return ls(ls({[r]:Object.keys(md(y)),[u]:y||{},[g]:b||{},[n]:S||{},[c]:!0===e.minimalFlagCalledEvents},f?{[l]:f}:{}),m?{[a]:m}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),i,this._logger);if(s)if(!1===(null==i?void 0:i.persist)){const e=!ft(this._client.kv.get(u));this._bootstrapState=s,e||this._set(s)}else this._clearBootstrapState(),this._markCrossTabFeatureFlagSnapshot(s,e,!!(null==i?void 0:i.partialResponse)),this._set(s);else t&&this._fallBackToPersistedFlags();t||(this._staleCacheRefreshTriggered=!1),this._fireFeatureFlagsCallbacks(t)}override(e,t=!1){this._logger.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this._overrideFeatureFlags(e)}_overrideFeatureFlags(e){if(this._client){if(!1===e)return this._remove([v,f]),this._fireFeatureFlagsCallbacks(),void hd.info("All overrides cleared");if(_t(e))return this._set({[v]:fd(e)}),this._fireFeatureFlagsCallbacks(),void hd.info("Flag overrides set",{flags:e});if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t;const i=e;this._override_warning=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t);const s={},r=i.flags,n=i.payloads;return r&&(s[v]=_t(r)?fd(r):r),n&&(s[f]=n),Object.keys(s).length&&this._set(s),!1===r&&!1===n?this._remove([v,f]):!1===r?this._remove(v):!1===n&&this._remove(f),this._fireFeatureFlagsCallbacks(),!1===r?hd.info("Flag overrides cleared"):r&&hd.info("Flag overrides set",{flags:r}),void(!1===n?hd.info("Payload overrides cleared"):n&&hd.info("Payload overrides set",{payloads:n}))}if(e&&"object"==typeof e)return this._set({[v]:e}),this._fireFeatureFlagsCallbacks(),void hd.info("Flag overrides set",{flags:e});this._logger.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this._logger.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this._hasLoadedFlags){const{flags:t,flagVariants:i}=this._prepareFeatureFlagsForCallbacks();try{e(t,i)}catch(e){this._logger.error("Error while running feature flags callback",e)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;const n=(this._prop("$early_access_features")||[]).find(t=>t.flagKey===e),o={[`$feature_enrollment/${e}`]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};n&&(a.$early_access_feature_name=n.name),i&&(a.$feature_enrollment_stage=i);const l=ls(ls({},this.getFlagVariants()),{},{[e]:t});null===(s=this._crossTabPersistence)||void 0===s||s.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(o)}),this._set({[r]:Object.keys(md(l)),[u]:l,[h]:ls(ls({},this._prop("$stored_person_properties")||{}),o)}),this._fireFeatureFlagsCallbacks();try{var c;null===(c=this._client)||void 0===c||c.capture("$feature_enrollment_update",a)}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t=!1,i){const r=this._prop(s);!r||t?this._getEarlyAccessFeatures(e,i):e(r)}_getEarlyAccessFeatures(e,t){var i=this;return Lt(function*(){const r=i._client;if(!r)return;const n=t?`&${t.map(e=>`stage=${e}`).join("&")}`:"";let o;try{const e=yield r.sendRequest(`/api/early_access_features/?token=${r.projectToken}${n}`,{target:"api",method:"GET",sentAt:"query"});if(!e.json)return;o=e.json.earlyAccessFeatures,i._set({[s]:o})}catch(e){return void i._logger.error("Early access feature request failed",e)}try{e(o)}catch(e){i._logger.error("Early access feature callback failed",e)}})()}_prepareFeatureFlagsForCallbacks(){const e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(e=>t[e]),flagVariants:Object.keys(t).filter(e=>t[e]).reduce((e,i)=>(e[i]=t[i],e),{})}}_fireFeatureFlagsCallbacks(e){this._rebuildEventProperties();const{flags:t,flagVariants:i}=this._prepareFeatureFlagsForCallbacks();this.featureFlagEventHandlers.forEach(s=>{try{s(t,i,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}})}setPersonPropertiesForFlags(e,t=!0){this._setPersonPropertiesForFlags(e,t)}_setPersonPropertiesForFlags(e,t=!0){const i=this._prop("$stored_person_properties")||{},s=(null==e?void 0:e.$set)||((null==e?void 0:e.$set_once)?{}:e),r=null==e?void 0:e.$set_once,n={};if(r)for(const e in r)({}).hasOwnProperty.call(r,e)&&(e in i||(n[e]=r[e]));this._set({[h]:ls(ls(ls({},i),n),s)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const i=ls({},this._prop("$stored_person_properties")||{});e.forEach(e=>{delete i[e]}),this._set({[h]:i}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this._remove(h),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t=!0){const i=this._prop("$stored_group_properties")||{},s=ls({},i);for(const t of Object.keys(e))s[t]=ls(ls({},i[t]),e[t]);this._set({[d]:s}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this._prop("$stored_group_properties")||{};this._set({[d]:ls(ls({},t),{},{[e]:{}})})}else this._remove(d)}reset(){this._requestGeneration++,this._settleReloads(this._pendingReloads,"cancelled"),this._settleReloads(this._activeReloads,"cancelled"),this._additionalReloadRequested=!1,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._bootstrapState=void 0,this._hasLoadedFlags=!1,this._reloadingDisabled=!1,this._flagsLoadedFromRemote=!1,this.$anon_distinct_id=void 0,this._clearDebouncer(),this._override_warning=!1,this._consecutiveStatusZeroFailures=0}};const bd=Cn("[FeatureFlags]");var Sd=class{constructor(e,t=!1){this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,r,n,o,a,l,c;return{bootstrap:{featureFlags:null!==(i=null===(s=e.bootstrap)||void 0===s?void 0:s.featureFlags)&&void 0!==i?i:void 0,featureFlagPayloads:null!==(r=null===(n=e.bootstrap)||void 0===n?void 0:n.featureFlagPayloads)&&void 0!==r?r:void 0},remoteRequestsDisabled:t,featureFlagsDisabled:!!e.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!e.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!e.advanced_feature_flags_dedup_per_session,cacheTtlMs:e.feature_flag_cache_ttl_ms,refreshIntervalMs:null!==(o=e.remote_config_refresh_interval_ms)&&void 0!==o?o:3e5,idleRefreshBackoff:ft(e.remote_config_refresh_interval_ms),requestTimeoutMs:e.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,null!==(a=e.feature_flag_request_max_retries)&&void 0!==a?a:1),compression:e.disable_compression?void 0:"best-available",evaluationContexts:null!==(l=null!==(c=e.evaluation_contexts)&&void 0!==c?c:e.evaluation_environments)&&void 0!==l?l:[],flagKeys:_t(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(bd.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),ft(e.flag_keys)||_t(e.flag_keys)||bd.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}};const wd=e=>It(e)&&("RangeError"===e.name&&0===e.message.indexOf("Maximum call stack size exceeded")||"InternalError"===e.name&&"too much recursion"===e.message),Ed=Cn("[Error tracking]"),Cd="webkit-masked-url:",kd=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],Pd=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",Cd],xd=["__firefox__","__gCrWeb"],Fd="Refusing to render web experiment since the viewer is a likely bot",Id={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Mc(t,e),not_regex:(e,t)=>!Mc(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},Td=Cn("[Conversations]"),Rd="Conversations not available yet.";function $d(e,t){var i,s,r,n,o,a,l;const c=null!==(i=null==e?void 0:e.flushIntervalMs)&&void 0!==i?i:3e3,u=null!==(s=null==e?void 0:e.maxBufferSize)&&void 0!==s?s:100,d=(null==t?void 0:t.consoleCapture)?void 0:null!==(r=null==e?void 0:e.maxLogsPerInterval)&&void 0!==r?r:1e3,h=ft(d)?Math.max(u,2048):Math.max(u,d),_=ls(ls({},function(){let e="",t="";try{var i;const s="u">typeof globalThis?globalThis:"u">typeof window?window:void 0,r=null==s||null===(i=s.navigator)||void 0===i?void 0:i.userAgent;r&&([e,t]=qi(r))}catch(e){}return function(e,t){const i=function(e){if(e)return{}.hasOwnProperty.call(an,e)?an[e]:e}(e);return ls(ls({},i?{"os.name":i}:{}),t?{"os.version":t}:{})}(e,t)}()),null==e?void 0:e.resourceAttributes);return{serviceName:null!==(n=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==n?n:null==t?void 0:t.serviceNameDefault,serviceVersion:null!==(a=null==_?void 0:_["service.version"])&&void 0!==a?a:null==e?void 0:e.serviceVersion,environment:null!==(l=null==_?void 0:_["deployment.environment"])&&void 0!==l?l:null==e?void 0:e.environment,resourceAttributes:_,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:c,maxBufferSize:u,maxQueueSize:h,maxBatchRecordsPerPost:100,rateCapWindowMs:c,maxLogsPerInterval:d,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}const Md=["debug","log","warn","error","info"],Ad=e=>{for(;null==e?void 0:e.__rrweb_original__;)e=e.__rrweb_original__;return e},Od="console",Ld="__posthogHandledLogsRequestError",Dd=(e,t)=>{const i=e instanceof Error?e:new Error(t);return i[Ld]=!0,i},Nd=e=>!!e&&"object"==typeof e&&!0===e[Ld];var Bd=class{get _coreLogger(){return ls(ls({},this._logger),{},{error:(...e)=>{e.some(Nd)||this._logger.error(...e)}})}constructor(e,t){var i;this._configSource=e,this._getSdkContext=t,this.name="logs",this._isLogsEnabled=!1,this._isLoaded=!1,this._isLoading=!1,this._logger=Cn("[logs]"),this._queue=[],this._consoleQueue=[],this._consecutiveStatusZeroFailures=0,this._setupStarted=!1,this._disposed=!1,this._consoleBuffer=[],this._consoleRecorderUnpatchers=[],this._isRecordingConsole=!1,this._isRecordingConsoleEntry=!1,this._listeningForReconnect=!1,this._onReconnect=()=>{var e,t;this._disposed||(this._consecutiveStatusZeroFailures=0,null===(e=this._core)||void 0===e||e.onReconnect(),null===(t=this._consoleCore)||void 0===t||t.onReconnect())},this._isLogsEnabled=!!(null===(i=e.get())||void 0===i?void 0:i.captureConsoleLogs)}get _isRequestReady(){return!0}_getConsoleLoader(){}_listenForReconnect(){if(!this._listeningForReconnect){try{this._window=typeof window>"u"?void 0:window}catch(e){this._window=void 0}this._window&&(An(this._window,"online",this._onReconnect),this._listeningForReconnect=!0)}}_buildCore(e,t,i,s){this._listenForReconnect();const r=$d(this._configSource.get(),i);return[new fn(this._createHost(e,t),r,this._coreLogger,()=>this._getSdkContext(),e=>e(),void 0,s),r]}_getCore(){const e=this._configSource.get();var t;return this._core&&this._resolvedFrom===e||(null===(t=this._core)||void 0===t||t.reset(),this._resolvedFrom=e,[this._core,this._resolvedConfig]=this._buildCore(()=>this._queue,e=>{this._queue=e})),this._core}_getConsoleCore(){const e=this._configSource.get();var t;return this._consoleCore&&this._consoleResolvedFrom===e||(null===(t=this._consoleCore)||void 0===t||t.reset(),this._consoleResolvedFrom=e,[this._consoleCore,this._consoleResolvedConfig]=this._buildCore(()=>this._consoleQueue,e=>{this._consoleQueue=e},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Od)),this._consoleCore}setup(e){if(!this._disposed&&!this._setupStarted)return this._setupStarted=!0,this._client=e,this._logger=e.logger.createLogger("[logs]"),Zu(e.kv.initialize(),()=>{this._disposed||this._finishSetup(e)})}_finishSetup(e){var t;this._listenForReconnect(),(null===(t=this._configSource.get())||void 0===t?void 0:t.captureConsoleLogs)&&(this._isLogsEnabled=!0),(this._isLogsEnabled||this._configSource.remoteConfigWillArrive&&e.kv.get(this._configSource.captureHintKey))&&this._startConsoleRecorder();let i=!1;const s=e.onRemoteConfig(e=>{var t;i=e.ok&&!0===(null===(t=e.config.logs)||void 0===t?void 0:t.captureConsoleLogs),this.onRemoteConfig(e)});this._disposed?s.dispose():(this._remoteConfigSubscription=s,i||this.loadIfEnabled())}dispose(){var e,t,i,s,r,n,o;this._disposed||(this._disposed=!0,this._stopConsoleRecorder(),null===(e=this._remoteConfigSubscription)||void 0===e||e.dispose(),this._remoteConfigSubscription=void 0,this._client=void 0,this._isLoading=!1,null===(t=this._window)||void 0===t||t.removeEventListener("online",this._onReconnect),null===(i=this._consoleLogsDispose)||void 0===i||i.call(this),this._consoleLogsDispose=void 0,null===(s=this._core)||void 0===s||s.clearQueue(),null===(r=this._consoleCore)||void 0===r||r.clearQueue(),null===(n=this._core)||void 0===n||n.reset(),null===(o=this._consoleCore)||void 0===o||o.reset())}onRemoteConfig(e){var t,i;if(this._disposed)return;const s=e.ok?null===(t=e.config.logs)||void 0===t?void 0:t.captureConsoleLogs:void 0;St(s)?this._stopRecorderStartedByPersistedHint():(null===(i=this._client)||void 0===i||i.kv.set(this._configSource.captureHintKey,!!s),s?(this._isLogsEnabled=!0,this._isLoaded||this._startConsoleRecorder(),this.loadIfEnabled()):this._stopRecorderStartedByPersistedHint())}reset(){var e,t,i,s;this._stopConsoleRecorder(),null===(e=this._core)||void 0===e||e.clearQueue(),this._queue=[],null===(t=this._core)||void 0===t||t.reset(),null===(i=this._consoleCore)||void 0===i||i.clearQueue(),this._consoleQueue=[],null===(s=this._consoleCore)||void 0===s||s.reset(),this._consecutiveStatusZeroFailures=0}captureLog(e){!this._disposed&&this._client&&this._getCore().captureLog(e)}captureConsoleLog(e){!this._disposed&&this._client&&this._getConsoleCore().captureLog(e)}captureBufferedConsoleLog(e,t,i){!this._disposed&&this._client&&this._getConsoleCore().captureLog(e,{context:t,occurredAtMs:i})}_onOptOut(){var e;this._stopConsoleRecorder(),null===(e=this._consoleCore)||void 0===e||e.clearQueue(),this._consoleQueue=[]}_stopRecorderStartedByPersistedHint(){this._isLogsEnabled||this._stopConsoleRecorder()}_startConsoleRecorder(){var e;if(this._isRecordingConsole||!(null===(e=this._window)||void 0===e?void 0:e.console))return;const t=$d(this._configSource.get()).maxBufferSize;let i=!0;this._consoleRecorderUnpatchers.push(()=>{i=!1});for(const e of Md){let s;try{s=Ad(this._window.console[e])}catch(e){continue}s&&this._consoleRecorderUnpatchers.push(Au(this._window.console,e,r=>{const n=(...s)=>{try{i&&this._recordConsoleEntry(e,s,t)}catch(e){}return r.apply(this._window.console,s)};return n.__rrweb_original__=s,n}))}this._isRecordingConsole=!0,this._consoleRecorderTimeout=setTimeout(()=>{this._stopConsoleRecorder()},3e4)}_recordConsoleEntry(e,t,i){var s;if(this._isRecordingConsole&&!this._isRecordingConsoleEntry&&0!==t.length)if(null===(s=this._client)||void 0===s?void 0:s.canCapture){if(i>this._consoleBuffer.length){this._isRecordingConsoleEntry=!0;try{this._consoleBuffer.push({level:e,args:t,occurredAtMs:Date.now(),context:this._getSdkContext()})}finally{this._isRecordingConsoleEntry=!1}}}else this._stopConsoleRecorder()}_stopConsoleRecorder(){if(this._consoleBuffer=[],this._isRecordingConsole){this._isRecordingConsole=!1,this._consoleRecorderTimeout&&(clearTimeout(this._consoleRecorderTimeout),this._consoleRecorderTimeout=void 0);for(const e of this._consoleRecorderUnpatchers)e();this._consoleRecorderUnpatchers=[]}}_takeConsoleBuffer(){const e=this._consoleBuffer;return this._stopConsoleRecorder(),e}get logger(){return this._capture_logger||(this._capture_logger={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this._capture_logger}flushLogs(e){this._client&&(e?this._flushViaTransport(e):(this._core&&this._core.flush().catch(e=>this._logFlushError(e)),this._consoleCore&&this._consoleCore.flush().catch(e=>this._logFlushError(e))))}flush(){var e=this;return Lt(function*(){var t,i;const s=null===(t=e._core)||void 0===t?void 0:t.flush().catch(t=>e._logFlushError(t)),r=null===(i=e._consoleCore)||void 0===i?void 0:i.flush().catch(t=>e._logFlushError(t));yield s,yield r})()}_logFlushError(e){Nd(e)||this._logger.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this._disposed||!this._isLogsEnabled||this._isLoaded||this._isLoading)return;const e=this._getConsoleLoader();if(e){this._isLoading=!0;try{e((e,t)=>{if(this._isLoading=!1,!this._disposed&&this._isLogsEnabled)if(e||!t)this._logger.error("Could not load logs script",e),this._stopConsoleRecorder();else{const e=this._takeConsoleBuffer();this._consoleLogsDispose=t.initialize(this._client),this._isLoaded=!0,e.length>0&&t.replay(this._client,e)}})}catch(e){throw this._isLoading=!1,e}}else this._stopConsoleRecorder()}_createHost(e,t){const i=this._client;return{get isDisabled(){return!1},get optedOut(){return!i.canCapture},getPersistedProperty:t=>t===it.LogsQueue?e():void 0,setPersistedProperty(e,i){e===it.LogsQueue&&t(null!=i?i:[])},_sendLogsBatch:e=>this._sendLogsBatch(e),getLibraryId:()=>i.library.name,getLibraryVersion:()=>i.library.version}}_sendLogsBatch(e){return new Promise(t=>{if(ma(this._consecutiveStatusZeroFailures,3))return void t({kind:"fatal",error:Dd(void 0,"logs endpoint is unreachable, dropping batch")});let i=!1;const s=e=>{i||(i=!0,clearTimeout(r),t(e))},r=setTimeout(()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:Dd(void 0,"logs request timed out")})},9e4),n=this._isRequestReady;this._client.sendRequest("/i/v1/logs",{method:"POST",query:{token:this._client.projectToken},body:e,compression:"best-available",timeoutMs:6e4}).then(e=>{var t;const i=e.statusCode;this._trackEndpointReachability(i,n),i>=200&&300>i?s({kind:"ok"}):413===i?s({kind:"too-large"}):0!==i&&408!==i&&429!==i&&500>i?s({kind:"fatal",error:new Error(`logs request failed with status ${i}`)}):0===i?(e.error||this._logger.warn("Logs request failed before receiving an HTTP response"),s({kind:"retry-later",error:Dd(e.error,"logs request failed before receiving an HTTP response")})):s({kind:"retry-later",error:null!==(t=e.error)&&void 0!==t?t:new Error(`logs request failed with status ${i}`)})},e=>{s({kind:"retry-later",error:e})})})}_trackEndpointReachability(e,t){(0!==e||t)&&(this._consecutiveStatusZeroFailures=ya(e,this._consecutiveStatusZeroFailures,3,()=>this._logger.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}_flushViaTransport(e){this._queue.length>0&&this._drainQueueViaTransport(e,this._queue,this._resolvedConfig,this._client.library.name,e=>{this._queue=e}),this._consoleQueue.length>0&&this._drainQueueViaTransport(e,this._consoleQueue,this._consoleResolvedConfig,Od,e=>{this._consoleQueue=e})}_drainQueueViaTransport(e,t,i,s,r){if(0===t.length)return;const n=t.map(e=>e.record);r([]);const o=_n(n,hn(i,this._client.library.name,this._client.library.version),s,this._client.library.version);this._client.sendRequest("/i/v1/logs",{method:"POST",query:{token:this._client.projectToken},body:o,compression:"best-available",transport:e,timeoutMs:6e4}).catch(e=>this._logFlushError(e))}};const qd=Cn("[NetworkMetrics]"),Ud=()=>{var e;return(null==je||null===(e=je.performance)||void 0===e?void 0:e.now)?je.performance.now():Date.now()},Hd={"http:":80,"https:":443},zd=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),jd=(e,t)=>{var i;const s=String(t);return{method:String(e).toUpperCase(),url:(null===(i=Sa(s))||void 0===i?void 0:i.href)||s}},Wd=(e,t,i,s,r,n,o=!1)=>{try{var a,l;const c=r();if(!c)return;const u=i||void 0,d=Ud()-s,h=Sa(t.url);if(h&&"http:"!==h.protocol&&"https:"!==h.protocol)return;const _={url:(null==h?void 0:h.href)||t.url,method:t.method},p=pt(c.name)?c.name(_):mt(c.name)?c.name:"http.client.request.duration";if(!p)return;const g=o&&!u?void 0:((e,t)=>e?400>e?void 0:String(e):(null==t?void 0:t.name)||"_OTHER")(u,n),v=ls(ls(ls(ls(ls({},(e=>{const t=zd.has(e)?e:"_OTHER";return ls({"http.request.method":t},"_OTHER"===t&&e!==t?{"http.request.method_original":e}:{})})(_.method)),h?(e=>{return{"server.address":e.hostname.startsWith("[")&&e.hostname.endsWith("]")?e.hostname.slice(1,-1):e.hostname,"server.port":Number(e.port)||Hd[e.protocol],"url.scheme":e.protocol.slice(0,-1),"url.template":(t=e.pathname,t.split("/").map(e=>(e=>/^\d+$/.test(e)||e.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(e))(e)?":id":e).join("/"))};var t})(h):{}),u?{"http.response.status_code":u}:{}),g?{"error.type":g}:{}),null===(a=c.attributes)||void 0===a?void 0:a.call(c,_,{status:u,durationMs:d}));null===(l=e.metrics)||void 0===l||l.histogram(p,d,{unit:"ms",attributes:v})}catch(e){qd.error("Failed to record network metric",e)}},Vd=()=>{},Gd=(e,t)=>pt(null==je?void 0:je.fetch)?Au(je,"fetch",i=>function(...s){const r=Ud(),n=i.apply(this,s);if(!t())return n;try{var o,a,l;const[i,c]=s,u=jd(null!==(o=null!==(a=null==c?void 0:c.method)&&void 0!==a?a:null==i?void 0:i.method)&&void 0!==o?o:"GET",null!==(l=null==i?void 0:i.url)&&void 0!==l?l:i);return n.then(i=>(Wd(e,u,null==i?void 0:i.status,r,t,void 0,!0),i),i=>{throw Wd(e,u,void 0,r,t,i),i})}catch(e){return qd.error("Failed to observe fetch",e),n}}):Vd,Kd=(e,t)=>{var i;const s=null==je||null===(i=je.XMLHttpRequest)||void 0===i?void 0:i.prototype;if(!s)return Vd;const r=new WeakMap,n=Au(s,"open",e=>function(...t){try{(()=>Xl.has(this))()||r.set(this,jd(t[0],t[1]))}catch(e){qd.error("Failed to observe XHR open",e)}return e.apply(this,t)}),o=Au(s,"send",i=>function(...s){let n;try{const i=r.get(this);if(i&&t()){const s=Ud();n=()=>{this.removeEventListener("loadend",n),Wd(e,i,this.status,s,t)},An(this,"loadend",n)}}catch(e){qd.error("Failed to observe XHR send",e)}try{return i.apply(this,s)}catch(e){throw n&&this.removeEventListener("loadend",n),e}});return()=>{n(),o()}},Qd=new WeakMap,Jd=new Set(["$comment","$defs","$id","$schema","additionalProperties","default","definitions","deprecated","description","examples","minProperties","properties","readOnly","required","title","type","writeOnly"]),Yd={maxStringLength:2048,truncationSuffix:"..."},Zd={maxStringLength:2048,truncationSuffix:"..."};function Xd(e){if(e)return!0===e?{intent:!0,model:!0}:{intent:!1!==e.intent,model:!1!==e.model}}function eh(e,t){return{}.hasOwnProperty.call(e,t)}function th(e,t){const i=Object.create(e);return t&&Object.defineProperty(i,"inputSchema",{configurable:!0,enumerable:!0,writable:!0,value:t}),i}function ih(e,t,i=!1){if(!mt(e))return;const s=e.trim();return s?(i?Qr(s,Yd):s).slice(0,t):void 0}function sh(e){try{return gt(e)&&!0===e.isError}catch(e){return!1}}function rh(e,t){try{return Qr((t?function(e){try{if(!gt(e)||!_t(e.content))return;return e.content.filter(e=>gt(e)&&"text"===e.type&&mt(e.text)).map(e=>e.text).join(" ").trim()||void 0}catch(e){return}}(e):gt(e)&&mt(e.message)?e.message:mt(e)?e:String(e))||"Unknown error",Zd).slice(0,2048)}catch(e){return"Unknown error"}}function nh(e,t){if(t)return"Error";try{if(!gt(e))return"Error";let t=mt(e.name)?e.name.trim():"";const i=e.constructor;return t&&"Error"!==t||!pt(i)||"Error"===i.name||(t=i.name),(t||"Error").slice(0,256)}catch(e){return"Error"}}function oh(e,t){return{message:rh(e,t),type:nh(e,t)}}const ah={featureFlags:class extends yd{constructor(e){const t=new Sd(e.config,e._shouldDisableFlags());super(t),this.name=Yc,this._instance=e,this._mutableConfigSource=t}get _crossTabPersistence(){return this._instance.persistence}updateConfig(e,t){this._mutableConfigSource.update(e,t),this._onConfigUpdated()}}},lh={sessionRecording:class{get _config(){return this._instance.config}get _persistence(){return this._instance.persistence}get started(){var e;return!!(null===(e=this._lazyLoadedSessionRecording)||void 0===e?void 0:e.isStarted)}get status(){var e,t;return"awaiting_config"===this._recordingStatus||"missing_config"===this._recordingStatus?this._recordingStatus:null!==(e=null===(t=this._lazyLoadedSessionRecording)||void 0===t?void 0:t.status)&&void 0!==e?e:this._recordingStatus}constructor(e){if(this._instance=e,this._forceAllowLocalhostNetworkCapture=!1,this._recordingStatus=Uu,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._documentWasEverVisible=(()=>{var e,t;if(!(null==Ge?void 0:Ge.visibilityState)||"visible"===Ge.visibilityState)return!0;const i=null==je||null===(e=je.performance)||void 0===e||null===(t=e.getEntriesByType)||void 0===t?void 0:t.call(e,"visibility-state");return!(null==i?void 0:i.length)||i.some(e=>"visible"===e.name)})(),this._onVisibilityChange=()=>{var e,t;"visible"===(null==Ge?void 0:Ge.visibilityState)&&(this._documentWasEverVisible=!0,null===(e=this._lazyLoadedSessionRecording)||void 0===e||null===(t=e.setDocumentWasEverVisible)||void 0===t||t.call(e,!0))},!this._instance.sessionManager)throw zu.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if("always"===this._config.cookieless_mode)throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');(null==Ge?void 0:Ge.addEventListener)&&An(Ge,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this._sessionRecordingDisposed=!0,null==Ge||null===(t=Ge.removeEventListener)||void 0===t||t.call(Ge,"visibilitychange",this._onVisibilityChange),e?this._discardRecording(!0):this.stopRecording()}get _isRecordingEnabled(){var e;const t=!!(null===(e=this._instance.get_property("$session_recording_remote_config"))||void 0===e?void 0:e.enabled),i=!this._config.disable_session_recording,s=this._config.disable_session_recording||this._instance.consent.isOptedOut();return je&&t&&i&&!s}startIfEnabledOrStop(e){var t;if(this._sessionRecordingDisposed)return;if(this._isRecordingEnabled&&(null===(t=this._lazyLoadedSessionRecording)||void 0===t?void 0:t.isStarted))return;const i=!ft(Object.assign)&&!ft(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),zu.info("starting")):(this._recordingStatus=Uu,this.stopRecording())}_lazyLoadAndStart(e){var t,i;if(this._isRecordingEnabled)if("awaiting_config"!==this._recordingStatus&&"missing_config"!==this._recordingStatus&&(this._recordingStatus=Hu),(null==tt||null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t?void 0:t.record)&&(null===(i=tt.__PosthogExtensions__)||void 0===i?void 0:i.initSessionRecording))this._onScriptLoaded(e);else{var s,r;const t=this._instance.sessionManager;null===(s=tt.__PosthogExtensions__)||void 0===s||null===(r=s.loadExternalDependency)||void 0===r||r.call(s,this._instance,this._scriptName,i=>{if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager===t)return i?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),zu.error("could not load recorder",i)):void this._onScriptLoaded(e);this._recordingStatus="disabled"})}}stopRecording(){var e,t;null===(e=this._persistFlagsOnSessionListener)||void 0===e||e.call(this),this._persistFlagsOnSessionListener=void 0,null===(t=this._lazyLoadedSessionRecording)||void 0===t||t.stop()}_discardRecording(e=!1){var t,i;null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=void 0,null===(i=this._lazyLoadedSessionRecording)||void 0===i||i.discard({discardProducerEvents:e})}_resetSampling(){var e,t;null===(e=this._persistence)||void 0===e||e.unregister("$session_is_sampled"),null===(t=this._persistence)||void 0===t||t.unregister("$replay_sample_rate")}_validateSampleRate(e,t){if(St(e))return null;const i=wt(e)?e:parseFloat(e);return"number"!=typeof(s=i)||!Number.isFinite(s)||0>s||s>1?(zu.warn(`${t} must be between 0 and 1. Ignoring invalid value:`,e),null):i;var s}_persistRemoteConfig(e){if(this._persistence){var t,i;const s=this._persistence,r=()=>{var t;const i=!1===e.sessionRecording?void 0:e.sessionRecording,r=this._validateSampleRate(null===(t=this._config.session_recording)||void 0===t?void 0:t.sampleRate,"session_recording.sampleRate"),n=this._validateSampleRate(null==i?void 0:i.sampleRate,"remote config sampleRate"),o=null!=r?r:n;St(o)&&this._resetSampling();const a=null==i?void 0:i.minimumDurationMilliseconds;s.register({[U]:ls(ls({cache_timestamp:Date.now(),enabled:!!i},i),{},{networkPayloadCapture:ls({capturePerformance:e.capturePerformance},null==i?void 0:i.networkPayloadCapture),canvasRecording:{enabled:null==i?void 0:i.recordCanvas,fps:null==i?void 0:i.canvasFps,quality:null==i?void 0:i.canvasQuality},sampleRate:o,minimumDurationMilliseconds:ft(a)?null:a,endpoint:null==i?void 0:i.endpoint,triggerMatchType:null==i?void 0:i.triggerMatchType,masking:null==i?void 0:i.masking,urlTriggers:null==i?void 0:i.urlTriggers,version:null==i?void 0:i.version,triggerGroups:null==i?void 0:i.triggerGroups})})};r(),null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=null===(i=this._instance.sessionManager)||void 0===i?void 0:i.onSessionId(r)}}onRemoteConfig(e){const t=e.ok?e.config:void 0;return t&&"sessionRecording"in t?!1===t.sessionRecording?(this._persistRemoteConfig(t),void this._discardRecording()):(this._persistRemoteConfig(t),void this.startIfEnabledOrStop()):("awaiting_config"===this._recordingStatus&&(this._recordingStatus="missing_config",this._instance.register_for_session({[Pe]:!0}),zu.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t="log"){var i;(null===(i=this._lazyLoadedSessionRecording)||void 0===i?void 0:i.log)?this._lazyLoadedSessionRecording.log(e,t):zu.warn("log called before recorder was ready")}get _scriptName(){var e,t;const i=null===(e=this._instance)||void 0===e||null===(e=e.persistence)||void 0===e?void 0:e.get_property(U);return(null==i||null===(t=i.scriptConfig)||void 0===t?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){const e=this._instance.get_property(U);if(!e)return!1;let t;try{t="object"==typeof e?e:JSON.parse(e)}catch(e){return zu.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!St(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}_onScriptLoaded(e){var t,i,s;if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager){if(!(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.initSessionRecording))return zu.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[ke]:!0});var r;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null===(r=tt.__PosthogExtensions__)||void 0===r?void 0:r.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._isRemoteConfigFresh()){if("missing_config"===this._recordingStatus||"awaiting_config"===this._recordingStatus)return;return this._recordingStatus="awaiting_config",zu.info("persisted remote config is stale, requesting fresh config before starting"),void new fl(this._instance).load()}this._recordingStatus=Hu,null===(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||void 0===i||i.call(s,this._documentWasEverVisible),this._lazyLoadedSessionRecording.start(e)}else this._recordingStatus=Uu}onRRwebEmit(e){var t,i;null===(t=this._lazyLoadedSessionRecording)||void 0===t||null===(i=t.onRRwebEmit)||void 0===i||i.call(t,e)}overrideLinkedFlag(){var e,t;this._lazyLoadedSessionRecording||null===(t=this._persistence)||void 0===t||t.register({$replay_override_linked_flag:!0}),null===(e=this._lazyLoadedSessionRecording)||void 0===e||e.overrideLinkedFlag()}overrideSampling(){var e,t;this._lazyLoadedSessionRecording||null===(t=this._persistence)||void 0===t||t.register({$replay_override_sampling:!0}),null===(e=this._lazyLoadedSessionRecording)||void 0===e||e.overrideSampling()}overrideTrigger(e){var t,i;this._lazyLoadedSessionRecording||null===(i=this._persistence)||void 0===i||i.register({["url"===e?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),null===(t=this._lazyLoadedSessionRecording)||void 0===t||t.overrideTrigger(e)}get sdkDebugProperties(){var e;const t={};for(const e of ju){var i;const s=null===(i=this._instance.sessionPersistence)||void 0===i?void 0:i.get_property(e);ft(s)||(t[e]=s)}return ls(ls({},t),(null===(e=this._lazyLoadedSessionRecording)||void 0===e?void 0:e.sdkDebugProperties)||{$recording_status:this.status})}tryAddCustomEvent(e,t){var i;return!!(null===(i=this._lazyLoadedSessionRecording)||void 0===i?void 0:i.tryAddCustomEvent(e,t))}flushBeforeIdentityReset(){var e,t;null===(e=this._lazyLoadedSessionRecording)||void 0===e||null===(t=e.flushBeforeIdentityReset)||void 0===t||t.call(e)}}},ch={autocapture:class extends Iu{constructor(e){super(new Tu(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._isFlushingPageview=!1,this._instance=e,this._lastLocation=this._getCurrentLocation()}initialize(){this.startIfEnabled()}get isEnabled(){const e=this._getCaptureOptions();return!!(e.path||e.search||this._shouldCaptureHashChanges(e))}startIfEnabled(){this.isEnabled&&(En.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this._lastLocation=this._getCurrentLocation(),this.startIfEnabled()}stop(){this._popstateListener&&this._popstateListener(),this._popstateListener=void 0,this._hashchangeListener&&this._hashchangeListener(),this._hashchangeListener=void 0,En.info("History API monitoring stopped")}monitorHistoryChanges(){je&&je.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(!je||(null===(t=je.history[e])||void 0===t?void 0:t.__posthog_wrapped__))return;const i=this;Au(je.history,e,t=>function(s,r,n){var o;i._isUrlChanging(n)&&i._flushPendingPageview(),t.call(this,s,r,n),i._capturePageview(e,!i._isFlushingPageview&&"popstate"!==(null==je||null===(o=je.event)||void 0===o?void 0:o.type))})}_getCurrentLocation(){const e=null==je?void 0:je.location;if(null==e?void 0:e.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}_getCaptureOptions(){const e=this._instance.config.capture_pageview;return"history_change"===e?{path:!0}:gt(e)?e:{}}_shouldCaptureHashChanges(e=this._getCaptureOptions()){return!!e.hash&&!this._instance.config.disable_capture_url_hashes}_hasLocationChanged(e){const t=this._getCaptureOptions(),i=this._lastLocation;return!(!i||!(t.path&&e.pathname!==i.pathname||t.search&&e.search!==i.search||this._shouldCaptureHashChanges(t)&&e.hash!==i.hash))}_capturePageview(e,t=!1){try{t||this._flushPendingPageview();const i=this._getCurrentLocation();if(!i)return;if(this._hasLocationChanged(i)){const i=()=>this._instance.capture(qe,{navigation_type:e});t?(this._pendingPageview=i,Promise.resolve().then(()=>this._flushPendingPageview())):i()}this._lastLocation=i}catch(t){En.error(`Error capturing ${e} pageview`,t)}}_isUrlChanging(e){var t,i;return!(St(e)||!je)&&(null===(t=Sa(String(e)))||void 0===t?void 0:t.href)!==(null===(i=je.location)||void 0===i?void 0:i.href)}_flushPendingPageview(){const e=this._pendingPageview;if(e){this._pendingPageview=void 0,this._isFlushingPageview=!0;try{e()}catch(e){En.error("Error capturing deferred pageview",e)}finally{this._isFlushingPageview=!1}this._lastLocation=this._getCurrentLocation()}}_setupPopstateListener(){if(this._popstateListener)return;const e=()=>{this._capturePageview("popstate")};An(je,"popstate",e),this._popstateListener=()=>{je&&je.removeEventListener("popstate",e)}}_setupHashchangeListener(){if(this._hashchangeListener)return;const e=()=>{this._capturePageview("hashchange")};An(je,"hashchange",e),this._hashchangeListener=()=>{je&&je.removeEventListener("hashchange",e)}}},heatmaps:class{get _config(){return this.instance.config}constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._flushInterval=null,this.instance=e,this._enabledServerSide=!!(null===(t=this.instance.persistence)||void 0===t?void 0:t.props[R]),this.rageclicks=new Eu(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return gt(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return St(this._config.capture_heatmaps)?St(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;Wu.info("starting..."),this._setupListeners(),this._onVisibilityChange()}else{var e;clearInterval(null!==(e=this._flushInterval)&&void 0!==e?e:void 0),this._removeListeners(),this.getAndClearBuffer()}}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("heatmaps"in t))return;const i=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[R]:i}),this._enabledServerSide=i,this.startIfEnabled()}getAndClearBuffer(){const e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){Vu(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval="visible"===(null==Ge?void 0:Ge.visibilityState)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){je&&Ge&&(this._flushHandler=this._flush.bind(this),An(je,Be,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==je?void 0:je.event)),An(Ge,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==je?void 0:je.event)),An(Ge,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new na(this.instance,sa,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),An(Ge,m,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;je&&Ge&&(this._flushHandler&&je.removeEventListener(Be,this._flushHandler),this._onClickHandler&&Ge.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&Ge.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&Ge.removeEventListener(m,this._onVisibilityChange_handler),clearTimeout(this._mouseMoveTimeout),null===(e=this._deadClicksCapture)||void 0===e||e.stop(),this._initialized=!1)}_getProperties(e,t){const i=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),n=function(e,t,i){let s=e;for(;s&&po(s)&&!go(s,"body");){if(s===i)return!1;let e;try{var r,n,o;e=null===(r=null!==(n=null===(o=s.ownerDocument)||void 0===o?void 0:o.defaultView)&&void 0!==n?n:je)||void 0===r?void 0:r.getComputedStyle(s).position}catch(e){return!1}if(ot(t,e))return!0;s=xo(s)}return!1}(Eo(e),["fixed","sticky"],r);return{x:e.clientX+(n?0:s),y:e.clientY+(n?0:i),target_fixed:n,type:t}}_onClick(e,t="click"){var i;if(_o(e.target)||!Vu(e))return;const s=this._getProperties(e,t);(null===(i=this.rageclicks)||void 0===i?void 0:i.isRageClick(e.clientX,e.clientY,(new Date).getTime()))&&Bo(Eo(e),this.instance.config.rageclick)&&this._capture(ls(ls({},s),{},{type:"rageclick"})),this._capture(s)}_onMouseMove(e){!_o(e.target)&&Vu(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(e,"mousemove"))},500))}_capture(e){if(!je)return;const t=this._config.disable_capture_url_hashes?es(je.location.href):je.location.href,i=this._config.custom_personal_data_properties,s=this._config.mask_personal_data_properties?[...ka,...i||[]]:[],r=Ea(t,s,xa);this._buffer=this._buffer||{},this._buffer[r]||(this._buffer[r]=[]),this._buffer[r].push(e)}_flush(){this._buffer&&!vt(this._buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:na,webVitalsAutocapture:class{constructor(e){var t;this._instance=e,this._enabledServerSide=!1,this._initialized=!1,this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this._flushToCapture=()=>{clearTimeout(this._delayedFlushTimer),this._delayedFlushTimer=void 0,0!==this._buffer.metrics.length&&(this._instance.capture("$web_vitals",ls({$current_url:this._buffer.url},this._buffer.metrics.reduce((e,t)=>ls(ls({},e),{},{[`$web_vitals_${t.name}_event`]:ls({},t),[`$web_vitals_${t.name}_value`]:t.value}),{}))),this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this._addToBuffer=e=>{var t;if(this._buffer=this._buffer||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},St(null==e?void 0:e.name)||St(null==e?void 0:e.value))return void Lu.error("Invalid metric received",e);const i="string"==typeof e.navigationURL?e.navigationURL:void 0,s=this._maskedURL(i);if(ft(s))return;const r=wt(e.navigationId)||"string"==typeof e.navigationId?`navigation:${e.navigationId}`:`url:${s}`;if(this._maxAllowedValue&&e.value>=this._maxAllowedValue)return void Lu.error("Ignoring metric with value >= "+this._maxAllowedValue,e);this._buffer.navigationKey!==r&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),ft(this._buffer.navigationKey)&&(this._buffer.navigationKey=r,this._buffer.url=s),this._buffer.firstMetricTimestamp=ft(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;const n=null===(t=this._instance.sessionManager)||void 0===t?void 0:t.checkAndGetSessionAndWindowId(!0),o=ls(ls(ls({},e),i?{navigationURL:s}:{}),{},{$current_url:s,timestamp:Date.now()});if(delete o.entries,gt(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){const t={};for(const i of qu){const s="url"===i&&"string"==typeof e.attribution[i]?this._maskedURL(e.attribution[i]):e.attribution[i];ft(s)||(t[i]=s)}o.attribution=t}else delete o.attribution;ft(n)||(o.$session_id=n.sessionId,o.$window_id=n.windowId),this._buffer.metrics.push(o),this._buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()},this._startCapturing=()=>{if(this._initialized)return;let e,t,i,s,r=!1;const n=tt.__PosthogExtensions__,o=null==n?void 0:n.postHogWebVitalsCallbacksByFlavor,a=(null==o?void 0:o[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&ft(o)?null==n?void 0:n.postHogWebVitalsCallbacks:void 0);if(!ft(a)){const n=a.withoutAttribution,o=this.attributionMetrics;r=!ft(n),e=o.indexOf("LCP")>-1?a.onLCP:(null==n?void 0:n.onLCP)||a.onLCP,t=o.indexOf("CLS")>-1?a.onCLS:(null==n?void 0:n.onCLS)||a.onCLS,i=o.indexOf("FCP")>-1?a.onFCP:(null==n?void 0:n.onFCP)||a.onFCP,s=o.indexOf("INP")>-1?a.onINP:(null==n?void 0:n.onINP)||a.onINP}if(!(e&&t&&i&&s))return void Lu.error("web vitals callbacks not loaded - not starting");const l={reportSoftNavs:this.useSoftNavs},c=r&&this.attributionMetrics.indexOf("INP")>-1?ls(ls({},l),{},{includeProcessedEventEntries:!1}):l;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("FCP")>-1&&i(this._addToBuffer.bind(this),l),this.allowedMetrics.indexOf("INP")>-1&&s(this._addToBuffer.bind(this),c),this._initialized=!0},this._enabledServerSide=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[L]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const i=gt(this._perfConfig)?null===(e=this._perfConfig)||void 0===e?void 0:e.web_vitals_allowed_metrics:void 0;return St(i)?(null===(t=this._instance.persistence)||void 0===t?void 0:t.props.$web_vitals_allowed_metrics)||Nu:i}get flushToCaptureTimeoutMs(){return(gt(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=gt(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return Ct(e)?e?Nu:[]:_t(e)?e:Bu}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=gt(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){const e=gt(this._perfConfig)&&wt(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:Du;return e>0&&6e4>=e?Du:e}get isEnabled(){const e=null==Ke?void 0:Ke.protocol;if("http:"!==e&&"https:"!==e)return Lu.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=gt(this._perfConfig)?this._perfConfig.web_vitals:Ct(this._perfConfig)?this._perfConfig:void 0;return Ct(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(Lu.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const i=gt(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=gt(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[L]:i}),this._instance.persistence.register({[q]:s})),this._enabledServerSide=i,this.startIfEnabled()}get _callbackFlavor(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}_loadScript(e){var t;const i=tt.__PosthogExtensions__,s=this._callbackFlavor,r=null==i?void 0:i.postHogWebVitalsCallbacksByFlavor;(null==r?void 0:r[s])||"web-vitals"===s&&ft(r)&&(null==i?void 0:i.postHogWebVitalsCallbacks)?e():null==i||null===(t=i.loadExternalDependency)||void 0===t||t.call(i,this._instance,s,t=>{t?Lu.error("failed to load script",t):e()})}_maskedURL(e){const t=e||(null==je?void 0:je.location.href);if(!t)return void Lu.error("Could not determine current URL");const i=this._instance.config.disable_capture_url_hashes?es(t):t,s=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ka,...s||[]]:[];return Ea(i,r,xa)}}},uh={exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(!je||!this.isEnabled||!(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.errorWrappingFunctions))return;const t=tt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=tt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=tt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this._unwrapOnError&&this._config.capture_unhandled_errors&&(this._unwrapOnError=t(this.captureException.bind(this))),!this._unwrapUnhandledRejection&&this._config.capture_unhandled_rejections&&(this._unwrapUnhandledRejection=i(this.captureException.bind(this))),!this._unwrapConsoleError&&this._config.capture_console_errors&&(this._unwrapConsoleError=s(this.captureException.bind(this)))}catch(e){Ru.error("failed to start",e),this._stopCapturing()}},this._instance=e,this._remoteEnabled=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[M]),this._rateLimiter=new Ut(ls(ls({},function(e={}){var t,i,s,r;return{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(r=e.exceptionRateLimiterBucketSize)&&void 0!==r?r:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking)),{},{refillInterval:1e4,_logger:Ru})),this._config=this._requiredConfig(),this.startIfEnabledOrStop()}_requiredConfig(){const e=this._instance.config.capture_exceptions;let t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return gt(e)?t=ls(ls({},t),e):(ft(e)?this._remoteEnabled:e)&&(t=ls(ls({},t),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this._config.capture_console_errors||this._config.capture_unhandled_errors||this._config.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ru.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.errorWrappingFunctions)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"exception-autocapture",t=>{if(t)return Ru.error("failed to load script",t);e()})}_stopCapturing(){var e,t,i;null===(e=this._unwrapOnError)||void 0===e||e.call(this),this._unwrapOnError=void 0,null===(t=this._unwrapUnhandledRejection)||void 0===t||t.call(this),this._unwrapUnhandledRejection=void 0,null===(i=this._unwrapConsoleError)||void 0===i||i.call(this),this._unwrapConsoleError=void 0}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"autocaptureExceptions"in t&&(this._remoteEnabled=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[M]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}onConfigChange(){this._config=this._requiredConfig()}captureException(e){try{var t,i,s;const r=null!==(t=null==e||null===(i=e.$exception_list)||void 0===i||null===(i=i[0])||void 0===i?void 0:i.type)&&void 0!==t?t:"Exception";if(this._rateLimiter.consumeRateLimit(r))return void Ru.info("Skipping exception capture because of client rate limiting.",{exception:r});null===(s=this._instance.exceptions)||void 0===s||s.sendExceptionEvent(e)}catch(e){}}},exceptions:class{constructor(e){var t,i;this._suppressionRules=[],this._errorPropertiesBuilder=new gs([new Ls,new Vs,new Ns,new Ds,new js,new zs,new qs,new Ws],function(e,...t){return(i,s=0)=>{const r=[],n=i.split("\n"),o=Math.min(n.length,s+1e3),a=[];for(let i=s;o>i;i++){const s=n[i];if(s.length>1024)continue;const o=Fs.test(s)?s.replace(Fs,"$1"):s;if(!o.match(/\S*Error: /)){for(const i of t){const t=i(o,e);if(t){r.push(t);const e=Ts(r);if(e){for(let t=a.length-1;t>=0;t--){const i=a[t];if(e.start>=i.start+i.length)break;a.pop()}a.push(e)}break}}if(As(r,a)>=50)break}}const l=[...a].sort((e,t)=>t.start-e.start),c=l[l.length-1];if(c){const e=$s(r,c);r.splice(c.start-e,e);for(const t of l)t.start-=e}for(const e of l)Rs(r,e);return a.some(e=>0===e.start&&r.length===e.length)&&function(e){const t=e.map(e=>`${e.function}|${e.filename}|${e.lineno}|${e.colno}|${e.module}`);let i=0;for(let e=1;t.length>e;e++)Os(t,e,i)&&(i=e);e.push(...e.splice(0,i))}(r),function(e){if(!e.length)return[];const t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{return ls(ls({},e),{},{filename:e.filename||(i=t,i[i.length-1]||{}).filename,function:e.function||"?"});var i})}(r)}}("web:javascript",Cs,xs)),this._instance=e,this._suppressionRules=null!==(t=null===(i=this._instance.persistence)||void 0===i?void 0:i.get_property("$error_tracking_suppression_rules"))&&void 0!==t?t:[],this._exceptionStepsConfig=Ys(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new Zs(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=Ys(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(!e.ok)return;const r=e.config;if(!("errorTracking"in r))return;const n=null!==(t=null===(i=r.errorTracking)||void 0===i?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null===(s=r.errorTracking)||void 0===s?void 0:s.captureExtensionExceptions;this._suppressionRules=n,this._instance.persistence&&this._instance.persistence.register({[A]:this._suppressionRules,[O]:o})}get _captureExtensionExceptions(){var e;const t=!!this._instance.get_property(O),i=this._instance.config.error_tracking.captureExtensionExceptions;return null!==(e=null!=i?i:t)&&void 0!==e&&e}buildProperties(e,t){return this._errorPropertiesBuilder.buildFromUnknown(e,{syntheticException:null==t?void 0:t.syntheticException,mechanism:{handled:null==t?void 0:t.handled}})}addExceptionStep(e,t){if(this._exceptionStepsConfig.enabled)try{if(!mt(e)||0===e.trim().length)return void Ed.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:i,droppedKeys:s}=function(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};const t=[];return{sanitizedProperties:Object.keys(e).reduce((i,s)=>Qs.has(s)?(t.push(s),i):(i[s]=e[s],i),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t));s.length>0&&Ed.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this._exceptionStepsBuffer.add(ls({[Gs]:e,[Ks]:(new Date).toISOString()},i))}catch(e){Ed.error("Failed to add exception step. Ignoring breadcrumb.",e)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this._isExceptionList(t)){if(this._matchesSuppressionRule(t))return this._addDroppedExceptionStep("Exception dropped: matched a suppression rule"),void Ed.info("Skipping exception capture because a suppression rule matched");if(!this._captureExtensionExceptions&&this._isExtensionException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by a browser extension"),void Ed.info("Skipping exception capture because it was thrown by an extension");if(!this._captureExtensionExceptions&&this._isInjectedBrowserScriptException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by an injected browser script"),void Ed.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this._isPostHogException(t))return this._addDroppedExceptionStep("Exception dropped: thrown by the PostHog SDK"),void Ed.info("Skipping exception capture because it was thrown by the PostHog SDK")}const i=this._exceptionStepsConfig.enabled&&St(e.$exception_steps)?this._addBufferedExceptionSteps(e):e,s=function(){if("u">typeof process){var e;const t=null===(e=process.env.POSTHOG_RELEASE_ID)||void 0===e?void 0:e.trim();if(t)return t}const t=globalThis._posthogReleaseId;return"string"==typeof t&&t.length>0?t:void 0}();s&&(i.$release_id=s);try{const e=this._instance.capture("$exception",i,{_noTruncate:!0,_batchKey:"exceptionEvent",_originatedFromCaptureException:!0});return e&&this._exceptionStepsBuffer.clear(),e}catch(e){return wd(e)||Ed.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void(wd(e)||Ed.error("Failed to process exception event. Ignoring this exception.",e))}}_addBufferedExceptionSteps(e){try{const t=this._exceptionStepsBuffer.getAttachable();return 0===t.length?e:ls(ls({},e),{},{$exception_steps:t})}catch(t){return Ed.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_addDroppedExceptionStep(e){this._exceptionStepsConfig.enabled&&this._exceptionStepsBuffer.add({[Gs]:e,[Ks]:(new Date).toISOString()})}_coerceExceptionStepProperties(e){return gt(e)?ls({},e):{}}_getExceptionStepsConfig(){var e,t;return null!==(e=null===(t=this._instance.config.error_tracking)||void 0===t?void 0:t.exception_steps)&&void 0!==e?e:{}}_matchesSuppressionRule(e){if(0===e.length)return!1;try{const t=e.reduce((e,{type:t,value:i})=>(mt(t)&&t.length>0&&e.$exception_types.push(t),mt(i)&&i.length>0&&e.$exception_values.push(i),e),{$exception_types:[],$exception_values:[]});return this._suppressionRules.some(e=>{const i=e.values.map(e=>{const i=Oc[e.operator],s=t[e.key];if(!i||!s)return!1;const r=_t(e.value)?e.value:[e.value];return r.length>0&&i(r,s)});return"OR"===e.type?i.some(Boolean):i.every(Boolean)})}catch(e){return Ed.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}_isExtensionException(e){const t=e.flatMap(e=>{var t,i;return null!==(t=null===(i=e.stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[]}),i=t.filter(({filename:e})=>!!e&&Pd.some(t=>e.startsWith(t)));return 0!==i.length&&(!i.every(({filename:e})=>!!e&&e.startsWith(Cd))||e.some(({type:e,value:t})=>"NoResponse"===e||mt(t)&&kd.some(({value:e,exact:i})=>i?t===e:t.includes(e)))&&!t.some(({in_app:e,filename:t})=>e&&!(null==t?void 0:t.startsWith(Cd))))}_isInjectedBrowserScriptException(e){return e.some(({value:e})=>mt(e)&&xd.some(t=>e.includes(t)))}_isPostHogException(e){if(e.length>0){var t,i,s,r;const n=null!==(t=null===(i=e[0].stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[],o=n[n.length-1];return null!==(s=null==o||null===(r=o.filename)||void 0===r?void 0:r.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!St(e)&&_t(e)}}},dh=ls({productTours:class{get _persistence(){return this._instance.persistence}constructor(e){this._productTourManager=null,this._cachedTours=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if("productTours"in t){var i,s;if(this._persistence&&this._persistence.register({[N]:!!t.productTours}),!Ku(this._instance))return!this._productTourManager&&St(null===(i=this._persistence)||void 0===i?void 0:i.props.ph_product_tours)||Gu.info("product tours disabled; stopping and clearing cached tours"),null===(s=this._productTourManager)||void 0===s||s.stop(),this._productTourManager=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this._productTourManager&&Ku(this._instance)&&this._loadScript(()=>this._startProductTours())}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.generateProductTours)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"product-tours",t=>{t?Gu.error("Could not load product tours script",t):e()})}_startProductTours(){var e;!this._productTourManager&&(null===(e=tt.__PosthogExtensions__)||void 0===e?void 0:e.generateProductTours)&&(this._productTourManager=tt.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(_t(this._cachedTours)&&!t)return void e(this._cachedTours,{isLoaded:!0});const i=this._persistence;if(i){const s=i.props[ae];if(_t(s)&&!t)return this._cachedTours=s,void e(s,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:t=>{if(!Ku(this._instance))return void e([],{isLoaded:!0});const s=t.statusCode;if(200!==s||!t.json){const i=`Product Tours API could not be loaded, status: ${s}`;return 0===s?t.error||Gu.warn(i):Gu.error(i),void e([],{isLoaded:!1,error:i})}const r=_t(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=r,i&&i.register({[ae]:r}),e(r,{isLoaded:!0})}})}getActiveProductTours(e){St(this._productTourManager)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this._productTourManager.getActiveProductTours(e)}showProductTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.showTourById(e)}previewTour(e){this._productTourManager?this._productTourManager.previewTour(e):this._loadScript(()=>{var t;this._startProductTours(),null===(t=this._productTourManager)||void 0===t||t.previewTour(e)})}dismissProductTour(){var e;null===(e=this._productTourManager)||void 0===e||e.dismissTour("user_clicked_skip")}nextStep(){var e;null===(e=this._productTourManager)||void 0===e||e.nextStep()}previousStep(){var e;null===(e=this._productTourManager)||void 0===e||e.previousStep()}clearCache(){var e;this._cachedTours=null,null===(e=this._persistence)||void 0===e||e.unregister("ph_product_tours")}resetTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.resetTour(e)}resetAllTours(){var e;null===(e=this._productTourManager)||void 0===e||e.resetAllTours()}cancelPendingTour(e){var t;null===(t=this._productTourManager)||void 0===t||t.cancelPendingTour(e)}}},ah),hh={siteApps:class{constructor(e){this._instance=e,this._siteAppElementPatchCount=0,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}_eventCollector(e,t){if(!t)return;const i=this.globalsForEvent(t);this._bufferedInvocations.push(i),this._bufferedInvocations.length>1e3&&(this._bufferedInvocations=this._bufferedInvocations.slice(10))}get siteAppLoaders(){var e;return null===(e=tt._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.siteApps}initialize(){if(this.isEnabled){const e=this._instance._addCaptureHook(this._eventCollector.bind(this));this._stopBuffering=()=>{e(),this._bufferedInvocations=[],this._stopBuffering=void 0}}}globalsForEvent(e){var t,i,s,r,n,o,a;if(!e)throw new Error("Event payload is required");const l={},c=this._instance.get_property("$groups")||[],u=this._instance.get_property("$stored_group_properties")||{};for(const[e,t]of Object.entries(u))l[e]={id:c[e],type:e,properties:t};const{$set_once:d,$set:h}=e;return{event:ls(ls({},_r(e,Qu)),{},{properties:ls(ls(ls({},e.properties),h?{$set:ls(ls({},null!==(t=null===(i=e.properties)||void 0===i?void 0:i.$set)&&void 0!==t?t:{}),h)}:{}),d?{$set_once:ls(ls({},null!==(s=null===(r=e.properties)||void 0===r?void 0:r.$set_once)&&void 0!==s?s:{}),d)}:{}),elements_chain:null!==(n=null===(o=e.properties)||void 0===o?void 0:o.$elements_chain)&&void 0!==n?n:"",distinct_id:null===(a=e.properties)||void 0===a?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}_prepareElementForSiteApp(e){var t;const i=null===(t=e.tagName)||void 0===t?void 0:t.toLowerCase();if("style"===i&&this._instance.config.prepare_external_dependency_stylesheet){return this._instance.config.prepare_external_dependency_stylesheet(e)||(Ju.error("prepare_external_dependency_stylesheet returned null"),null)}if("script"===i&&this._instance.config.prepare_external_dependency_script){return this._instance.config.prepare_external_dependency_script(e)||(Ju.error("prepare_external_dependency_script returned null"),null)}return e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,r,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const l=null==Ge?void 0:Ge.defaultView,c=null==l||null===(e=l.Node)||void 0===e?void 0:e.prototype;if(!l||!c)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();const u=[],d=this,h=new WeakSet,_=(e,t,i)=>{if(!(null==e?void 0:e[t]))return;const s=e[t];e[t]=i(s),u.push(()=>{e[t]=s})},p=e=>{if(h.has(e))return e;const t=d._prepareElementForSiteApp(e);return t&&h.add(t),t},g=e=>e.map(e=>"string"==typeof e?e:p(e)).filter(e=>!bt(e));return _(c,"appendChild",e=>function(t){const i=p(t);return i?e.call(this,i):t}),_(c,"insertBefore",e=>function(t,i){const s=p(t);return s?e.call(this,s,i):t}),_(c,"replaceChild",e=>function(t,i){const s=p(t);return s?e.call(this,s,i):i}),[null===(t=l.Element)||void 0===t?void 0:t.prototype,null===(i=l.Document)||void 0===i?void 0:i.prototype,null===(s=l.DocumentFragment)||void 0===s?void 0:s.prototype].forEach(e=>{_(e,"append",e=>function(...t){return e.apply(this,g(t))}),_(e,"prepend",e=>function(...t){return e.apply(this,g(t))})}),[null===(r=l.Element)||void 0===r?void 0:r.prototype,null===(n=l.CharacterData)||void 0===n?void 0:n.prototype,null===(o=l.DocumentType)||void 0===o?void 0:o.prototype].forEach(e=>{_(e,"before",e=>function(...t){return e.apply(this,g(t))}),_(e,"after",e=>function(...t){return e.apply(this,g(t))}),_(e,"replaceWith",e=>function(...t){const i=g(t);return t.length&&!i.length?void 0:e.apply(this,i)})}),_(null===(a=l.Element)||void 0===a?void 0:a.prototype,"insertAdjacentElement",e=>function(t,i){const s=p(i);return s?e.call(this,t,s):null}),this._restoreSiteAppElementPatches=()=>{u.forEach(e=>e()),this._restoreSiteAppElementPatches=void 0},this._releaseSiteAppElementPatches()}_releaseSiteAppElementPatches(){let e=!1;return()=>{var t;e||(e=!0,this._siteAppElementPatchCount--,0===this._siteAppElementPatchCount&&(null===(t=this._restoreSiteAppElementPatches)||void 0===t||t.call(this)))}}_runWithPreparedSiteAppElements(e,t=!0){const i=this._patchSiteAppElementInsertionMethods();try{const s=e(i);return t&&i(),s}catch(e){throw i(),e}}setupSiteApp(e){const t=this.apps[e.id],i=()=>{var i;!t.errored&&this._bufferedInvocations.length&&(Ju.info(`Processing ${this._bufferedInvocations.length} events for site app with id ${e.id}`),this._bufferedInvocations.forEach(e=>this._runWithPreparedSiteAppElements(()=>{var i;return null===(i=t.processEvent)||void 0===i?void 0:i.call(t,e)})),t.processedBuffer=!0),Object.values(this.apps).every(e=>e.processedBuffer||e.errored)&&(null===(i=this._stopBuffering)||void 0===i||i.call(this))};let s=!1;const r=r=>{t.errored=!r,t.loaded=!0,Ju.info(`Site app with id ${e.id} ${r?"loaded":"errored"}`),s&&i()};try{const{processEvent:i}=this._runWithPreparedSiteAppElements(t=>e.init({posthog:this._instance,callback(e){t(),r(e)}}),!1);i&&(t.processEvent=i),s=!0}catch(t){Ju.error(Yu+e.id,t),r(!1)}if(s&&t.loaded)try{i()}catch(i){Ju.error(`Error while processing buffered events PostHog app with config id ${e.id}`,i),t.errored=!0}}_setupSiteApps(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}_onCapturedEvent(e){if(0===Object.keys(this.apps).length)return;const t=this.globalsForEvent(e);for(const i of Object.values(this.apps))try{this._runWithPreparedSiteAppElements(()=>{var e;return null===(e=i.processEvent)||void 0===e?void 0:e.call(i,t)})}catch(t){Ju.error(`Error while processing event ${e.event} for site app ${i.id}`,t)}}onRemoteConfig(e){var t,i,s;if(null===(t=this.siteAppLoaders)||void 0===t?void 0:t.length)return this.isEnabled?(this._setupSiteApps(),void this._instance.on("eventCaptured",e=>this._onCapturedEvent(e))):void Ju.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null===(i=this._stopBuffering)||void 0===i||i.call(this),!e.ok)return;const r=e.config;if(null===(s=r.siteApps)||void 0===s?void 0:s.length)if(this.isEnabled)for(const{id:e,url:t}of r.siteApps){var n,o;tt[`__$$ph_site_app_${e}`]=this._instance,null===(n=tt.__PosthogExtensions__)||void 0===n||null===(o=n.loadSiteApp)||void 0===o||o.call(n,this._instance,t,t=>{if(t)return Ju.error(Yu+e,t)})}else Ju.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},_h={tracingHeaders:class{constructor(e){this._instance=e,this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._startCapturing=()=>{const e=this._syncHostnamesForPatch();var t,i;e?(ft(this._restoreXHRPatch)&&(this._restoreXHRPatch=null===(t=tt.__PosthogExtensions__)||void 0===t||null===(t=t.tracingHeadersPatchFns)||void 0===t?void 0:t._patchXHR(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),ft(this._restoreFetchPatch)&&(this._restoreFetchPatch=null===(i=tt.__PosthogExtensions__)||void 0===i||null===(i=i.tracingHeadersPatchFns)||void 0===i?void 0:i._patchFetch(e,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this._stopCapturing()}}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i,s;(null===(t=tt.__PosthogExtensions__)||void 0===t?void 0:t.tracingHeadersPatchFns)?e():null===(i=tt.__PosthogExtensions__)||void 0===i||null===(s=i.loadExternalDependency)||void 0===s||s.call(i,this._instance,"tracing-headers",t=>{if(t)return Ou.error("failed to load script",t);e()})}_getConfiguredHostnames(){var e,t;return null!==(e=null!==(t=this._instance.config.tracing_headers)&&void 0!==t?t:this._instance.config.addTracingHeaders)&&void 0!==e?e:this._instance.config.__add_tracing_headers}_syncHostnamesForPatch(){const e=this._getConfiguredHostnames();return _t(e)?(_t(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):(_t(this._hostnamesForPatch)&&this._hostnamesForPatch.splice(0),this._hostnamesForPatch=e||void 0,this._hostnamesForPatch)}_stopCapturing(){var e,t;null===(e=this._restoreXHRPatch)||void 0===e||e.call(this),null===(t=this._restoreFetchPatch)||void 0===t||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0}startIfEnabledOrStop(){this._syncHostnamesForPatch()?this._loadScript(this._startCapturing):this._stopCapturing()}}},ph=ls({surveys:class extends td{constructor(e){var t;super(new ad(e),(t=e,{get projectToken(){return t.config.token},kv:new od(t)})),this._instance=e}_sendSurveysRequest(e,t){const i=t.query?rc(e,t.query):e;return new Promise(e=>{var s;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor(null!==(s=t.target)&&void 0!==s?s:"api",i),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:e})})}}},ah),gh={toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){tt.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=tt.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,i=void 0){var s,r;if(On(this.instance.config))return!1;if(!je||!Ge)return!1;e=null!==(s=e)&&void 0!==s?s:je.location,i=null!==(r=i)&&void 0!==r?r:je.history;try{if(!t){try{je.localStorage.setItem("test","test"),je.localStorage.removeItem("test")}catch(e){return!1}t=null==je?void 0:je.localStorage}const s=ld||Ca(e.hash,"__posthog")||Ca(e.hash,"state");let r;const n=s?ts(()=>JSON.parse(atob(decodeURIComponent(s))))||ts(()=>JSON.parse(decodeURIComponent(s))):null;return n&&"ph_authorize"===n.action?(r=n,r.source="url",r&&Object.keys(r).length>0&&(n.desiredHash?e.hash=n.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):(r=JSON.parse(t.getItem(cd)||"{}"),r.source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch(e){return!1}}_callLoadToolbar(e){const t=tt.ph_load_toolbar||tt.ph_load_editor;!St(t)&&pt(t)?t(e,this.instance):ud.warn("No toolbar load function found")}loadToolbar(e){const t=!!(null==Ge?void 0:Ge.getElementById("__POSTHOG_TOOLBAR__"));if(!je||t)return!1;const i="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,s=ls(ls({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},i?{instrument:!1}:{});if(je.localStorage.setItem(cd,JSON.stringify(ls(ls({},s),{},{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(s);else if(0===this._getToolbarState()){var r,n;this._setToolbarState(1),null===(r=tt.__PosthogExtensions__)||void 0===r||null===(n=r.loadExternalDependency)||void 0===n||n.call(r,this.instance,"toolbar",e=>{if(e)return ud.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(s)}),An(je,"turbolinks:load",()=>{this._setToolbarState(0),this.loadToolbar(s)})}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,i=void 0){return this.maybeLoadToolbar(e,t,i)}}},vh=ls({experiments:class e{get _config(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(t=!1)=>{this.getWebExperiments(t=>{e._logInfo("retrieved web experiments from the server"),this._flagToExperiments=new Map,t.forEach(t=>{if(t.feature_flag_key){var i;this._flagToExperiments&&(e._logInfo("setting flag key ",t.feature_flag_key," to web experiment ",t),null===(i=this._flagToExperiments)||void 0===i||i.set(t.feature_flag_key,t));const s=this._instance.getFeatureFlag(t.feature_flag_key);mt(s)&&t.variants[s]&&this._applyTransforms(t.name,s,t.variants[s].transforms)}else if(t.variants)for(const i in t.variants){const s=t.variants[i];e._matchesTestVariant(s,this._instance)&&this._applyTransforms(t.name,i,s.transforms)}})},t)},this._instance.onFeatureFlags(e=>{this.onFeatureFlags(e)})}initialize(){}onFeatureFlags(t){if(this._is_bot())e._logInfo(Fd);else if(!this._config.disable_web_experiments){if(St(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();e._logInfo("applying feature flags",t),t.forEach(e=>{var t;if(this._flagToExperiments&&(null===(t=this._flagToExperiments)||void 0===t?void 0:t.has(e))){var i;const t=this._instance.getFeatureFlag(e),s=null===(i=this._flagToExperiments)||void 0===i?void 0:i.get(e);t&&(null==s?void 0:s.variants[t])&&this._applyTransforms(s.name,t,s.variants[t].transforms)}})}}previewWebExperiment(){const t=e.getWindowLocation();if(null==t?void 0:t.search){const i=wa(null==t?void 0:t.search,"__experiment_id"),s=wa(null==t?void 0:t.search,"__experiment_variant");i&&s&&(e._logInfo(`previewing web experiments ${i} && ${s}`),this.getWebExperiments(e=>{this._showPreviewWebExperiment(parseInt(i),s,e)},!1,!0))}}loadIfEnabled(){this._config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._config.disable_web_experiments&&!i)return e([]);const s=this._instance.get_property("$web_experiments");if(s&&!t)return e(s);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this._config.token}`),method:"GET",timestampMode:"query",callback:t=>e(200===t.statusCode&&t.json&&t.json.experiments||[])})}_showPreviewWebExperiment(t,i,s){const r=s.filter(e=>e.id===t);r&&r.length>0&&(e._logInfo(`Previewing web experiment [${r[0].name}] with variant [${i}]`),this._applyTransforms(r[0].name,i,r[0].variants[i].transforms))}static _matchesTestVariant(t,i){return!St(t.conditions)&&e._matchUrlConditions(t,i)&&e._matchUTMConditions(t)}static _matchUrlConditions(t,i){var s;if(St(t.conditions)||St(null===(s=t.conditions)||void 0===s?void 0:s.url))return!0;const r=e.getWindowLocation();if(r){var n,o,a;const e=ho(i,r.href);return!(null===(n=t.conditions)||void 0===n?void 0:n.url)||Id[null!==(o=null===(a=t.conditions)||void 0===a?void 0:a.urlMatchType)&&void 0!==o?o:"icontains"](t.conditions.url,e)}return!1}static getWindowLocation(){return null==je?void 0:je.location}static _matchUTMConditions(e){var t;if(St(e.conditions)||St(null===(t=e.conditions)||void 0===t?void 0:t.utm))return!0;const i=Ia();if(i.utm_source){var s,r,n,o,a,l,c,u;const t=!(null===(s=e.conditions)||void 0===s||null===(s=s.utm)||void 0===s?void 0:s.utm_campaign)||(null===(r=e.conditions)||void 0===r||null===(r=r.utm)||void 0===r?void 0:r.utm_campaign)==i.utm_campaign,d=!(null===(n=e.conditions)||void 0===n||null===(n=n.utm)||void 0===n?void 0:n.utm_source)||(null===(o=e.conditions)||void 0===o||null===(o=o.utm)||void 0===o?void 0:o.utm_source)==i.utm_source,h=!(null===(a=e.conditions)||void 0===a||null===(a=a.utm)||void 0===a?void 0:a.utm_medium)||(null===(l=e.conditions)||void 0===l||null===(l=l.utm)||void 0===l?void 0:l.utm_medium)==i.utm_medium,_=!(null===(c=e.conditions)||void 0===c||null===(c=c.utm)||void 0===c?void 0:c.utm_term)||(null===(u=e.conditions)||void 0===u||null===(u=u.utm)||void 0===u?void 0:u.utm_term)==i.utm_term;return t&&h&&_&&d}return!1}static _logInfo(e,...t){En.info(`[WebExperiments] ${e}`,t)}_applyTransforms(t,i,s){this._is_bot()?e._logInfo(Fd):"control"!==i?s.forEach(s=>{if(s.selector){var r;e._logInfo(`applying transform of variant ${i} for experiment ${t} `,s);const n=null===(r=document)||void 0===r?void 0:r.querySelectorAll(s.selector);null==n||n.forEach(e=>{const t=e;s.html&&(t.innerHTML=s.html),s.css&&t.setAttribute("style",s.css)})}}):e._logInfo("Control variants leave the page unmodified.")}_is_bot(){return Ve&&this._instance?Ic(Ve,this._config.custom_blocked_useragents):void 0}}},ah),fh={conversations:class{constructor(e){this._instance=e,this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations)return;if(this._remoteConfigSuccessful=e.ok,!e.ok)return;const t=e.config.conversations;St(t)||(Ct(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this.loadIfEnabled())}reset(){var e;null===(e=this._conversationsManager)||void 0===e||e.reset(),this._conversationsManager=null,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1}loadIfEnabled(){if(this._conversationsManager)return;if(this._isInitializing)return;if(this._instance.config.disable_conversations)return;if(On(this._instance.config))return;if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=null==tt?void 0:tt.__PosthogExtensions__;if(e&&!ft(this._isConversationsEnabled)&&this._isConversationsEnabled)if(this._remoteConfig&&this._remoteConfig.token){this._isInitializing=!0;try{const t=e.initConversations;if(t)return this._completeInitialization(t),void(this._isInitializing=!1);const i=e.loadExternalDependency;if(!i)return void this._handleLoadError(Oe);i(this._instance,"conversations",t=>{t||!e.initConversations?this._handleLoadError("Could not load conversations script",t):this._completeInitialization(e.initConversations),this._isInitializing=!1})}catch(e){this._handleLoadError("Error initializing conversations",e),this._isInitializing=!1}}else Td.error("Conversations enabled but missing token in remote config.")}_completeInitialization(e){if(this._remoteConfig)try{this._conversationsManager=e(this._remoteConfig,this._instance),this._loadFailed=!1,Td.info("Conversations loaded successfully")}catch(e){this._handleLoadError("Error completing conversations initialization",e)}else Td.error("Cannot complete initialization: remote config is null")}_handleLoadError(e,t){Td.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():Td.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return!0===this._isConversationsEnabled&&!bt(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":On(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":ft(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?St(this._remoteConfig)||!this._remoteConfig.token?"missing_token":(null==tt?void 0:tt.__PosthogExtensions__)?this._isInitializing?"initializing":this._loadFailed?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.isVisible())&&void 0!==e&&e}sendMessage(e,t,i){var s=this;return Lt(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,i):(Td.warn(Rd),null)})()}getMessages(e,t){var i=this;return Lt(function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(Td.warn(Rd),null)})()}markAsRead(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Td.warn(Rd),null)})()}getTickets(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Td.warn(Rd),null)})()}requestRestoreLink(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(Td.warn(Rd),null)})()}restoreFromToken(e){var t=this;return Lt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(Td.warn(Rd),null)})()}restoreFromUrlToken(){var e=this;return Lt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(Td.warn(Rd),null)})()}getCurrentTicketId(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null===(t=this._conversationsManager)||void 0===t?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}_onIdentityChanged(){var e;null===(e=this._conversationsManager)||void 0===e||e.setIdentity()}_onIdentityCleared(){var e;null===(e=this._conversationsManager)||void 0===e||e.clearIdentity()}}},mh={logs:class extends Bd{constructor(e){super({get(){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.logs},captureHintKey:B,get remoteConfigWillArrive(){var t,i;return!(null===(t=e._shouldDisableFlags)||void 0===t?void 0:t.call(e))||!!(null===(i=tt._POSTHOG_REMOTE_CONFIG)||void 0===i||null===(i=i[e.config.token])||void 0===i?void 0:i.config)}},()=>function(e){var t;const i={};if(i.distinctId=e.get_distinct_id(),e.sessionManager){const{sessionId:t,windowId:s,sessionStartTimestamp:r,lastActivityTimestamp:n}=e.sessionManager.checkAndGetSessionAndWindowId(!0);i.sessionId=t,i.windowId=s,St(r)||(i.sessionStartTimestamp=r),St(n)||(i.lastActivityTimestamp=n)}if((null==tt||null===(t=tt.location)||void 0===t?void 0:t.href)&&(i.currentUrl=e.config.disable_capture_url_hashes?es(tt.location.href):tt.location.href),e.featureFlags){const t=e.featureFlags.getFlags();t&&t.length>0&&(i.activeFeatureFlags=t)}return i}(e)),this._instance=e,this.name=Zc,this._listenForReconnect()}get _isRequestReady(){return this._instance.__loaded}_getConsoleLoader(){const e=Cn("[logs]"),t=null==tt?void 0:tt.__PosthogExtensions__;if(!t)return void e.error("PostHog Extensions not found.");const i=t.loadExternalDependency;if(i)return e=>{i(this._instance,"logs",i=>{const s=t.logs;e(i,(null==s?void 0:s.initializeLogs)?{initialize:e=>s.initializeLogs(e),replay(e,t){var i;return null===(i=s.replayConsoleBuffer)||void 0===i?void 0:i.call(s,e,t)}}:void 0)})};e.error(Oe)}}},yh={metrics:class{constructor(e){this._instance=e,this._logger=Cn("[metrics]"),this._disposed=!1}initialize(){this.onConfigChange()}onConfigChange(){var e;if(this._disposed)return;const t=!!(null===(e=this._instance.config.metrics)||void 0===e?void 0:e.network);t&&!this._stopNetworkMetrics?this._stopNetworkMetrics=(e=>{let t=!0;const i=()=>t?(e=>{var t;const i=null===(t=e.config.metrics)||void 0===t?void 0:t.network;return!0===i?{}:i||void 0})(e):void 0,s=Gd(e,i),r=Kd(e,i);return()=>{t=!1,s(),r()}})(this._instance):!t&&this._stopNetworkMetrics&&(this._stopNetworkMetrics(),this._stopNetworkMetrics=void 0)}_getCore(){var e;const t=null===(e=this._instance)||void 0===e||null===(e=e.config)||void 0===e?void 0:e.metrics;var i;return this._core&&this._resolvedFrom===t||(null===(i=this._core)||void 0===i||i.reset(),this._resolvedFrom=t,this._core=new Sn(this._createHost(),function(e){var t,i,s,r,n;const o=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(t=null==o?void 0:o["service.name"])&&void 0!==t?t:null==e?void 0:e.serviceName,serviceVersion:null!==(i=null==o?void 0:o["service.version"])&&void 0!==i?i:null==e?void 0:e.serviceVersion,environment:null!==(s=null==o?void 0:o["deployment.environment"])&&void 0!==s?s:null==e?void 0:e.environment,resourceAttributes:o,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:null!==(r=null==e?void 0:e.flushIntervalMs)&&void 0!==r?r:1e4,maxSeriesPerFlush:null!==(n=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==n?n:1e3}}(t),this._logger)),this._core}count(e,t=1,i){this._getCore().count(e,t,i)}gauge(e,t,i){this._getCore().gauge(e,t,i)}histogram(e,t,i){this._getCore().histogram(e,t,i)}flush(e){if(!this._core)return Promise.resolve();if(e){const t=this._core.drainWindow();return t&&this._sendMetricsBatch(t,e),Promise.resolve()}return this._core.flush().catch(e=>this._logger.error("PostHog metrics flush failed:",e))}reset(){var e;null===(e=this._core)||void 0===e||e.reset()}dispose(){var e,t;this._disposed=!0,null===(e=this._stopNetworkMetrics)||void 0===e||e.call(this),this._stopNetworkMetrics=void 0,null===(t=this._core)||void 0===t||t.reset()}_createHost(){const e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},_sendMetricsBatch:e=>t._sendMetricsBatch(e),getLibraryId:()=>i.LIB_NAME,getLibraryVersion:()=>i.LIB_VERSION}}_sendMetricsBatch(e,t){return new Promise(i=>{let s=!1;const r=e=>{s||(s=!0,clearTimeout(n),i(e))},n=setTimeout(()=>r({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(ls(ls({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),{},{fireCallbackOnDrop:!0,callback(e){const t=e.statusCode;if(t>=200&&300>t)r({kind:"ok"});else if(413===t)r({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)r({kind:"fatal",error:new Error(`metrics request failed with status ${t}`)});else{var i;r({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error(`metrics request failed with status ${t}`)})}}}))})}_metricsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},bh={webMCP:class{constructor(e){this._instance=e,this._isPatched=!1}initialize(){this.startIfEnabled()}startIfEnabled(){if(!this._instance.config.capture_webmcp||this._isPatched)return;const e=null==Ge?void 0:Ge.modelContext;if(!e||!pt(e.registerTool))return;const t=Qd.get(e);if(t)return t.instances.add(this._instance),void(this._isPatched=!0);const i={instances:new Set([this._instance])},s=e.registerTool,r=this;Au(e,"registerTool",e=>{const t=e;return function(e,...s){let n=e;try{n=r._wrapTool(e,i)}catch(i){return t.call(this,e,...s)}return t.call(this,n,...s)}}),e.registerTool!==s&&(Qd.set(e,i),this._isPatched=!0)}_wrapTool(e,t){if(!e||!pt(e.execute))return e;const i=e.execute,s=this,{tool:r,injected:n}=function(e,t){const i={intent:!1,model:!1},s=e.inputSchema;if(!function(e){return!!ft(e)||gt(e)&&Object.keys(e).every(e=>Jd.has(e)||e.startsWith("x-"))&&!0!==e.additionalProperties&&!gt(e.additionalProperties)&&(!e.type||"object"===e.type)&&(!e.properties||gt(e.properties))&&(!e.required||_t(e.required))}(s))return{tool:th(e),injected:i};const r=(null==s?void 0:s.properties)||{},n=e=>eh(r,e)||_t(null==s?void 0:s.required)&&s.required.includes(e);if(i.intent=t.intent&&!n("context"),i.model=t.model&&!n("llm_model"),!i.intent&&!i.model)return{tool:th(e),injected:i};const o=ls({},r),a=_t(null==s?void 0:s.required)?[...s.required]:[];return i.intent&&(o.context={type:"string",description:'Explain why this tool is called and how it supports the user\'s goal. Describe the abstract purpose only. Do not include personal or identifying information. Generalize specific entities as roles such as "a customer".'},a.includes("context")||a.push("context")),i.model&&(o.llm_model={type:"string",description:'The exact model identifier you are running as, taken from your system prompt or environment. Pass "unknown" if you do not know it. Never guess.'},a.includes("llm_model")||a.push("llm_model")),{tool:th(e,ls(ls({},s),{},{type:(null==s?void 0:s.type)||"object",properties:o,required:a})),injected:i}}(e,function(e){const t={intent:!1,model:!1};for(const i of e.instances){const e=Xd(i.config.capture_webmcp);t.intent||(t.intent=!0===(null==e?void 0:e.intent)),t.model||(t.model=!0===(null==e?void 0:e.model))}return t}(t));return Object.defineProperty(r,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const a=new Date,l=function(e,t){if(!gt(e))return{};try{const i=t.intent?ih(e.context,2048,!0):void 0,s=t.model?ih(e.llm_model,256):void 0;return ls(ls({},i&&"{}"!==i?{intent:i}:{}),s&&"unknown"!==s.toLowerCase()?{model:s}:{})}catch(e){return{}}}(o[0],n),c=function(e,t){const i=e[0];if(!gt(i))return e;try{const s=t.intent&&eh(i,"context"),r=t.model&&eh(i,"llm_model");if(!s&&!r)return e;const n=ls({},i);return s&&delete n.context,r&&delete n.llm_model,[n,...e.slice(1)]}catch(t){return e}}(o,n);let u;try{u=i.apply(this===r?e:this,c)}catch(e){throw s._captureToolCall(t,r,a,{error:e,errorResult:!1},l),e}if((d=u)&&"function"==typeof d.then)return Promise.resolve(u).then(e=>{const i=sh(e)?{error:e,errorResult:!0}:void 0;return s._captureToolCall(t,r,a,i,l),e},e=>{throw s._captureToolCall(t,r,a,{error:e,errorResult:!1},l),e});var d;const h=sh(u)?{error:u,errorResult:!0}:void 0;return s._captureToolCall(t,r,a,h,l),u}}),r}_captureToolCall(e,t,i,s,r){const n=Date.now()-i.getTime();let o;for(const a of e.instances){const e=Xd(a.config.capture_webmcp);if(e){s&&!o&&(o=oh(s.error,s.errorResult));try{a.capture("$mcp_tool_call",ls(ls(ls({$mcp_source:"posthog_mcp_analytics",$mcp_interface:"webmcp",$mcp_tool_name:t.name,$mcp_resource_name:t.name,$mcp_tool_description:t.description,$mcp_server_name:null==Ke?void 0:Ke.hostname,$mcp_duration_ms:n,$mcp_is_error:!!s},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),e.intent&&r.intent?{$mcp_intent:r.intent,$mcp_intent_source:"context_parameter"}:{}),e.model&&r.model?{$mcp_llm_model:r.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:i})}catch(e){continue}}}}}};wu.__defaultExtensionClasses=ls({},ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls(ls({},ah),lh),ch),uh),dh),hh),ph),_h),gh),vh),fh),mh),yh),bh));const Sh=function(){i.SDK_DIST_CHANNEL="npm";const e=iu[vu]=new wu;return function(){function e(){e.done||(e.done=!0,fc=!1,Pn(iu,function(e){e._dom_loaded()}))}(null==Ge?void 0:Ge.addEventListener)?"complete"===Ge.readyState?e():An(Ge,"DOMContentLoaded",e,{capture:!1}):je&&En.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),e}();export{Za as Compression,dl as DEFAULT_PRODUCT_TOUR_APPEARANCE,cl as DisplaySurveyType,wu as PostHog,hl as ProductTourEventName,_l as ProductTourEventProperties,al as SurveyEventName,ll as SurveyEventProperties,Xa as SurveyEventType,tl as SurveyPosition,nl as SurveyQuestionBranchingType,rl as SurveyQuestionType,ol as SurveySchedule,il as SurveyTabPosition,sl as SurveyType,el as SurveyWidgetType,Sh as default,Sh as posthog,ml as severityLevels};
|
|
2
2
|
//# sourceMappingURL=module.no-external.js.map
|