posthog-js 1.453.1 → 1.453.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- const e="0.12.1",t={DEBUG:(!1,!1),LIB_VERSION:(e,"1.453.1"),LIB_NAME:("browser-common","web"),JS_SDK_VERSION:e};var i=t;const s="u">typeof window?window:void 0,n="u">typeof globalThis?globalThis:s,r=null==n?void 0:n.navigator,o=null==n?void 0:n.document,a=null==n?void 0:n.location,l=null==n?void 0:n.fetch,c=(null==n?void 0:n.XMLHttpRequest)&&"withCredentials"in new n.XMLHttpRequest?n.XMLHttpRequest:void 0,u=null==n?void 0:n.AbortController,d=null==n?void 0:n.CompressionStream,h=null==r?void 0:r.userAgent,_="undefined"!=typeof globalThis?globalThis:s;_&&"undefined"==typeof self&&(_.self=_),_&&"undefined"==typeof File&&(_.File=function(){});const p=null!=s?s:{},g=e=>{var t;return(null==e?void 0:e.config.require_subresource_integrity)?e.__loadExternalDependency:null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.loadExternalDependency},f="$early_access_features",v="$active_feature_flags",m="$feature_flag_details",y="$feature_flag_errors",b="$feature_flag_evaluated_at",S="$feature_flag_request_id",w="$minimal_flag_called_events",C="$enabled_feature_flags",E="$stored_group_properties",k="$stored_person_properties",x="$flag_call_reported",P="$flag_call_reported_session_id",T="$feature_flag_payloads",I="$override_feature_flags",F="$override_feature_flag_payloads",R="visibilitychange",A="$autocapture_disabled_server_side",M="$surveys",O="$surveys_loaded_at",L="PostHog loadExternalDependency extension not found.",D="$surveys_activated",N="$surveys_activated_session",B="$surveys_activated_timestamps",U="$people_distinct_id",z="distinct_id",H="$device_id",q="$device_model",j="__alias",W="__cmpns",V="$fbc",G="$fbc_persistence",K="$fbp",Y="$fbp_persistence",Q="__timers",J="$heatmaps_enabled_server_side",Z="$exception_capture_enabled_server_side",X="$error_tracking_suppression_rules",ee="$error_tracking_capture_extension_exceptions",te="$web_vitals_enabled_server_side",ie="$dead_clicks_enabled_server_side",se="$product_tours_enabled_server_side",ne="$logs_capture_enabled_server_side",re="$web_vitals_allowed_metrics",oe="$session_recording_remote_config",ae="$session_recording_enabled_server_side",le="$replay_sample_rate",ce="$replay_override_sampling",ue="$replay_override_linked_flag",de="$replay_override_url_trigger",he="$replay_override_event_trigger",_e="$sesid",pe="$session_is_sampled",ge="$session_past_minimum_duration",fe="$session_recording_url_trigger_activated_session",ve="$session_recording_event_trigger_activated_session",me="$debug_first_full_snapshot_timestamp",ye="$sess_rec_flush_size",be="$groups",Se="ph_product_tours",we="$product_tours_activated",Ce="$product_tours_activated_session",Ee="$conversations_widget_session_id",ke="$conversations_ticket_id",xe="$conversations_widget_state",Pe="$conversations_user_traits",Te="$user_state",Ie="$client_session_props",Fe="$capture_rate_limit",Re="$initial_campaign_params",Ae="$initial_referrer_info",$e="$initial_person_info",Me="$epp",Oe="$posthog_cookieless",Le="$cookieless_mode",De="$sdk_debug_extensions_init_method",Ne="$sdk_debug_extensions_init_time_ms",Be="$sdk_debug_recording_script_not_loaded",Ue="$sdk_debug_replay_stale_config",ze="$sdk_debug_replay_event_trigger_status",He="$sdk_debug_replay_linked_flag_trigger_status",qe="$sdk_debug_replay_matched_recording_trigger_groups",je="$sdk_debug_replay_pending_trigger_conditions",We="$sdk_debug_replay_remote_trigger_matching_config",Ve="$sdk_debug_replay_trigger_groups_count",Ge="$sdk_debug_replay_url_trigger_status",Ke="$session_recording_start_reason",Ye="anonymous",Qe="identified",Je="identified_only",Ze="beforeunload",Xe="$pageview",et="$pageleave",tt="$identify",it="$groupidentify";var st=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}({}),nt=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"],ot=["token"];function at(e,t){return-1!==e.indexOf(t)}const lt=function(e){return e.trim()},ct=function(e){return e.replace(/^\$/,"")};function ut(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 dt=Object.prototype,ht=dt.hasOwnProperty,_t=dt.toString,pt=Array.isArray||function(e){return"[object Array]"===_t.call(e)},gt=e=>"function"==typeof e,ft=e=>e===Object(e)&&!pt(e),vt=e=>{if(ft(e)){for(const t in e)if(ht.call(e,t))return!1;return!0}return!1},mt=e=>void 0===e,yt=e=>"[object String]"==_t.call(e),bt=e=>yt(e)&&0===e.trim().length,St=e=>null===e,wt=e=>mt(e)||St(e),Ct=e=>"[object Number]"==_t.call(e)&&e==e,Et=e=>Ct(e)&&e>0,kt=e=>"[object Boolean]"===_t.call(e),xt=e=>at(rt,e),Pt=e=>at(ot,e);function Tt(e){return null===e||"object"!=typeof e}function It(e,t){return{}.toString.call(e)===`[object ${t}]`}function Ft(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 At(e,Error)}}function Rt(e){return"u">typeof Event&&At(e,Event)}function At(e,t){try{return e instanceof t}catch(e){return!1}}const $t=[!0,"true",1,"1","yes"],Mt=e=>at($t,e),Ot=[!1,"false",0,"0","no"];function Lt(e,t,i,s,n,r,o){try{var a=e[r](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,n)}function Dt(e){return function(){var t=this,i=arguments;return new Promise(function(s,n){var r=e.apply(t,i);function o(e){Lt(r,s,n,o,a,"next",e)}function a(e){Lt(r,s,n,o,a,"throw",e)}o(void 0)})}}const Nt=["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","lightpanda","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"],Bt=new Map,Ut=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=Bt.get(i);if(void 0!==s)return s;const n=e.toLowerCase(),r=Nt.concat(t).some(e=>-1!==n.indexOf(e.toLowerCase()));return 256>Bt.size||Bt.clear(),Bt.set(i,r),r};function zt(e,t,i,s,n){return t>i&&(s.warn("min cannot be greater than max."),t=i),Ct(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: "+n),zt(null!=n?n:i,t,i,s))}var Ht=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=zt(e.bucketSize,0,100,e._logger),this._refillRate=zt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=zt(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 n=this._buckets[s];return n?this._applyRefill(n,i):(n={tokens:this._bucketSize,lastAccess:i},this._buckets[s]=n),0===n.tokens||(n.tokens--,0===n.tokens&&(null===(t=this._onBucketRateLimited)||void 0===t||t.call(this,e)),0===n.tokens)}stop(){this._buckets={}}};const qt="Mobile",jt="Android",Wt="Tablet",Vt="Android Tablet",Gt="iPad",Kt="Apple Watch",Yt="Safari",Qt="BlackBerry",Jt="Samsung Internet",Zt="Chrome",Xt="Chrome iOS",ei="Internet Explorer",ti="Internet Explorer Mobile",ii="Opera",si="Microsoft Edge",ni="Firefox",ri="Firefox iOS",oi="Nintendo",ai="PlayStation",li="Xbox",ci="Android Mobile",ui="Mobile Safari",di="Windows",hi="Windows Phone",_i="Nokia",pi="Ouya",gi="Generic tablet",fi="Konqueror",vi="Oculus Browser",mi="Vivaldi",yi="Yandex",bi="Whale",Si="DuckDuckGo",wi="Pale Moon",Ci="Waterfox",Ei="Brave",ki="Claude",xi="Codex",Pi="ChatGPT",Ti="Google Search App",Ii=new RegExp("Version/(\\d+(\\.\\d+)?)"),Fi=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),Ri=new RegExp(li,"i"),Ai=new RegExp("PlayStation \\w+","i"),$i=new RegExp("Nintendo \\w+","i"),Mi=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 n=function(e){return(null==e?void 0:e.brave)?Ei:null}(i);return n||((null==s?void 0:s.detectGoogleSearchApp)&&at(e,"GSA/")?Ti:at(e," OPR/")&&at(e,"Mini")?"Opera Mini":at(e," OPR/")?ii:Mi.test(e)?Qt:at(e,"IEMobile")||at(e,"WPDesktop")?ti:at(e,"OculusBrowser")?vi:at(e,"SamsungBrowser")?Jt:at(e,"Edge")||at(e,"Edg/")?si:at(e,"Vivaldi/")?mi:at(e,"YaBrowser/")?yi:at(e,"Whale/")?bi:at(e,"DuckDuckGo/")||at(e,"Ddg/")?Si:at(e,"Claude/")?ki:at(e,"Codex/")?xi:at(e,"ChatGPT/")?Pi:at(e,"FBIOS")?"Facebook Mobile":at(e,"UCWEB")||at(e,"UCBrowser")?"UC Browser":at(e,"CriOS")?Xt:at(e,"CrMo")||at(e,Zt)?Zt:at(e,jt)&&at(e,Yt)?ci:at(e,"FxiOS")?ri:at(e.toLowerCase(),fi.toLowerCase())?fi:at(e,"Brave/")?Ei:((e,t)=>t&&at(t,"Apple")||function(e){return at(e,Yt)&&!at(e,Zt)&&!at(e,jt)}(e))(e,t)?at(e,qt)?ui:Yt:at(e,"PaleMoon/")?wi:at(e,"Waterfox/")?Ci:at(e,ni)?ni:at(e,"MSIE")||at(e,"Trident/")?ei:at(e,"Gecko")?ni:"")},Di={[ti]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[si]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Zt]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Xt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Yt]:[Ii],[ui]:[Ii],[ii]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[ni]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[ri]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[fi]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Qt]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ii],[ci]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[Jt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[vi]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[mi]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[yi]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[bi]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Ei]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[ki]:[Fi],[xi]:[Fi],[Pi]:[Fi],[Si]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[wi]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Ci]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Ti]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[ei]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},Ni=function(e,t,i,s){const n=Li(e,t,i,s),r=Di[n];if(mt(r))return null;for(let t=0;r.length>t;t++){const i=e.match(r[t]);if(i)return parseFloat(i[i.length-2])}return null},Bi=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[li,e&&e[1]||""]],[new RegExp(oi,"i"),[oi,""]],[new RegExp(ai,"i"),[ai,""]],[Mi,[Qt,""]],[new RegExp(di,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[hi,""];if(new RegExp(qt).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"),[di,e]}return[di,""]}],[/((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=mt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[jt,[e[2],e[3],e[4]||"0"].join(".")]:[jt,""]],[/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",""]]],Ui=function(e){for(let t=0;Bi.length>t;t++){const[i,s]=Bi[t],n=i.exec(e),r=n&&(gt(s)?s(n,e):s);if(r)return r}return["",""]},zi=function(e){return $i.test(e)?oi:Ai.test(e)?ai:Ri.test(e)?li:new RegExp(pi,"i").test(e)?pi:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?hi:/iPad/.test(e)?Gt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Kt:Mi.test(e)?Qt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(_i,"i").test(e)?_i:/(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(qt).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)?jt:Vt:new RegExp("(pda|Mobile)","i").test(e)?"Generic mobile":new RegExp(Wt,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?gi:""},Hi=function(e,t){var i;const s=zi(e);return s===Gt||s===Vt||"Kobo"===s||"Kindle Fire"===s||s===gi?Wt:s===oi||s===li||s===ai||s===pi?"Console":s===Kt?"Wearable":s?qt:"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!==(n=null==t?void 0:t.screenWidth)&&void 0!==n?n:0,null!==(r=null==t?void 0:t.screenHeight)&&void 0!==r?r:0)/(null!==(o=null==t?void 0:t.devicePixelRatio)&&void 0!==o?o:1)?qt:Wt:"Desktop";var n,r,o},qi=/\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",qi],[/\bFBAN\/EMA\b/i,"Facebook Lite",qi],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",qi],[/\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 Yi=3e5;var Qi=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,Yi);if(!t)return this._installedAt=i,void(this._until=i+s);this._until=Math.max(this._until,Math.min(i+s,this._installedAt+Yi))}remainingMs(){const e=Date.now();if(this._installedAt-5e3>e)return this.reset(),0;const t=Math.min(Yi,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 Ji=/^[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)&&Ji.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 ns.apply(this,arguments)}function ns(){return(ns=Dt(function*(e,t,i){let s;try{return yield Promise.race([e,new Promise((e,n)=>{s=is(()=>{try{null==i||i(),e()}catch(e){n(e)}},t)})])}finally{clearTimeout(s)}})).apply(this,arguments)}function rs(e){return rs="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},rs(e)}function os(e,t,i){return(t=function(e){var t=function(e){if("object"!=rs(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!=rs(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==rs(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 n=i?Object.keys(i):[],r=s?Object.keys(s):[];if(hs&&ps(i,n,us)&&ps(s,r,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 n of t){const t=i[n];if(!t)continue;const r=null==cs?void 0:cs[n];if(r){hs[r]=t;continue}const o=e(n);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[n]=i;break}}}};return s&&o(r,s),i&&o(n,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),n=this.buildParsingContext(t),r=this.parseStacktrace(s,n);return{$exception_list:this.convertToExceptionList(r,i),$exception_level:"error"}}modifyFrames(e){var t=this;return Dt(function*(){for(const i of e)i.stacktrace&&i.stacktrace.frames&&pt(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,n;if(null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch(e){}return ls(ls({},e),{},{cause:s,stack:n,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 Dt(function*(){let i=e;for(const e of t.modifiers)i=yield e(i);return i})()}convertToExceptionList(e,t){const i=[],s=(e,n,r)=>{var o;const a=i.length,l=void 0===n?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:r,synthetic:e.synthetic,exception_id:a,parent_id:n},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(Ft(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 pt(t)?t:void 0}i=Object.getPrototypeOf(i)}}}catch(e){}}buildCoercingContext(e,t,i=0){let s=0,n=0,r=!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;r||(r=!!_);try{if(p=this.applyCoercers(e,c),!p)throw l}catch(e){if(e===l)return void(0===i&&s--);if(!r)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 f=[];for(let e=0;50>s&&1e3>n&&g>e;e++){let i;n++;try{i=c.next(_[e])}catch(e){s++,i=this.coerceFallback(u(t+1))}i&&f.push(i)}return ls(ls({},p),{},{errors:f})},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 fs=/^([a-z][a-z0-9.+-]+):/i,vs=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ms(e){if(!e||"<anonymous>"===e)return!1;const t=fs.exec(e);return!t||vs.includes(t[1].toLowerCase())}function ys(e,t,i,s,n){const r={platform:e,filename:t,function:"<anonymous>"===i?"?":i,in_app:ms(t)};return mt(s)||(r.lineno=s),mt(n)||(r.colno=n),r}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,Cs=/\((\S*)(?::(\d+))(?::(\d+))\)/,Es=(e,t)=>{const i=Ss.exec(e);if(i){const[,e,s,n]=i;return ys(t,e,"?",+s,+n)}const s=ws.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){const e=Cs.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,xs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ps=(e,t)=>{const i=ks.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){const e=xs.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)}},Ts=/\(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 Fs(e){for(let t=1;10>=t;t++){const i=e.length-2*t;if(0>i)break;let s=!0;for(let n=0;t>n;n++)if(!Is(e[i+n],e[i+t+n])){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=$s(e,t);s&&e.splice(i+s===e.length?i:t.start,s)}function As(e,t){let i=t.start;for(;i>0&&Is(e[i-1],e[i-1+t.length]);)i--;return t.start-i}function $s(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 Ms(e,t){const i=t[0];let s=e.length-(i?As(e,i):0);for(const i of t)s-=$s(e,i);return s}function Os(e,t,i){for(let s=0;e.length>s;s++){const n=e[(t+s)%e.length],r=e[(i+s)%e.length];if(n!==r)return r>n}return!1}var Ls=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const i=yt(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 It(e,"DOMException")}isDOMError(e){return It(e,"DOMError")}},Ds=class{match(e){return Ft(e)}coerce(e,t){var i;const s=this.getStack(e),n=void 0===s?null===(i=t.syntheticException)||void 0===i?void 0:i.stack:void 0,r=!!n;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:n,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}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!!It(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 yt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i;const s=e,n=null!==(t=s.lineno)&&void 0!==t?t:0,r=null!==(i=s.colno)&&void 0!==i?i:0;if(yt(s.filename)&&0!==s.filename.length&&0!==n)return`Error\n at ${s.filename}:${n}:${r}`}};const Bs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var Us=class{match(e){return"string"==typeof e}coerce(e,t){var i;const[s,n]=this.getInfos(e);return{type:null!=s?s:"Error",value:null!=n?n: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 zs=["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]";let s="";for(const e of i){const i=s?`${s}, ${e}`:e;if(i.length>t)break;s=i}return s}var qs=class{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s;const n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{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(Rt(e))return e.constructor.name;const t="name"in e?e.name:void 0;return yt(t)&&!bt(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 yt(e)&&!bt(e)&&zs.indexOf(e)>=0}getStack(e){try{return yt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:yt(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(Ft(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 Rt(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 Tt(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 It(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Rt(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 Tt(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",Ys=new Set([Gs,Ks]),Qs={enabled:!0,max_bytes:32768};function Js(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Qs.enabled,max_bytes:Xs(e.max_bytes,Qs.max_bytes)}:ls({},Qs)}var Zs=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Js(e)}setConfig(e){this._config=Js(e),this._trimToMaxBytes()}add(e){const t=function(e){let t;try{t=ut(e)}catch(e){return}try{const e=JSON.parse(t);if(!ft(e))return;const i=e,s=i[Gs],n=i[Ks];if(!yt(s)||0===s.trim().length)return;if(!yt(n)&&!Ct(n))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(!Ct(e)||1/0===e||-1/0===e)return t;const i=Math.floor(e);return 0>i?t:i}const en=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function tn(e){return"string"==typeof e||e}function sn(e){return"string"==typeof e?e:void 0}const nn=["$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","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],rn="NativeGzipValidationError",on=e=>e.length>=2&&31===e[0]&&139===e[1],an=(e,t)=>e===nt.GZipJS||t===nt.GZipJS||"gzip"===t,ln=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):"");let cn;const un=e=>{throw Xi(rn,`Native gzip produced invalid output: ${e}`)};let dn=0,hn=!1;const _n=function(){var e=Dt(function*(e,t){18>e.size&&un("too-short");const i=new Uint8Array(yield e.slice(0,10).arrayBuffer());on(i)&&8===i[2]||un("invalid-header");const s=new DataView(yield e.slice(e.size-8).arrayBuffer()),n=t.length>>>0;s.getUint32(4,!0)!==n&&un("invalid-size"),(hn||3>dn)&&(s.getUint32(0,!0)!==(e=>{const t=(()=>{if(cn)return cn;cn=[];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;cn[e]=t>>>0}return cn})();let i=4294967295;for(let s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&(hn=!0,un("invalid-crc")),dn++)});return function(t,i){return e.apply(this,arguments)}}();function pn(){return pn=Dt(function*(e,t=!0,i){try{const t=(new TextEncoder).encode(e),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),r=n.write(t).then(()=>n.close()).catch((s=Dt(function*(e){try{yield n.abort(e)}catch(e){}throw e}),function(e){return s.apply(this,arguments)})),o=new Response(i.readable).blob(),[a]=yield Promise.all([o,r]);return yield _n(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}),pn.apply(this,arguments)}function gn(e,t){if(null==e)return{};var i,s,n=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 r=Object.getOwnPropertySymbols(e);for(s=0;r.length>s;s++)t.includes(i=r[s])||{}.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}const fn="[redacted]",vn=/^[A-Za-z0-9+/\n\r]+=*$/,mn=/^[A-Za-z0-9_-]+={0,2}$/,yn=/[-_]/,bn=/^data:[^,\s]*;base64,/i,Sn=/^[A-Za-z0-9+/_-]+={0,2}$/,wn=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,Cn=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,En=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,kn=/[\s<>"]/,xn=(()=>new RegExp(En.source,"i"))(),Pn=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Tn=(()=>new RegExp(`^${Pn.source}`,"i"))(),In=(()=>new RegExp(Pn.source,"gi"))(),Fn=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,Rn=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,An=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,$n=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Mn=/\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,On=/(^|[^\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,Ln=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,Dn=/\d+/g,Nn=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,Bn=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;function Un(e){return function(e){return Cn.test(e)}(e)||Fn.test(e)||Rn.test(e)}function zn(e){return e.split("&",129).length>128}function Hn(e,t,i){return Un(e)||t.includes(";")&&function(e){return e.split(";").some(e=>Un(e.split("=",1)[0]))}(t)?fn:xn.test(t)?i?Kn(t,{allowNestedUrls:!1,stripPunctuation:!0}):fn:t}function qn(e,t){const i=new URLSearchParams;let s=!1,n=!1;for(const[r,o]of new URLSearchParams(e)){const e=Yn(r),a=Yn(o);s||(s=e!==r||a!==o);const l=Hn(e,a,t);s||(s=l!==a),n=Un(e)||l!==a,i.append(e,l)}return{changed:s,lastFieldSensitive:n,serialized:i.toString()}}function jn(e,t){if(!e.includes("="))return{value:Wn(e,t),lastFieldSensitive:!1};const i=qn(e,t);return{value:i.changed?i.serialized:e,lastFieldSensitive:i.lastFieldSensitive}}function Wn(e,t){return t?Kn(e,{allowNestedUrls:!1,stripPunctuation:!0}):xn.test(e)?fn:e}function Vn(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 Gn(e,t){var i;if(e.length>8192&&Tn.test(e))return fn;const{address:s,suffix:n}=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 r;try{r=new URL(s)}catch(e){return fn+n}const o=r.search.slice(1),a=""!==r.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)}}(r.hash);if(zn(o)||zn(l.head)||zn(null!==(i=l.tail)&&void 0!==i?i:""))return fn+n;let c=!1;(r.username||r.password)&&(r.username=fn,r.password="",c=!0);const u=qn(o,t.allowNestedUrls);u.changed&&(r.search=u.serialized,c=!0);const d=jn(l.head,t.allowNestedUrls),h=null===l.tail?null:(_=l.tail,d.lastFieldSensitive?{value:""===_?"":fn,lastFieldSensitive:!0}:jn(_,t.allowNestedUrls));var _;const p=null===h?d.value:`${d.value}?${h.value}`;p!==r.hash.slice(1)&&(r.hash=p,c=!0);const g=a?null!=h?h:d:u;return(c?Yn(r.toString()):s)+(g.lastFieldSensitive?"":n)}function Kn(e,t){return e.replace(En,i=>function(e,t){const i=function(e){if(!e.includes("://"))return[];const t=[...e.matchAll(In)].map(e=>e.index),i=[],s={query:!1,fragment:!1,fragmentQuery:!1};let n=0,r=!1,o="";for(let a=0;e.length>a&&t.length>n;a++){t[n]===a&&(a>0&&"="!==o&&i.push(a),n++);const l=e[a];Vn(l,s,o)?(o=l,r=!0):r&&"=&".includes(l)&&(o=l)}return i}(e);if(0===i.length)return Gn(e,t);let s="",n=0;for(const r of i)s+=Gn(e.slice(n,r),ls(ls({},t),{},{stripPunctuation:!1})),n=r;return s+Gn(e.slice(n),t)}(i,ls(ls({},t),{},{stripPunctuation:t.stripPunctuation&&i.length!==e.length})))}function Yn(e){return e.replace(wn,fn)}function Qn(e,t){return function(e){return e.length>=10240&&(vn.test(e)||function(e){const t=bn.exec(e);if(!t)return!1;let i;try{i=decodeURIComponent(e.slice(t[0].length))}catch(e){return!1}return Sn.test(i.replace(/[\r\n]/g,""))}(e)||yn.test(e)&&mn.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 n=t(e.slice(0,function(e,t){let i=t;for(;i>0&&!kn.test(e[i-1]);)i--;return i}(e,s)));if(n.length>=2*i.maxStringLength)return n+i.truncationSuffix}return t(e)}(e,e=>function(e){return Kn(e,{allowNestedUrls:!0,stripPunctuation:!0})}(function(e){let t=e.replace(An," ");return t=t.replace($n,fn),t=t.replace(Mn,fn),t=t.replace(On,`$1${fn}`),t=function(e){let t="",i=0;for(let s=tr(e,0);null!==s;s=tr(e,s[1]))t+=e.slice(i,s[0])+ir(e.slice(s[0],s[1])),i=s[1];return t+e.slice(i)}(t),t=t.replace(Ln,fn),t=t.replace(Nn,`$1${fn}`),t=t.replace(Bn,`$1${fn}`),t}(Yn(e))),t)}function Jn(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let n=e.charCodeAt(s)-48;if(0>n||n>9)return!1;i&&(n*=2,n>9&&(n-=9)),t+=n,i=!i}return t%10==0}function Zn(e,t){const i=e.charCodeAt(t);return i>=48&&57>=i}function Xn(e,t){const i=e.charCodeAt(t);return Zn(e,t)||95===i||i>=65&&90>=i||i>=97&&122>=i}function er(e,t){let i=t;for(;Zn(e,i);)i++;return i}function tr(e,t){for(let i=t;e.length>i;i++){if(!Zn(e,i)||Xn(e,i-1))continue;let t=0,s=-1,n=i;for(;;){const i=er(e,n);if(t+=i-n,13>t||Xn(e,i)||(s=i),n=i+1,!" ./-".includes(e.charAt(i))||!Zn(e,n))break}if(s>=0)return[i,s];i=n-1}return null}function ir(e){const t=[];for(let i=Dn.exec(e);null!==i;i=Dn.exec(e))t.push({digits:i[0],start:i.index,end:i.index+i[0].length});let i="",s=0,n=0;for(;t.length>n;){let r="",o=-1;for(let e=n;t.length>e&&(r+=t[e].digits,19>=r.length);e++)r.length>=13&&Jn(r)&&(o=e);0>o?n++:(i+=e.slice(s,t[n].start)+fn,s=t[o].end,n=o+1)}return i+e.slice(s)}const sr={}.propertyIsEnumerable;function nr(e,t){try{return ar(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch(e){return[]}}function rr(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:Wi};if(i.remainingNodes--,kt(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 n=e.toJSON;if("function"==typeof n)return rr(n.call(e),t,i,s+1)}catch(e){}return pt(e)?{arrayValue:{values:or(e,t,i,s+1)}}:{kvlistValue:{values:ar(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Gi(String(e))}}function or(e,t,i,s){const n=[],r=Math.min(e.length,1e3);let o=0;for(;r>o&&i.remainingNodes>0;o++)try{const r=o in e?e[o]:void 0;if(wt(r))continue;n.push(rr(r,t,i,s))}catch(e){n.push({stringValue:Vi})}return e.length>o&&n.push({stringValue:Wi}),n}function ar(e,t,i,s){const n=[];for(const r in e)if(sr.call(e,r)){if(!r){null==t||t.debug("Dropping an attribute with an empty key");continue}if(n.length>=1e3||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[r];if(St(o)||mt(o))continue;n.push({key:Gi(r),value:rr(o,t,i,s)})}catch(e){n.push({key:Gi(r),value:{stringValue:Vi}})}}return n}function lr(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 cr=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function ur(e,t){const i=Ki({},e),s={};for(const e of cr)({}).hasOwnProperty.call(i,e)&&(s[e]=i[e],delete i[e]);return[...nr(i,t),...nr(s,t)]}const dr={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 hr={text:"INFO",number:9},_r={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:hr,warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}};function pr(e){try{return Gi(String(e))}catch(e){return Vi}}function gr(e,t,i,s){const n=e.level||"info",{text:r,number:o}=_r[n]||hr,a=function(e=Date.now()){return String(e)+"000000"}(Ct(s)?s:void 0),l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),wt(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),wt(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:r,body:{stringValue:pr(e.body)},attributes:nr(c,i)};return e.trace_id&&(d.traceId=e.trace_id),e.span_id&&(d.spanId=e.span_id),mt(e.trace_flags)||(d.flags=e.trace_flags),d}function fr(e,t,i){return lr(e,t,i)}function vr(e,t,i,s){return{resourceLogs:[{resource:{attributes:ur(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}var mr=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 yr(){return.75+.5*Math.random()}function br(e,t,i,s){const n=Math.min(Math.max(0,t-1),6),r=e*Math.pow(2,n);return Math.round((void 0===s?r:Math.min(r,Math.max(s,e)))*i)}var Sr=class{constructor(e,t,i,s,n,r=()=>Promise.resolve(),o,a=()=>!1){var l;this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=n,this._waitForStoragePersist=r,this._scopeName=o,this._isConsentWithdrawn=a,this._flushTimer=new mr(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._backgroundFlushPromise=null,this._retryAfter=new Qi,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(l=t.maxQueueSize)&&void 0!==l?l: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(st.LogsQueue,[])}get throttled(){return this._retryAfter.isOpen()}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 n={record:gr(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(n))}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=pt(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 Dt(function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally(()=>{e._flushPromise=null})),e._flushPromise})()}_flushInner(){var e=this;return Dt(function*(){var t;if(e._flushTimer.clear(),e._discardQueueIfConsentWithdrawn())return;let i=null!==(t=e._instance.getPersistedProperty(st.LogsQueue))&&void 0!==t?t:[];if(0===i.length)return;const s=i.length;let n=0;for(;i.length>0&&s>n;){var r,o;if(e._discardQueueIfConsentWithdrawn())return;const t=e._queueGeneration;e._evictedSinceAdvance=0;const s=Math.min(i.length,e._maxBatchRecordsPerPost),a=i.slice(0,s),l=vr(a.map(e=>e.record),e._buildResourceAttributes(),null!==(r=e._scopeName)&&void 0!==r?r: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(st.LogsQueue))&&void 0!==o?o:[],n+=a.length,"fatal"===c.kind)throw c.error}}})()}_discardQueueIfConsentWithdrawn(){return!!this._isConsentWithdrawn()&&(this._hasQueuedRecords()&&this.clearQueue(),!0)}_persistQueueAdvance(e){var t=this;return Dt(function*(){var i;const s=Math.max(0,e-t._evictedSinceAdvance),n=null!==(i=t._instance.getPersistedProperty(st.LogsQueue))&&void 0!==i?i:[];t._instance.setPersistedProperty(st.LogsQueue,n.slice(s)),yield t._waitForStoragePersist()})()}_buildResourceAttributes(){return fr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(this._instance.optedOut)return;const i=null!==(t=this._instance.getPersistedProperty(st.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(st.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(br(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){const e=this._instance.getPersistedProperty(st.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Dt(function*(){t._flushTimer.clear();const i=t.flush().catch(()=>{});void 0!==e?yield ss(i,e):yield i})()}flushWithTimeout(e){var t=this;return Dt(function*(){const i=t.flush();yield ss(i,e,()=>{i.catch(()=>{})})})()}flushInBackground(){if(this._backgroundFlushPromise)return this._backgroundFlushPromise;const e=this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},e=>{this._consecutiveFlushFailures++,this._flushJitter=yr(),this._logger.error("PostHog logs flush failed:",e)}).finally(()=>{this._backgroundFlushPromise===e&&(this._backgroundFlushPromise=null),!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())});return this._backgroundFlushPromise=e,e}_flushInBackground(){this.flushInBackground()}};const wr=/^[0-9a-f]+$/;function Cr(e,t,i){return"string"==typeof e&&e.length===t&&e!==i&&wr.test(e)}const Er=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;const kr="00",xr=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Pr(e){return String(e)+"000000"}function Tr(e,t,i,s){let n="";return s&&(n=Object.keys(s).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(s[e])}`).join(",")),`${e}\0${t}\0${null!=i?i:""}\0${n}`}var Ir=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushTimer=new mr(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._queuedFlush=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new Qi,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,bounds:pt(null==i?void 0:i.bounds)?i.bounds.slice():null==i?void 0:i.bounds})}flush(){var e=this;const t=this._flushPromise,i=function(){var i=Dt(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}flushCoalesced(){var e,t;return this._isBackingOff()?null!==(e=this._flushPromise)&&void 0!==e?e:Promise.resolve():(this._queuedFlush||(this._queuedFlush=(null!==(t=this._flushPromise)&&void 0!==t?t:Promise.resolve()).catch(()=>{}).then(()=>(this._queuedFlush=null,this._isBackingOff()?void 0:this.flush()))),this._queuedFlush)}_isBackingOff(){return this._consecutiveFlushFailures>0||this._retryAfter.remainingMs()>0}drainWindow(){if(0===this._series.size)return null;const e=this._series;return this._startWindow(),this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._queuedFlush=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=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&&"gauge"!==t.type&&"histogram"!==t.type)return void this._logger.warn(`Dropping metric '${t.name}': unknown type '${String(t.type)}'`);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=Tr(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 n,r=this._series.get(s);if(!r&&!this._admitNewSeries())return;if("histogram"===t.type&&(n=this._histogramBounds(t.name,t.unit,t.bounds),!n))return;r||(r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now(),hist:n&&Rr(n)},this._series.set(s,r));const o=this._typeByName.get(t.name);void 0===o?this._typeByName.set(t.name,t.type):o===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(r,t.value);const a=this._activeTraceContext();a&&(r.exemplar=ls(ls({},a),{},{value:t.value,timeMs:Date.now()})),this._armFlushTimer()}_activeTraceContext(){try{var e,t;const i=function(e){const t=function(e){if("string"!=typeof e)return;const t=Er.exec(e.trim());if(!t)return;const[,i,s,n,r,o]=t;return"ff"===i||"00"===i&&o||!function(e){return Cr(e,32,"00000000000000000000000000000000")}(s)||!function(e){return Cr(e,16,"0000000000000000")}(n)?void 0:{version:i,traceId:s,spanId:n,flags:r}}(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:(i=t.flags,1&parseInt(i,16)?"01":kr)};var i}(null===(e=(t=this._instance).getActiveSpan)||void 0===e||null===(e=e.call(t))||void 0===e?void 0:e.traceparent());if(i&&"01"===i.flags)return{traceId:i.traceId,spanId:i.spanId}}catch(e){}}_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)}_histogramBounds(e,t,i){if(void 0!==i&&!function(e){if(!pt(e)||0===e.length)return!1;for(let t=0;e.length>t;t++)if(!Number.isFinite(e[t])||t>0&&e[t-1]>=e[t])return!1;return!0}(i))return void this._logger.warn(`Dropping histogram '${e}': bounds must be a non-empty array of finite, strictly increasing numbers`);const s=Tr("histogram",e,t,void 0),n=this._boundsByHistogram.get(s);if(n)return this._warnOnBoundsConflict(e,s,n,i),n;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),i&&!Fr(i,xr))return;return xr}const r=i?i.slice():xr;return this._boundsByHistogram.set(s,r),r}_warnOnBoundsConflict(e,t,i,s){Fr(i,null!=s?s:xr)||this._boundsConflictWarned.has(t)||(this._boundsConflictWarned.add(t),this._logger.warn(`Histogram '${e}' already uses the bounds [${i.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_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":{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,i.bounds)]+=1;break}}}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=pt(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(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_doFlush(){var e=this;return Dt(function*(){if(e._flushTimer.clear(),0===e._series.size)return;const t=e._series;e._startWindow();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=yr()):(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 lr(e,t,i)}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:ur(i)},scopeMetrics:[{scope:{name:s,version:n},metrics:t}]}]};var t,i,s,n}_buildMetrics(e){const t=Pr(Date.now()),i=new Map;for(const o of e.values()){var s;const e=Tr(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=nr(null!==(s=o.attributes)&&void 0!==s?s:{},this._logger),c=Pr(o.windowStartMs),u=Ar(o.exemplar);if("count"===o.type){var n;const e=ls({attributes:l,startTimeUnixNano:c,timeUnixNano:t,asDouble:null!==(n=o.total)&&void 0!==n?n:0},u);a.sum.dataPoints.push(e)}else if("gauge"===o.type){var r;const e=ls({attributes:l,timeUnixNano:t,asDouble:null!==(r=o.last)&&void 0!==r?r:0},u);a.gauge.dataPoints.push(e)}else{const e=o.hist,i=ls({attributes:l,startTimeUnixNano:c,timeUnixNano:t,count:e.count,sum:e.sum,min:e.min,max:e.max,bucketCounts:e.bucketCounts,explicitBounds:e.bounds},u);a.histogram.dataPoints.push(i)}}return Array.from(i.values())}_mergeWindowBack(e){for(const[n,r]of e){var t;const e=this._series.get(n);if(e)switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=null!==(t=e.exemplar)&&void 0!==t?t:r.exemplar,e.type){case"count":var i,s;e.total=(null!==(i=e.total)&&void 0!==i?i:0)+(null!==(s=r.total)&&void 0!==s?s:0);break;case"gauge":break;case"histogram":{const t=e.hist,i=r.hist;t.count+=i.count,t.sum+=i.sum,t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max);for(let e=0;t.bucketCounts.length>e;e++)t.bucketCounts[e]+=i.bucketCounts[e];break}}else this._admitNewSeries()&&this._series.set(n,r)}}};function Fr(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;e.length>i;i++)if(e[i]!==t[i])return!1;return!0}function Rr(e){return{bounds:e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:new Array(e.length+1).fill(0)}}function Ar(e){return e?{exemplars:[{filteredAttributes:[],timeUnixNano:Pr(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}:{}}const $r=(e,{debugEnabled:i}={})=>{const s={_log(s,...n){let r;try{r=typeof window>"u"?void 0:window}catch(e){return}r&&(t.DEBUG||r.POSTHOG_DEBUG||i)&&!mt(r.console)&&r.console&&("__rrweb_original__"in r.console[s]?r.console[s].__rrweb_original__:r.console[s])(e,...n)},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)=>$r(`${e} ${t}`,i)};return s},Mr=$r("[PostHog.js]"),Or=(e,t)=>Mr.createLogger(e,t);function Lr(e,t){pt(e)&&e.forEach(t)}function Dr(e,t){if(!wt(e))if(pt(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(const i in e)ht.call(e,i)&&t(e[i],i)}const Nr=function(e,...t){for(const i of t)for(const t in i)void 0!==i[t]&&(e[t]=i[t]);return e};function Br(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 Ur=function(e){return function(...t){try{return e.apply(this,t)}catch(e){Mr.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Mr.critical(e)}}},zr=function(e){const t={};return Dr(e,function(e,i){(yt(e)&&e.length>0||Ct(e))&&(t[i]=e)}),t};function Hr(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 qr=["herokuapp.com","vercel.app","netlify.app"];function jr(e){const t=null==e?void 0:e.hostname;if(!yt(t))return!1;const i=t.split(".").slice(-2).join(".");for(const e of qr)if(i===e)return!1;return!0}function Wr(e,t,i,s){const{capture:n=!1,passive:r=!0}=null!=s?s:{};null==e||e.addEventListener(t,i,{capture:n,passive:r})}function Vr(e){return"ph_toolbar_internal"===e.name}const Gr=e=>{if(o){try{const t=e+"=",i=o.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}};var Kr=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,s,n){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||!Number.isInteger(n)||0>t||0>i||0>s||0>n||t>0xffffffffffff||i>4095||s>1073741823||n>4294967295)throw new RangeError("invalid field value");const r=new Uint8Array(16);return r[0]=t/Math.pow(2,40),r[1]=t/Math.pow(2,32),r[2]=t/Math.pow(2,24),r[3]=t/Math.pow(2,16),r[4]=t/256,r[5]=t,r[6]=112|i>>>8,r[7]=i,r[8]=128|s>>>24,r[9]=s>>>16,r[10]=s>>>8,r[11]=s,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new e(r)}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}},Yr=class{generate(){const e=this.generateOrAbort();if(!mt(e))return e;{this._timestamp=0;const e=this.generateOrAbort();if(mt(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const e=(()=>{const e=Date.now();return Ct(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 Kr.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 Zr}};const Qr=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};let Jr;var Zr=class{nextUint32(){var e;return this._buffer.length>this._cursor||((null!==(e=Jr)&&void 0!==e?e:Jr="u">typeof window&&!mt(window.crypto)&&crypto.getRandomValues?e=>{try{return crypto.getRandomValues(e)}catch(t){return Qr(e)}}:Qr)(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}};let Xr;const eo=()=>to().toString(),to=()=>(Xr||(Xr=new Yr)).generate();let io="";const so=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let no=null;const ro={_is_supported(){if(!St(no))return no;if(no=!1,o)try{const e=`__ph_cookie_support_${eo()}`;ro._set(e,"xyz"),no='"xyz"'===Gr(e),ro._remove(e)}catch(e){no=!1}return no},_error(e){Mr.error("cookieStore error: "+e)},_get:Gr,_parse(e){let t;try{t=JSON.parse(ro._get(e))||{}}catch(e){}return t},_set(e,t,i,s,n){if(!o)return!1;try{let r="",a="";const l=function(e,t){if(t){let t=function(e,t=o){if(io)return io;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";const i=e.split(".");let s=Math.min(i.length,8);const n="dmn_chk_"+eo();for(;!io&&s--;){const e=i.slice(s).join("."),r=n+"=1;domain=."+e+";path=/";t.cookie=r+";max-age=3",t.cookie.includes(n)&&(t.cookie=r+";max-age=0",io=e)}return io}(e);if(!t){const i=(e=>{const t=e.match(so);return t?t[0]:""})(e);i!==t&&Mr.info("Warning: cookie subdomain discovery mismatch",i,t),t=i}return t?"; domain=."+t:""}return""}(o.location.hostname,s);if(i){const e=new Date;e.setTime(e.getTime()+864e5*i),r="; expires="+e.toUTCString()}n&&(a="; secure");const c=e+"="+encodeURIComponent(JSON.stringify(t))+r+"; SameSite=Lax; path=/"+l+a;return c.length>3686.4&&Mr.warn("cookieStore warning: large cookie, len="+c.length),o.cookie=c,!0}catch(e){return!1}},_remove(e,t){if((null==o?void 0:o.cookie)&&(!t||!St(Gr(e))))try{ro._set(e,"",-1,t)}catch(e){return}}};let oo=null;const ao={_is_supported(){if(!St(oo))return oo;let e=!0;if(mt(s))e=!1;else try{const t="__mplssupport__";ao._set(t,"xyz"),'"xyz"'!==ao._get(t)&&(e=!1),ao._remove(t)}catch(t){e=!1}return e||Mr.error("localStorage unsupported; falling back to cookie store"),oo=e,e},_error(e){Mr.error("localStorage error: "+e)},_get(e){try{return null==s?void 0:s.localStorage.getItem(e)}catch(e){ao._error(e)}return null},_parse(e){try{return JSON.parse(ao._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==s||s.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){ao._error(e)}return!1},_remove(e){try{null==s||s.localStorage.removeItem(e)}catch(e){ao._error(e)}}},lo=[k,v,C,m,T,S,b,y,x],co=[H,z,_e,pe,Me,$e,G,Te],uo=e=>e+"_cpm",ho=["__proto__","constructor","prototype"],_o=e=>{if(!ft(e))return{};const t={};return Object.keys(e).forEach(i=>{-1===ho.indexOf(i)&&(t[i]=e[i])}),t},po=(e,t=[])=>{const i={};return[...co,...t].forEach(t=>{const s=e[t];mt(s)||St(s)||""===s||(i[t]=s)}),i},go=e=>{let t=5381,i=2166136261;for(let s=0;e.length>s;s++){const n=e.charCodeAt(s);t=33*t^n,i=Math.imul(i^n,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},fo=(e,t)=>({p:t,f:go(JSON.stringify(e))}),vo=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const i=ro._parse(uo(e)),s=(null==i?void 0:i.f)===go(t)&&pt(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},mo=(e,t)=>t+"|"+(ro._get(uo(e))||""),yo={},bo={_is_supported:()=>!0,_error(e){Mr.error("memoryStorage error: "+e)},_get:e=>e in yo?yo[e]:null,_parse:e=>e in yo?yo[e]:null,_set:(e,t)=>(yo[e]=t,!0),_remove(e){delete yo[e]}};let So=null;const wo={_is_supported(){if(!St(So))return So;if(So=!0,mt(s))So=!1;else try{const e="__support__";wo._set(e,"xyz"),'"xyz"'!==wo._get(e)&&(So=!1),wo._remove(e)}catch(e){So=!1}return So},_error(e){Mr.error("sessionStorage error: ",e)},_get(e){try{return null==s?void 0:s.sessionStorage.getItem(e)}catch(e){wo._error(e)}return null},_parse(e){try{return JSON.parse(wo._get(e))||null}catch(e){}return null},_set(e,t){try{return null==s||s.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){wo._error(e)}return!1},_remove(e){try{null==s||s.sessionStorage.removeItem(e)}catch(e){wo._error(e)}}};var Co=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:at(Ot,e)?0:-1}get _storage(){const e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?ao:ro,i=t._is_supported()?t:bo;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;const t="localStorage"===e?ro:ao;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==r?void 0:r.doNotTrack,null==r?void 0:r.msDoNotTrack,p.doNotTrack,null==r?void 0:r.globalPrivacyControl].some(e=>Mt(e))}};function Eo(e,t){var i;const s=null==e||null===(i=e.config)||void 0===i?void 0:i.get_current_url;if(!gt(s))return t;try{const e=s(t);return yt(e)&&e?e:t}catch(e){return Mr.error("Error in get_current_url, falling back to window.location.href",e),t}}function ko(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 xo(e){return!!e&&1===e.nodeType}function Po(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function To(e){return!!e&&3===e.nodeType}function Io(e){return!!e&&11===e.nodeType&&xo(e.host)}function Fo(e){return e?lt(e).split(/\s+/):[]}function Ro(e,t){const i=function(e){var t;const i=typeof window>"u"?void 0:window,s=null==i||null===(t=i.location)||void 0===t?void 0:t.href;return mt(s)?void 0:Eo(e,s)}(t);return!!(i&&e&&e.some(e=>i.match(e)))}function Ao(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 Fo(t)}function $o(e){return wt(e)?null:lt(e).split(/(\s+)/).filter(e=>ua(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Mo(e){let t="";return ta(e)&&!ia(e)&&e.childNodes&&e.childNodes.length&&Dr(e.childNodes,function(e){var i;To(e)&&e.textContent&&(t+=null!==(i=$o(e.textContent))&&void 0!==i?i:"")}),lt(t)}function Oo(e){var t;return mt(e.target)?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null}const Lo=["a","button","form","input","select","textarea","label"];function Do(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 No(e,t){if(mt(t))return!0;for(const i of e)if(t.some(e=>Do(i,e)))return!0;return!1}function Bo(e){const t=e.parentNode;return!(!t||!xo(t))&&t}const Uo=[".ph-no-autocapture","[data-ph-no-autocapture]"],zo=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],Ho=(()=>[...zo,"+","-","−","–"])(),qo=(()=>Ho.length+10)(),jo=["button","a","input","select","textarea","label"],Wo=["button","link","tab","menuitem","option"],Vo=(e,t)=>/[a-z0-9]/i.test(t)?at(Ho,t)?new RegExp(`\\b${t}\\b`).test(e):e.includes(t):e===t,Go=e=>at(jo,e.tagName.toLowerCase())||at(Wo,(e.getAttribute("role")||"").toLowerCase());function Ko(e){let t="",i="";const s=e=>{xo(e)&&ta(e)&&!ia(e)&&(t+=` ${Mo(e)}`,i=i||e.getAttribute("aria-label")||"",Dr(e.childNodes,s))};s(e),t=lt(t.replace(/\s+/g," "));const n=(ua(t)?t:"").toLowerCase(),r=e.getAttribute("aria-label")||(n?"":i);return{safeText:n,ariaLabel:lt(r).toLowerCase()}}const Yo=[".ph-no-rageclick",".ph-no-capture"],Qo=["","text","search","email","password","url","tel","number"];function Jo(e,t){if(!(typeof window>"u"?void 0:window)||Zo(e))return!1;let i,s,n;var r,o;if(kt(t)?(i=!!t&&Yo,s=void 0,n=!1):(i=null!==(r=null==t?void 0:t.css_selector_ignorelist)&&void 0!==r?r:Yo,s=null==t?void 0:t.content_ignorelist,n=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(n&&function(e){return!(!e||!xo(e))&&(!!Po(e,"textarea")||(Po(e,"input")?at(Qo,(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,isComplete:l}=Xo(e,!1);return!(!l||s&&function(e,{safeText:t,ariaLabel:i}){let s;if(!0===e)s=zo;else{if(!pt(e))return!1;if(e.length>qo)return Mr.error(`[PostHog] content_ignorelist array cannot exceed ${qo} items. Use css_selector_ignorelist for more complex matching.`),!1;s=e.map(e=>e.toLowerCase())}return s.some(e=>Vo(t,e)||Vo(i,e))}(s,function(e,t){for(const e of t)if(Go(e))return Ko(e);for(const e of t){try{var i;if("pointer"!==(null===(i=window)||void 0===i?void 0:i.getComputedStyle(e).getPropertyValue("cursor")))break}catch(e){break}const t=Ko(e);if(t.safeText||t.ariaLabel)return t}return Ko(e)}(e,a))||No(a,i))}const Zo=e=>!e||Po(e,"html")||!xo(e),Xo=(e,t)=>{const i=typeof window>"u"?void 0:window;if(!i||Zo(e))return{parentIsUsefulElement:!1,targetElementList:[],isComplete:!1};let s=!1;const n=[e];let r=e;const o=new Set([e]);for(;!Po(r,"body");){const e=r.assignedSlot||r.parentNode,a=Io(e)?e.host:e&&xo(e)?e:null;if(!a)break;if(o.has(a)||o.size>=1e3)return{parentIsUsefulElement:s,targetElementList:n,isComplete:!1};if(o.add(a),Io(e))n.push(a),r=a;else{if(t||Lo.indexOf(a.tagName.toLowerCase())>-1)s=!0;else try{const e=i.getComputedStyle(a);e&&"pointer"===e.getPropertyValue("cursor")&&(s=!0)}catch(e){}n.push(a),r=a}}return{parentIsUsefulElement:s,targetElementList:n,isComplete:!0}};function ea(e){const t=new Set;let i=0,s=e;for(;s;){if(i++>=1e3||t.has(s))return!0;t.add(s);const e=Ao(s);if(at(e,"ph-sensitive")||at(e,"ph-no-capture"))return!0;const n=s.assignedSlot||s.parentNode;s=Io(n)?n.host:n&&xo(n)?n:null}return!1}function ta(e){if(ea(e))return!1;if(at(Ao(e),"ph-include"))return!0;const t=e.type||"";if(yt(t))switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=e.name||e.id||"";return!yt(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function ia(e){return!!(Po(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Po(e,"select")||Po(e,"textarea")||"true"===e.getAttribute("contenteditable"))}const sa=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}))$"),na=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,ra=[16,15,14,13],oa=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),aa=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),la=/[0-9A-Za-z_]/;function ca(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let n=e.charCodeAt(s)-48;i&&(n*=2,n>9&&(n-=9)),t+=n,i=!i}return t%10==0}function ua(e,t=!0){if(wt(e))return!1;if(yt(e)){if(e=lt(e),t?sa.test((e||"").replace(/[- ]/g,"")):function(e){let t;for(na.lastIndex=0;t=na.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 ra){const s=e+t;if(i.length>=s){const t=i.slice(e,s);if(sa.test(t)&&ca(t))return!0}}}return!1}(e))return!1;if(t?oa.test(e):function(e){let t;for(aa.lastIndex=0;t=aa.exec(e);){const e=t[1],i=t[3];if(!(e&&i&&la.test(e)&&la.test(i)))return!0}return!1}(e))return!1}return!0}function da(e){let t=Mo(e);return t=`${t} ${ha(e)}`.trim(),ua(t)?t:""}function ha(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Dr(e.childNodes,function(e){var i;if(e&&"span"===(null===(i=e.tagName)||void 0===i?void 0:i.toLowerCase()))try{const i=Mo(e);t=`${t} ${i}`.trim(),e.childNodes&&e.childNodes.length&&(t=`${t} ${ha(e)}`.trim())}catch(e){Mr.error("[AutoCapture]",e)}}),t}function _a(e){return e.replace(/"|\\"/g,'\\"')}function pa(e){const t=e.attr__class;if(t)return pt(t)?t:Fo(t)}const ga=Or("[Dead Clicks]"),fa=()=>!0,va=e=>{var t;const i=!!(null===(t=e.instance.persistence)||void 0===t?void 0:t.get_property(ie)),s=e.instance.config.capture_dead_clicks;return kt(s)?s:!!ft(s)||i};var ma=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({[ie]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript(()=>{this._start()}):this.stop()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.initDeadClicksAutocapture)?e():null===(i=g(this.instance))||void 0===i||i(this.instance,"dead-clicks-autocapture",t=>{t?ga.error("failed to load script",t):e()})}_start(){var e;if(o){if(!this._lazyLoadedDeadClicksAutocapture&&(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.initDeadClicksAutocapture)){const e=ft(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=p.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,e),this._lazyLoadedDeadClicksAutocapture.start(o),ga.info("starting...")}}else ga.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,ga.info("stopping..."))}};const ya=Or("[SegmentIntegration]");function ba(e,t,i=!0){const s=e.config.segment;if(!s)return t();const{analytics:n,filterProperties:r}=(e=>gt(e.register))(o=s)?{analytics:o}:o;var o;!function(e,t,i,s){const n=t=>{const n=()=>t.anonymousId()||eo();e.config.get_device_id=n,s&&t.id()&&(e.register({distinct_id:t.id(),$device_id:n()}),e.persistence.set_property(Te,Qe)),i(s?void 0:t.anonymousId()||void 0)},r=t.user();"then"in r&&gt(r.then)?r.then(n):n(r)}(e,n,i=>{n.register(((e,t,{filterProperties:i}={})=>{"undefined"!=typeof Promise&&Promise.resolve||ya.warn("This browser does not have Promise support, and can not use the segment integration");const s=(s,n)=>{if(!n)return s;const r=!!t&&s.event.anonymousId===t&&!s.event.userId;r||s.event.userId||s.event.anonymousId===e.get_distinct_id()||(ya.info("No userId set, resetting PostHog"),e.reset()),r||(t=void 0),s.event.userId&&s.event.userId!==e.get_distinct_id()&&(ya.info("UserId set, identifying with PostHog"),e.identify(s.event.userId));let o=e.calculateEventProperties(n,s.event.properties);if(!wt(i)){const e=s.event.properties||{},t={};for(const i of Object.keys(o))ht.call(e,i)||(t[i]=o[i]);const n=((e,t)=>{const i=pt(e)?e:[e];let s=ls({},t);for(const e of i)try{if(s=e(s),wt(s))return null}catch(e){return ya.error("Error in Segment filterProperties:",e),null}return s})(i,t);if(wt(n))return s;o=n}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,Xe)},identify(e){return s(e,tt)},screen(e){return s(e,"$screen")}}})(e,i,{filterProperties:r})).then(()=>{t()},e=>{ya.error("Failed to register the Segment integration",e),t()})},i)}const Sa="posthog-js";function wa(e,{organization:t,projectId:i,prefix:s,severityAllowList:n=["error"],sendExceptionsToPostHog:r=!0}={}){return o=>{var a,l,c,u,d;if("*"!==n&&!n.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 f;return t&&i&&(g.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+o.event_id),r&&(null===(f=e.exceptions)||void 0===f||f.sendExceptionEvent(g)),o}}var Ca=class{constructor(e,t,i,s,n,r){this.name=Sa,this.setupOnce=function(o){o(wa(e,{organization:t,projectId:i,prefix:s,severityAllowList:n,sendExceptionsToPostHog:null==r||r}))}}},Ea=class{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(Mr.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 n=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==s?void 0:s.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}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 n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:e,lastScrollY:t,maxScrollY:i,maxContentHeight:r,lastContentY:o,maxContentY:a}=n;if(!(mt(e)||mt(t)||mt(i)||mt(r)||mt(o)||mt(a))){e=Math.ceil(e),t=Math.ceil(t),i=Math.ceil(i),r=Math.ceil(r),o=Math.ceil(o),a=Math.ceil(a);const n=e>1?zt(t/e,0,1,Mr):1,l=e>1?zt(i/e,0,1,Mr):1,c=r>1?zt(o/r,0,1,Mr):1,u=r>1?zt(a/r,0,1,Mr):1;s=Nr(s,{$prev_pageview_last_scroll:t,$prev_pageview_last_scroll_percentage:n,$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 ka=["flags","surveys"],xa={[U]:{exposure:"hidden"},[j]:{exposure:"hidden"},[W]:{exposure:"hidden"},[Q]:{exposure:"hidden"},[G]:{exposure:"hidden"},[Y]:{exposure:"hidden"},[A]:{exposure:"event"},[J]:{exposure:"hidden"},[ne]:{exposure:"hidden"},[Z]:{exposure:"event"},[X]:{exposure:"hidden"},[ee]:{exposure:"event"},[te]:{exposure:"event"},[ie]:{exposure:"event"},[se]:{exposure:"hidden"},[re]:{exposure:"event"},[oe]:{exposure:"hidden"},[ae]:{exposure:"hidden"},[_e]:{exposure:"hidden"},[pe]:{exposure:"event"},[le]:{exposure:"event",shouldSkipFromEventProperties:e=>St(e)},[ge]:{exposure:"event"},[fe]:{exposure:"event"},[ve]:{exposure:"event"},[me]:{exposure:"event"},[ye]:{exposure:"hidden"},[C]:{exposure:"hidden",storageGroup:"flags"},[v]:{exposure:"hidden",storageGroup:"flags"},[f]:{exposure:"hidden"},[m]:{exposure:"hidden",storageGroup:"flags"},[T]:{exposure:"hidden",storageGroup:"flags"},[S]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[w]:{exposure:"hidden",storageGroup:"flags"},[I]:{exposure:"hidden"},[F]:{exposure:"hidden"},[k]:{exposure:"hidden"},[E]:{exposure:"hidden"},[M]:{exposure:"hidden",storageGroup:"surveys"},[O]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[D]:{exposure:"event"},[N]:{exposure:"hidden"},[B]:{exposure:"hidden"},[Se]:{exposure:"hidden"},[we]:{exposure:"hidden"},[Ce]:{exposure:"hidden"},[Ee]:{exposure:"event"},[ke]:{exposure:"event"},[xe]:{exposure:"event"},[Pe]:{exposure:"event"},[x]:{exposure:"hidden"},[P]:{exposure:"hidden"},[be]:{exposure:"event"},[y]:{exposure:"hidden"},[b]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Te]:{exposure:"hidden"},[Ie]:{exposure:"hidden"},[Fe]:{exposure:"hidden"},[Re]:{exposure:"hidden"},[Ae]:{exposure:"hidden"},[$e]:{exposure:"hidden"},[Me]:{exposure:"hidden"},[ce]:{exposure:"event"},[ue]:{exposure:"event"},[de]:{exposure:"event"},[he]:{exposure:"event"},[De]:{exposure:"event"},[Ne]:{exposure:"event"},[Be]:{exposure:"hidden"},[Ue]:{exposure:"hidden"},[ze]:{exposure:"hidden"},[He]:{exposure:"hidden"},[qe]:{exposure:"hidden"},[je]:{exposure:"hidden"},[We]:{exposure:"hidden"},[Ve]:{exposure:"hidden"},[Ge]:{exposure:"hidden"},[Ke]:{exposure:"event"}},Pa=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Ta=e=>{const t=xa[e];if(t)return t;for(const[t,i]of Pa)if(0===e.indexOf(t))return i};function Ia(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}const Fa=e=>{const t=typeof document>"u"?void 0:document,i=null==t?void 0:t.createElement("a");return mt(i)?null:(i.href=e,i)},Ra=()=>{try{return"u">typeof window&&!1!==window.navigator.onLine}catch(e){return!1}},Aa=(e,t)=>e>=t&&Ra(),$a=(e,t,i,s)=>{if(0===e){if(Ra()){const e=t+1;return e===i&&s(),e}return t}return 0},Ma=(e,t)=>{try{let i;return JSON.stringify(e,(e,t)=>{var s;return Ft(t)?(null!==(s=i)&&void 0!==s||(i=new WeakMap),i.has(t)||i.set(t,Hr(t)),i.get(t)):"bigint"==typeof t?t.toString():t},t)}catch(t){return ut(e)}},Oa=function(e,t){const i=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let s;for(let e=0;i.length>e;e++){const n=i[e].split(/=(.*)/);if(n[0]===t){s=n;break}}if(!pt(s)||2>s.length)return"";{let e=s[1].replace(/\+/g," ");try{e=decodeURIComponent(e)}catch(t){Mr.error("Skipping decoding for malformed query param: "+e)}return e}},La=function(e,t,i){if(!e||!t||!t.length)return e;const s=e.split(/#(.*)/),n=s[1],r=(s[0]||"").split(/\?(.*)/),o=r[1],a=r[0],l=(o||"").split("&"),c=[];for(let e=0;l.length>e;e++){const s=l[e].split("?");let n=0;for(;s.length>n&&!t.includes(s[n].split("=")[0]);)n++;c.push(s.length>n?s.slice(0,n).concat(s[n].split("=")[0]+"="+i).join("?"):l[e])}let u=a;return null!=o&&(u+="?"+c.join("&")),null!=n&&(u+="#"+n),u},Da=function(e,t){const i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},Na=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],Ba=(()=>["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Na])(),Ua="<masked>",za=["li_fat_id"];function Ha(e,t,i){if(!o)return{};const s=t?[...Na,...i||[]]:[],n=qa(La(o.URL,s,Ua),e),r=function(){const e={};return Dr(za,function(t){const i=Gr(t);e[t]=i||null}),e}();return Nr(r,n)}function qa(e,t){const i=Ba.concat(t||[]),s={};return Dr(i,function(t){const i=Oa(e,t);s[t]=i||null}),s}function ja(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(!St(t)){s.$search_engine=t;const e=o?Oa(o.referrer,i):"";e.length&&(s.ph_keyword=e)}return s}function Wa(){return navigator.language||navigator.userLanguage}function Va(){const e=Wa();return"string"==typeof e?e.split("-")[0]:void 0}const Ga="$direct";function Ka(){return(null==o?void 0:o.referrer)||Ga}function Ya(e,t,i=!1){const s=e?[...Na,...t||[]]:[],n=i?es(null==a?void 0:a.href):null==a?void 0:a.href,r=null==n?void 0:n.substring(0,1e3);return{r:Ka().substring(0,1e3),u:r?La(r,s,Ua):void 0}}function Qa(e,t=!1){var i;const{r:s,u:n}=e,r=t?es(n):n,o={$referrer:s,$referring_domain:null==s?void 0:s==Ga?Ga:null===(i=Fa(s))||void 0===i?void 0:i.host};if(r){o.$current_url=r;const e=Fa(r);o.$host=null==e?void 0:e.host,o.$pathname=null==e?void 0:e.pathname;const t=qa(r);Nr(o,t)}if(s){const e=ja(s);Nr(o,e)}return o}function Ja(){try{return(new Date).getTimezoneOffset()}catch(e){return}}const Za={flags:b,surveys:O},Xa=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],el=e=>`${e}_cookie_identity_change_pending`,tl=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},il="main",sl=[C,v,m,T,S,b,w,k],nl=e=>-1!==sl.indexOf(e),rl=[G,Y],ol=e=>-1!==rl.indexOf(e),al=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},ll=e=>{if(!e)return{};const t=JSON.parse(e);return ft(t)?t:{}},cl=(e,t)=>{Dr(e,(i,s)=>{const n=Ta(s);n&&"event"!==n.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]})};var ul=class{constructor(e,t,i=!0,n=!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(n),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&Mr.info("Persistence loaded",e.persistence,ls({},this.props)),this.update_config(e,e,t),this.save(),s){const e=()=>this.flush();Wr(s,"beforeunload",e,{capture:!1}),Wr(s,"pagehide",e,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==s?void 0:s.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){const t=ka.find(t=>e.key===this._groupEntryName(t));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,il)},Wr(s,"storage",this._onStorage)}}reconcileFeatureFlagsBeforeMerge(){return!(this._disabled||this._cookieSyncSuppressed||this._storageMigrationInProgress)&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite()}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([e,t])=>{const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!nl(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&&s&&(s.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i=!0){if(this._disabled)return!1;let s,n;try{if(n=ao._get(e),St(n)){const e=this._slotWriteState(t);return e.storageValue=null,t!==il?e.persisted=!1:this._mergeMetaIdentifierProperties({}),!1}s=ll(n)}catch(e){return!1}t===il&&this._mergeMetaIdentifierProperties(s);const r=t===il?s:ao._parse(this._name);if(r&&this._hasCrossTabFeatureFlagIdentityMismatch(r))return!1;const o=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===il&&this._splitStorage&&!al(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,n),o}_hasCrossTabFeatureFlagIdentityMismatch(e){const t=this.props[z],i=e[z];return!mt(t)&&!mt(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){const n=this._slotWriteState(t);n.storageValue=s,t!==il&&(n.persisted=i);try{n.fingerprint=this._entryFingerprint(e,t)}catch(e){n.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){let s=!1;return sl.forEach(i=>{var n;const r=null===(n=Ta(i))||void 0===n?void 0:n.storageGroup;if(t===il&&this._splitStorage&&r||t!==il&&r!==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&&al(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}),s&&i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()),s}_mergeMetaIdentifierProperties(e){const t=this._storesIdentityInCookie&&this._config.cookieWinsOnConflict?[...co,...this._config.cookie_persisted_properties||[]]:[];rl.forEach(i=>{this._metaIdentifierChangePending.has(i)||-1!==t.indexOf(i)||(i in e?al(e[i],this.props[i])||this._setProp(i,e[i],!1):i in this.props&&this._deleteProp(i,!1))})}_metaIdentifierCookieSyncEnabled(){return this._storesIdentityInCookie&&this._splitStorageEligible&&!this._config.cookieWinsOnConflict}_adoptMetaIdentifiersFromCookie(){if(!this._metaIdentifierCookieSyncEnabled())return;let e,t;try{e=ro._get(this._name)||void 0}catch(e){return}if(e&&e!==this._lastSeenMetaIdentifierCookieValue){this._lastSeenMetaIdentifierCookieValue=e;try{t=_o(JSON.parse(e))}catch(e){return}rl.forEach(e=>{!(e in t)||e in this.props||this._metaIdentifierChangePending.has(e)||this._setProp(e,t[e],!1)})}}_rememberMetaIdentifierCookieValue(e){if(this._metaIdentifierCookieSyncEnabled())try{const t=JSON.stringify(po(e,this._config.cookie_persisted_properties||[])),i=ro._get(this._name)||void 0;i===t&&(this._lastSeenMetaIdentifierCookieValue=i)}catch(e){}}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;const e=ao._get(this._name),t=this._slotWriteState(il);let i,s=!1,n=!1;if(e!==t.storageValue)if(St(e))yt(t.storageValue)&&this._mergeMetaIdentifierProperties({}),t.storageValue=null;else{if(i=ll(e),this._mergeMetaIdentifierProperties(i),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(i),this._crossTabFeatureFlagIdentityMismatch)return!1;n=this._mergeCrossTabFeatureFlagProperties(i,il,!1),!this._splitStorage||al(this._partitionProps().main,i)?this._rememberCrossTabStorageFingerprint(i,il,!0,e):t.storageValue=e,s=!0}return this._splitStorage&&ka.forEach(e=>{const t=ao._get(this._groupEntryName(e)),r=this._slotWriteState(e),o=i||{},a=s&&sl.some(t=>{var i;return(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e&&t in o});if(t===r.storageValue&&!a)return;if(St(t))return r.storageValue=null,r.persisted=!1,void(a&&(n=this._mergeCrossTabFeatureFlagProperties(o,e,!1)||n));const l=ll(t);n=this._mergeCrossTabFeatureFlagProperties(l,e,!1)||n,this._rememberCrossTabStorageFingerprint(l,e,!0,t)}),n}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);const i=Ta(e);(null==i?void 0:i.volatile)||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||il).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){sl.forEach(e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{const e=ao._get(this._name),t=ll(e);this._slotWriteState(il).storageValue=e,sl.forEach(e=>{var i;const s=this._splitStorage?null===(i=Ta(e))||void 0===i?void 0:i.storageGroup:void 0,n=s?ao._get(this._groupEntryName(s)):null;if(s){const e=this._slotWriteState(s);e.storageValue=n,e.persisted=!St(n)}const r=s&&!St(n)?ll(n):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,r[e],this.props[e]):e in r&&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(pt(t)?t:[]),n=new Set(pt(this.props[e])?this.props[e]:[]);return i.forEach(e=>n.has(e)?s.add(e):s.delete(e)),Array.from(s)}const s=ft(t)?ls({},t):{},n=ft(this.props[e])?this.props[e]:{};return i.forEach(e=>{e in n?s[e]=n[e]:delete s[e]}),s}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(!nl(e))return;const s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0===s)return;let n=t;if(this._splitStorageEligible)try{var r;const t=this._splitStorage?null===(r=Ta(e))||void 0===r?void 0:r.storageGroup:void 0,i=t?this._groupEntryName(t):this._name;n=ll(ao._get(i))[e]}catch(e){}const o=new Set(s||[]);if("$active_feature_flags"===e){if(!mt(t)&&!pt(t)||!mt(n)&&!pt(n)||!pt(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(t||[]),r=new Set(n||[]),a=new Set(i);new Set([...s,...a]).forEach(e=>{s.has(e)!==a.has(e)&&o.add(e)}),o.forEach(e=>{r.has(e)===a.has(e)&&o.delete(e)})}else{if(!ft(i))return void(al(n,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));{if(!mt(t)&&!ft(t)||mt(t)&&vt(i)&&mt(n))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=ft(t)?t:{},r=ft(n)?n:{};new Set([...Object.keys(s),...Object.keys(i)]).forEach(e=>{e in s==e in i&&al(s[e],i[e])||o.add(e)}),o.forEach(e=>{e in r==e in i&&al(r[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 Ct(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{const t=po(e,this._config.cookie_persisted_properties||[]),i=fo(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),n=ro._get(this._name)||void 0;n&&mo(this._name,n)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=n)}catch(e){}else try{const e=ro._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=e?mo(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=ro._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;const s=mo(this._name,i);let n;try{n=_o(JSON.parse(i))}catch(e){return!1}if((ro._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=i;const r=vo(this._name,i),o=[...co,...r.properties],a={};if(Object.keys(n).forEach(e=>{const t=n[e];(mt(t)||St(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t)&&(a[e]=!0,delete n[e])}),vt(n))return!1;const l="distinct_id"in n||"anonymous"===n.$user_state||"identified"===n.$user_state,c=this.props,u=c[z],d=c[Te],h=Nr({},c);[...co,...e.cookie_persisted_properties||[]].forEach(e=>{if(-1!==o.indexOf(e)&&!(e in n)&&!a[e]&&(l||"distinct_id"!==e&&"$user_state"!==e)){const t=h[e];(r.isValid||-1===co.indexOf(e)||!1!==t&&0!==t)&&delete h[e]}}),this.props=Nr(h,n),sl.forEach(e=>{const t=e in this.props;e in c===t&&al(c[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,c[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))}),!l||"$user_state"in n||"$user_state"in this.props||this._setProp(Te,Ye);const _=this.props[z],p=this.props[Te];return!l||_===u&&p===d||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,wo._set(el(this._name),!0),this._deleteProp(k),this._deleteProp(v),this._deleteProp(C),this._deleteProp(m),this._deleteProp(T),this._deleteProp(S),this._deleteProp(b),this._deleteProp(y),this._deleteProp(x),"anonymous"!==p||"identified"!==d&&"anonymous"!==n.$user_state&&(mt(u)||_===u)||(cl(this.props,n),this._deleteProp(E)),"identified"===p?this.props.$user_id=_:delete this.props.$user_id,this._deleteProp(j)),!0}consumeCookieIdentityChange(){const e=el(this._name),t=this._cookieIdentityChangePending||!!wo._get(e);return this._cookieIdentityChangePending=!1,t&&wo._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&&(mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[il],this._writeNow(!0))}_endCookieSyncSuppression(e=!0){if(this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===Xa.indexOf(e.persistence.toLowerCase())&&(Mr.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((e=[],t=!1,i=()=>!1)=>{const n=[...co,...e];return ls(ls({},ao),{},{_parse(e){try{let r,o={};try{r=ro._get(e)||void 0,o=r?_o(JSON.parse(r)):{}}catch(e){}const a=JSON.parse(ao._get(e)||"{}");let l;if(t){const t=vo(e,r),i=[...co,...t.properties],c={};Object.keys(o).forEach(e=>{const t=o[e];St(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 s;const e=a[z],r=null!==(s=a.$user_state)&&void 0!==s?s:Ye;n.forEach(e=>{if(-1!==i.indexOf(e)&&!(e in o)&&(u||"distinct_id"!==e&&"$user_state"!==e)){const i=a[e];(t.isValid||-1===co.indexOf(e)||!1!==i&&0!==i)&&delete a[e]}}),!u||"$user_state"in o||"$user_state"in a||(a[Te]=Ye),!u||("distinct_id"in c?c[z]:a[z])===e&&("$user_state"in c?c[Te]:a[Te])===r||(lo.forEach(e=>delete a[e]),"identified"===c.$user_state&&"distinct_id"in c?a.$user_id=c[z]:delete a.$user_id,"identified"!==c.$user_state&&(delete a[be],delete a[E]),delete a.__alias)}l=Nr(a,c)}else l=Nr(o,a);return i()||ao._set(e,l),l}catch(e){}return null},_set(i,s,n,r,o,a){const l=ao._set(i,s,void 0,void 0,a);try{const c=po(s,e);if(Object.keys(c).length){if(t){const t=uo(i),u=fo(c,e);if(ro._set(t,u,n,r,o,a),ro._get(t)!==JSON.stringify(u)){ro._remove(t,r);const e=po(s);return ro._set(i,e,n,r,o,a),l}}ro._set(i,c,n,r,o,a)}}catch(e){ao._error(e)}return l},_remove(e,t){try{null==s||s.localStorage.removeItem(e),ro._remove(e,t),ro._remove(uo(e),t)}catch(e){ao._error(e)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this._disabled);let i,n=!1,r=!1;const o=e.persistence.toLowerCase();return"localstorage"===o&&ao._is_supported()?(i=ao,r=!0):"localstorage+cookie"===o&&t._is_supported()?(i=t,r=!0,n=!0):"sessionstorage"===o&&wo._is_supported()?i=wo:"memory"===o?i=bo:"cookie"===o&&ro._is_supported()?(i=ro,n=!0):t._is_supported()?(i=t,r=!0,n=!0):ro._is_supported()?(i=ro,n=!0):i=bo,this._splitStorageEligible=r,this._storesIdentityInCookie=n,i}_groupEntryName(e){return`${this._name}__${e}`}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){const e={};return Dr(this.props,(t,i)=>{const s=Ta(i);if(!s||"event"===s.exposure){var n;if(null==s||null===(n=s.shouldSkipFromEventProperties)||void 0===n?void 0:n.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?ao._parse(this._name):null;let s={};if(t)try{s=_o(ro._parse(this._name)),Dr(s,(e,t)=>{(mt(e)||St(e)||""===e)&&delete s[t]})}catch(e){}const n=this._storage._parse(this._name);if(n&&(this.props=Nr({},n)),this._splitStorage&&this._loadGroupEntries(),t&&n){var r,o;const e=null==i?void 0:i[z],t=null!==(r=null==i?void 0:i.$user_state)&&void 0!==r?r:Ye,a=n[z],l=null!==(o=n.$user_state)&&void 0!==o?o:Ye;if(a!==e||l!==t){this._cookieIdentityChangePending=!0,this._disabled||wo._set(el(this._name),!0);const i=Nr({},this.props);lo.forEach(e=>delete i[e]),"anonymous"!==l||"identified"!==t&&"anonymous"!==s.$user_state&&(mt(e)||a===e)||(cl(i,s),delete i[E]),this.props=i;const n=new Set;lo.forEach(e=>{var t;const i=null===(t=Ta(e))||void 0===t?void 0:t.storageGroup;i&&n.add(i)}),n.forEach(e=>{if(this._disabled)return;const t={};Dr(this.props,(i,s)=>{var n;(null===(n=Ta(s))||void 0===n?void 0:n.storageGroup)===e&&(t[s]=i)}),vt(t)?(ao._remove(this._groupEntryName(e)),this._slotState[e]={}):ao._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})})}}wo._get(el(this._name))&&(this._cookieIdentityChangePending=!0)}_loadGroupEntries(){for(const e of ka){const t=ao._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)||Nr(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some(t=>{var i;return(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e})}_groupEntryIsStale(e,t){const i=Za[e];if(!i)return!1;const s=t[i],n=this.props[i];return Ct(s)&&Ct(n)&&n>s}refreshKey(e){this._refreshKeys([e])}_refreshKeys(e){if(this._disabled)return;let t,i=!1;const s=()=>(i||(t=this._storage._parse(this._name),i=!0),t);e.forEach(e=>{var t;if(this._metaIdentifierChangePending.has(e))return;const i=this._splitStorage?null===(t=Ta(e))||void 0===t?void 0:t.storageGroup:void 0,n=i?ao._parse(this._groupEntryName(i)):s();if(n&&e in n)this._setProp(e,n[e],!1);else{if(i){const t=s();if(t&&e in t)return void this._setProp(e,t[e],!1)}this._deleteProp(e,!1)}})}refreshMetaIdentifiers(){this._disabled||(this._usesMetaIdentifierSnapshotRefresh()?this._refreshMetaIdentifiersIfStorageChanged():this._refreshKeys(rl))}_refreshMetaIdentifiersIfStorageChanged(){const e=this._storageSnapshot();(mt(e)||e!==this._metaIdentifierStorageSnapshot)&&(this._refreshKeys(rl),this._rememberMetaIdentifierStorageSnapshot(e))}_rememberMetaIdentifierStorageSnapshot(e=this._storageSnapshot()){this._metaIdentifierStorageSnapshot=0===this._metaIdentifierChangePending.size?e:void 0}refreshMetaIdentifiersBeforeCapture(){this._disabled||this._cookieSyncSuppressed||(this._usesMetaIdentifierSnapshotRefresh()||this._adoptMetaIdentifiersFromCookie(),this._refreshMetaIdentifiersIfStorageChanged())}_usesMetaIdentifierSnapshotRefresh(){return this._storage===ro||this._storage===wo||this._storage===bo}_storageSnapshot(){const e=this._storage._get(this._name);return yt(e)?e:void 0}save(){if(this._disabled)return;const e=this._saveDebounceMs();e>0?mt(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout(()=>{this._pendingSaveTimer=void 0,this._writeNow()},e)):this._writeNow()}flush(){mt(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._usesMetaIdentifierSnapshotRefresh()&&this.refreshMetaIdentifiers());const t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);const i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)return void(this._config.debug&&Mr.warn("skipping persistence write because storage belongs to a different distinct ID"));if(e||this._adoptMetaIdentifiersFromCookie(),this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()));const s=this._writeEntry(this._storage,this._name,this.props,il);"written"===s&&(this._rememberCurrentCookieProperties(this.props),this._rememberMetaIdentifierCookieValue(this.props)),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear()),"written"===s&&this._rememberMetaIdentifierStorageSnapshot(),i&&this._crossTabFeatureFlagHandlers.forEach(e=>e())}_writeNowSplit(){const{main:e,groups:t}=this._partitionProps(),i=this._writeEntry(this._storage,this._name,e,il);"written"===i&&(this._rememberCurrentCookieProperties(e),this._rememberMetaIdentifierCookieValue(e)),"failed"!==i&&(this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear(),sl.forEach(e=>{var t;(null===(t=Ta(e))||void 0===t?void 0:t.storageGroup)||this._pendingCrossTabFeatureFlagChanges.delete(e)})),"written"===i&&this._rememberMetaIdentifierStorageSnapshot();for(const e of ka){var s;const i=t[e];if(vt(i)&&!(null===(s=this._slotState[e])||void 0===s?void 0:s.persisted)){sl.forEach(t=>{var i;(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e&&this._pendingCrossTabFeatureFlagChanges.delete(t)});continue}const n=this._writeEntry(ao,this._groupEntryName(e),i,e);"failed"!==n&&sl.forEach(t=>{const i=Ta(t);(null==i?void 0:i.storageGroup)!==e||"written"!==n&&i.volatile||this._pendingCrossTabFeatureFlagChanges.delete(t)})}}_partitionProps(){const e={},t={flags:{},surveys:{}};return Dr(this.props,(i,s)=>{var n;const r=null===(n=Ta(s))||void 0===n?void 0:n.storageGroup;r?t[r][s]=i:e[s]=i}),{main:e,groups:t}}_entryFingerprint(e,t){if(t===il)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;const i={};return Dr(e,(e,t)=>{var s;i[t]=(null===(s=Ta(t))||void 0===s?void 0:s.volatile)?"__volatile__":e}),JSON.stringify(i)}_writeEntry(e,t,i,s){const n=this._slotWriteState(s);if(s!==il&&!n.dirty&&!mt(n.fingerprint))return"skipped";let r;try{if(r=this._entryFingerprint(i,s),r===n.fingerprint)return n.dirty=!1,"skipped"}catch(e){r=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(n.dirty=!1,s!==il&&(n.persisted=!0),mt(r)||(n.fingerprint=r),this._splitStorageEligible&&(n.storageValue=ao._get(t)),"written"):(this._config.debug&&Mr.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this._markAllCrossTabFeatureFlagChangesPending(),mt(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 ka)ao._remove(this._groupEntryName(e));e?delete this._slotState[il]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(ft(e)){this.syncCookieProperties(),mt(t)&&(t="None"),this._expire_days=mt(i)?this._default_expiry:i;let s=!1;if(Dr(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(ft(e)){this.syncCookieProperties(),this._expire_days=mt(t)?this._default_expiry:t;let i=!1;if(Dr(e,(t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||ft(t)||pt(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==o?void 0:o.URL;if(e===this._campaign_params_url)return;const t=Ha(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!vt(zr(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}update_search_keyword(){this.register(function(){const e=null==o?void 0:o.referrer;return e?ja(e):{}}())}update_referrer_info(){var e;this.register_once({$referrer:Ka(),$referring_domain:(null==o?void 0:o.referrer)&&(null===(e=Fa(o.referrer))||void 0===e?void 0:e.host)||Ga},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=Ya(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[$e]:this._storesIdentityInCookie?{r:tl(e.r),u:e.u?tl(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Dr([Ae,Re],t=>{const i=this.props[t];i&&Dr(i,function(t,i){e["$initial_"+ct(i)]=t})});const t=this.props[$e];if(t){const i=function(e,t=!1){const i=Qa(e,t),s={};return Dr(i,function(e,t){s[`$initial_${ct(t)}`]=e}),s}(t,this._config.disable_capture_url_hashes);Nr(e,i)}return e}safe_merge(e){return Dr(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,i){const s=e.persistence!==t.persistence,n=!((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||[]),r=s||n,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!i,l=!!this._disabled&&!a;a||this._syncCookieProperties(t,l),this._config=e,!a&&(s||n||o)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0,this._syncCookieProperties(ls(ls({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),l));const c=r||o?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();const u=this._resolveSplitStorage(e),d=r||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[il],this._writeNow()))}finally{this._storageMigrationInProgress=!1,h&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){const e=this.props[$e];if(!this._storesIdentityInCookie||!ft(e)||"string"!=typeof e.r)return;const t=tl(e.r),i="string"==typeof e.u?tl(e.u):e.u;t===e.r&&i===e.u||this._setProp($e,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(Q,i),this.save()}remove_event_timer(e){const t=this.props.__timers||{},i=t[e];return mt(i)||(delete t[e],this._setProp(Q,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 n=this.props[e];this.props[e]=t,i&&("distinct_id"!==e&&"$user_state"!==e||n===t||(this._localIdentityChangePending=!0),ol(e)&&!al(n,t)&&this._metaIdentifierChangePending.add(e),this._markPendingCrossTabFeatureFlagChanges(e,n,t),(null===(s=Ta(e))||void 0===s?void 0:s.volatile)||this._markGroupDirty(e))}_deleteProp(e,t=!0){delete this.props[e],t&&(nl(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),ol(e)&&this._metaIdentifierChangePending.add(e),this._markGroupDirty(e))}_markGroupDirty(e){var t;const i=null===(t=Ta(e))||void 0===t?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}};const dl={GZipJS:"gzip-js",Base64:"base64"},hl={Activation:"events",Cancellation:"cancelEvents"},_l={Button:"button",Tab:"tab",Selector:"selector"},pl={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"},gl={Top:"top",Left:"left",Right:"right",Bottom:"bottom"},fl={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},vl={Open:"open",MultipleChoice:"multiple_choice",SingleChoice:"single_choice",Rating:"rating",Link:"link"},ml={NextQuestion:"next_question",End:"end",ResponseBased:"response_based",SpecificQuestion:"specific_question"},yl={Once:"once",Recurring:"recurring",Always:"always"},bl={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Sl={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"},wl={Popover:"popover",Inline:"inline"};function Cl(e){let t=!0;return{dispose(){if(t){t=!1;const i=e();i&&gt(i.then)&&i.then(void 0,()=>{})}}}}const El={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},kl={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"},xl={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=Or("[RateLimiter]");var Tl=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)}get isClientRateLimited(){return 1>this._refilledBucket().tokens}clientRateLimitContext(e=!1){var t;const i=this._refilledBucket(),s=1>i.tokens;if(s||e||(i.tokens=Math.max(0,i.tokens-1)),s&&!e){const e=(Ct(i.dropped)?i.dropped:0)+1;i.dropped=e,!this.lastEventRateLimited&&this._captureWarning(e)&&(i.dropped=0)}return this.lastEventRateLimited=s,null===(t=this.instance.persistence)||void 0===t||t.set_property("$capture_rate_limit",i),{isRateLimited:s,remainingTokens:i.tokens}}_refilledBucket(){var e;const{captureEventsBurstLimit:t,captureEventsPerSecond:i}=this,s=(new Date).getTime(),n=null===(e=this.instance.persistence)||void 0===e?void 0:e.get_property(Fe),r=n?ls({},n):{tokens:t,last:s};return r.tokens+=Math.max(0,s-r.last)/1e3*i,r.last=Math.max(r.last,s),r.tokens>t&&(r.tokens=t),r}_isPropertyAllowed(e){const t=this.instance.config.property_denylist;return!pt(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&(null==a?void 0:a.pathname))return`${null!==(e=a.origin)&&void 0!==e?e:""}${a.pathname}`}_captureWarning(e){var t,i;const{captureEventsBurstLimit:s,captureEventsPerSecond:n}=this,r=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`,r?`triggered on ${r}`: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 ${n} 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 Il=Or("[RemoteConfig]");var Fl=class{constructor(e){this._instance=e}get remoteConfig(){var e;return null===(e=p._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.config}_loadRemoteConfigJs(e){const t=g(this._instance);t?t(this._instance,"remote-config",()=>e(this.remoteConfig)):e()}_loadRemoteConfigJSON(e){const t=this._instance.__pending_remote_config_callbacks;if(t)return void t.push(e);const i=[e];this._instance.__pending_remote_config_callbacks=i;try{this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),batchKey:"remote_config",fireCallbackOnDrop:!0,callback:e=>{this._instance.__pending_remote_config_callbacks=void 0,i.forEach(t=>t(e))}})}catch(e){throw this._instance.__pending_remote_config_callbacks=void 0,e}}load(){try{if(this.remoteConfig)return Il.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void Il.warn("Remote config is disabled. Falling back to local config.");if(!this._instance.config.opt_in_site_apps)return void this._loadRemoteConfigJSON(e=>{this._onRemoteConfig(e.json,e)});this._loadRemoteConfigJs(e=>{if(!e)return Il.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){Il.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||Il.warn("Failed to fetch remote config from PostHog."):Il.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){Il.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){Il.error("Error loading feature flags",e)}}};const Rl=["fatal","error","warning","log","info","debug"];var Al=Uint8Array,$l=Uint16Array,Ml=Uint32Array,Ol=new Al([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]),Ll=new Al([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]),Dl=new Al([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Nl=function(e,t){for(var i=new $l(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var n=new Ml(i[30]);for(s=1;30>s;++s)for(var r=i[s];i[s+1]>r;++r)n[r]=r-i[s]<<5|s;return[i,n]},Bl=Nl(Ol,2),Ul=Bl[1];Bl[0][28]=258,Ul[258]=28;for(var zl=Nl(Ll,0)[1],Hl=new $l(32768),ql=0;32768>ql;++ql){var jl=(43690&ql)>>>1|(21845&ql)<<1;Hl[ql]=((65280&(jl=(61680&(jl=(52428&jl)>>>2|(13107&jl)<<2))>>>4|(3855&jl)<<4))>>>8|(255&jl)<<8)>>>1}var Wl=function(e,t,i){for(var s=e.length,n=0,r=new $l(t);s>n;++n)++r[e[n]-1];var o,a=new $l(t);for(n=0;t>n;++n)a[n]=a[n-1]+r[n-1]<<1;if(i){o=new $l(1<<t);var l=15-t;for(n=0;s>n;++n)if(e[n])for(var c=n<<4|e[n],u=t-e[n],d=a[e[n]-1]++<<u,h=d|(1<<u)-1;h>=d;++d)o[Hl[d]>>>l]=c}else for(o=new $l(s),n=0;s>n;++n)o[n]=Hl[a[e[n]-1]++]>>>15-e[n];return o},Vl=new Al(288);for(ql=0;144>ql;++ql)Vl[ql]=8;for(ql=144;256>ql;++ql)Vl[ql]=9;for(ql=256;280>ql;++ql)Vl[ql]=7;for(ql=280;288>ql;++ql)Vl[ql]=8;var Gl=new Al(32);for(ql=0;32>ql;++ql)Gl[ql]=5;var Kl=Wl(Vl,9,0),Yl=Wl(Gl,5,0),Ql=function(e){return(e/8|0)+(7&e&&1)},Jl=function(e,t,i){(null==t||0>t)&&(t=0),(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof $l?$l:e instanceof Ml?Ml:Al)(i-t);return s.set(e.subarray(t,i)),s},Zl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},Xl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},ec=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var n=i.length,r=i.slice();if(!n)return[new Al(0),0];if(1==n){var o=new Al(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!=n-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=r[0].s;for(s=1;n>s;++s)r[s].s>h&&(h=r[s].s);var _=new $l(h+1),p=tc(i[u-1],_,0);if(p>t){s=0;var g=0,f=p-t,v=1<<f;for(r.sort(function(e,t){return _[t.s]-_[e.s]||e.f-t.f});n>s;++s){var m=r[s].s;if(t>=_[m])break;g+=v-(1<<p-_[m]),_[m]=t}for(g>>>=f;g>0;){var y=r[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=r[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new Al(_),p]},tc=function(e,t,i){return-1==e.s?Math.max(tc(e.l,t,i+1),tc(e.r,t,i+1)):t[e.s]=i},ic=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new $l(++t),s=0,n=e[0],r=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==n&&a!=t)++r;else{if(!n&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(n),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(n);r=1,n=e[a]}return[i.subarray(0,s),t]},sc=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},nc=function(e,t,i){var s=i.length,n=Ql(t+2);e[n]=255&s,e[n+1]=s>>>8,e[n+2]=255^e[n],e[n+3]=255^e[n+1];for(var r=0;s>r;++r)e[n+r+4]=i[r];return 8*(n+4+s)},rc=function(e,t,i,s,n,r,o,a,l,c,u){Zl(t,u++,i),++n[256];for(var d=ec(n,15),h=d[0],_=d[1],p=ec(r,15),g=p[0],f=p[1],v=ic(h),m=v[0],y=v[1],b=ic(g),S=b[0],w=b[1],C=new $l(19),E=0;m.length>E;++E)C[31&m[E]]++;for(E=0;S.length>E;++E)C[31&S[E]]++;for(var k=ec(C,7),x=k[0],P=k[1],T=19;T>4&&!x[Dl[T-1]];--T);var I,F,R,A,M=c+5<<3,O=sc(n,Vl)+sc(r,Gl)+o,L=sc(n,h)+sc(r,g)+o+14+3*T+sc(C,x)+(2*C[16]+3*C[17]+7*C[18]);if(O>=M&&L>=M)return nc(t,u,e.subarray(l,l+c));if(Zl(t,u,1+(O>L)),u+=2,O>L){I=Wl(h,_,0),F=h,R=Wl(g,f,0),A=g;var D=Wl(x,P,0);for(Zl(t,u,y-257),Zl(t,u+5,w-1),Zl(t,u+10,T-4),u+=14,E=0;T>E;++E)Zl(t,u+3*E,x[Dl[E]]);u+=3*T;for(var N=[m,S],B=0;2>B;++B){var U=N[B];for(E=0;U.length>E;++E)Zl(t,u,D[z=31&U[E]]),u+=x[z],z>15&&(Zl(t,u,U[E]>>>5&127),u+=U[E]>>>12)}}else I=Kl,F=Vl,R=Yl,A=Gl;for(E=0;a>E;++E)if(s[E]>255){var z;Xl(t,u,I[257+(z=s[E]>>>18&31)]),u+=F[z+257],z>7&&(Zl(t,u,s[E]>>>23&31),u+=Ol[z]);var H=31&s[E];Xl(t,u,R[H]),u+=A[H],H>3&&(Xl(t,u,s[E]>>>5&8191),u+=Ll[H])}else Xl(t,u,I[s[E]]),u+=F[s[E]];return Xl(t,u,I[256]),u+F[256]},oc=new Ml([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ac=new Al(0),lc=function(){for(var e=new Ml(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),cc=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function uc(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=lc[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var n,r,o,a,l,c,u=(a=10+((n=t).filename&&n.filename.length+1||0),l=8,function(e,t,i,s,n,r){var o=e.length,a=new Al(s+o+5*(1+Math.floor(o/7e3))+n),l=a.subarray(s,a.length-n),c=0;if(!t||8>o)for(var u=0;o>=u;u+=65535){var d=u+65535;o>d?c=nc(l,c,e.subarray(u,d)):(l[u]=r,c=nc(l,c,e.subarray(u,o)))}else{for(var h=oc[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,f=new $l(32768),v=new $l(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 Ml(25e3),w=new $l(288),C=new $l(32),E=0,k=0,x=(u=0,0),P=0,T=0;o>u;++u){var I=b(u),F=32767&u,R=v[I];if(f[F]=R,v[I]=F,u>=P){var A=o-u;if((E>7e3||x>24576)&&A>423){c=rc(e,l,0,S,w,C,k,x,T,u-T,c),x=E=k=0,T=u;for(var M=0;286>M;++M)w[M]=0;for(M=0;30>M;++M)C[M]=0}var O=2,L=0,D=p,N=F-R&32767;if(A>2&&I==b(u-N))for(var B=Math.min(_,A)-1,U=Math.min(32767,u),z=Math.min(258,A);U>=N&&--D&&F!=R;){if(e[u+O]==e[u+O-N]){for(var H=0;z>H&&e[u+H]==e[u+H-N];++H);if(H>O){if(O=H,L=N,H>B)break;var q=Math.min(N,H-2),j=0;for(M=0;q>M;++M){var W=u-N+M+32768&32767,V=W-f[W]+32768&32767;V>j&&(j=V,R=W)}}}N+=(F=R)-(R=f[F])+32768&32767}if(L){S[x++]=268435456|Ul[O]<<18|zl[L];var G=31&Ul[O],K=31&zl[L];k+=Ol[G]+Ll[K],++w[257+G],++C[K],P=u+O,++E}else S[x++]=e[u],++w[e[u]]}}c=rc(e,l,r,S,w,C,k,x,T,u-T,c),r||(c=nc(l,c,ac))}return Jl(a,0,s+Ql(c)+n)}(r=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.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&&cc(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),cc(u,d-8,i.d()),cc(u,d-4,s),u}const dc=!!c||!!l,hc=new WeakMap,_c="text/plain";let pc=0,gc=!1;const fc=(e,t)=>{const[i,s]=e.split("#"),[n,r]=i.split("?");if(!r)return e;const o=r.split("&").filter(e=>e.split("=")[0]!==t).join("&");return`${n}${o?`?${o}`:""}${s?`#${s}`:""}`},vc=(e,t,i=!0)=>{var s;const[n,r]=e.split("?"),o=ls({},t),a=null!==(s=null==r?void 0:r.split("&").map(e=>{var t;const[s,n]=e.split("="),r=i&&null!==(t=o[s])&&void 0!==t?t:n;return delete o[s],`${s}=${r}`}))&&void 0!==s?s:[],l=function(e,t="&"){let i,s;const n=[];return Dr(e,function(e,t){mt(e)||mt(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),n[n.length]=s+"="+i)}),n.join(t)}(o);return l&&a.push(l),a.length>0?`${n}?${a.join("&")}`:n},mc=e=>{if(e._encodedBody)return e._encodedBody;const{data:t,compression:i}=e;if(!t)return;if(i===dl.GZipJS){const e=uc(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new Al(e.length+(e.length>>>1)),s=0,n=function(e){i[s++]=e},r=0;t>r;++r){if(s+5>i.length){var o=new Al(s+8+(t-r<<1));o.set(i),i=o}var a=e.charCodeAt(r);128>a?n(a):2048>a?(n(192|a>>>6),n(128|63&a)):a>55295&&57344>a?(n(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++r))>>>18),n(128|a>>>12&63),n(128|a>>>6&63),n(128|63&a)):(n(224|a>>>12),n(128|a>>>6&63),n(128|63&a))}return Jl(i,0,s)}(Ma(t)),{mtime:0});return{contentType:_c,body:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),estimatedSize:e.byteLength}}if(i===dl.Base64){const i=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))):e}(Ma(t)),s="sendBeacon"===e.transport,n=s?i:(e=>"data="+encodeURIComponent("string"==typeof e?e:Ma(e)))(i);return{contentType:s?_c:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}const s=Ma(t);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}},yc=e=>{const t=()=>"sendBeacon"===e.transport?{url:vc(e.url,{compression:dl.Base64}),encodedBody:mc(ls(ls({},e),{},{compression:dl.Base64,_encodedBody:void 0}))}:{url:fc(e.url,"compression"),encodedBody:mc(ls(ls({},e),{},{compression:void 0,_encodedBody:void 0}))};let i;try{i=mc(e)}catch(i){if(an(e.compression,Oa(e.url,"compression")))return Mr.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return i&&an(e.compression,Oa(e.url,"compression"))&&!((s=i.body)instanceof ArrayBuffer?on(new Uint8Array(s)):ArrayBuffer.isView(s)&&on(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(gc=!0,t()):{url:e.url,encodedBody:i};var s},bc=e=>{try{return yc(e)}catch(i){var t;return Mr.error(i),void(null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0,error:i}))}},Sc=function(){var e=Dt(function*(e){const t=yield function(e){return pn.apply(this,arguments)}(Ma(e.data),i.DEBUG,{rethrow:!0});if(!t)return e;const s=yield t.arrayBuffer();return ls(ls({},e),{},{_encodedBody:{contentType:_c,body:s,estimatedSize:s.byteLength}})});return function(t){return e.apply(this,arguments)}}(),wc=e=>Xi("AbortError","PostHog request timed out"+(e?` after ${e}ms`:"")),Cc=/Failed to fetch|NetworkError|Load failed/i,Ec=e=>"TypeError"===(null==e?void 0:e.name)&&Cc.test((null==e?void 0:e.message)||""),kc=e=>{try{const t=function(e,t=Date.now(),i=3e5){if("string"!=typeof e||!e)return;const s=e.trim(),n=/^\d+\s*,/.test(s)?s.slice(0,s.indexOf(",")).trim():s;if(/^\d+$/.test(n)){const e=1e3*Math.min(Number(n),i/1e3);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;const r=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(r)-t;return Number.isFinite(o)&&o>0?Math.min(o,i):void 0}(e());return mt(t)?void 0:Math.min(t,3e4)}catch(e){return}},xc=e=>{var t;const i=bc(e);if(!i)return;const s=new c;hc.set(s,!0);const{url:n,encodedBody:r}=i;s.open(e.method||"GET",n,!0);const{contentType:o,body:a}=null!=r?r:{};Dr(e.headers,function(e,t){s.setRequestHeader(t,e)}),o&&s.setRequestHeader("Content-Type",o),e.timeout&&(s.timeout=e.timeout);let l=!1;s.ontimeout=()=>{l=!0},s.onloadend=()=>{var t;if(l){var i;const t=wc(e.timeout);return Mr.warn(t),void(null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))}const n={statusCode:s.status,text:s.responseText};if(200===s.status)try{n.json=JSON.parse(s.responseText)}catch(e){}null===(t=e.callback)||void 0===t||t.call(e,n,kc(()=>s.getResponseHeader("Retry-After")))},null===(t=e.onSend)||void 0===t||t.call(e,n),s.send(a)},Pc=e=>{const t=bc(e);if(!t)return;const{url:i,encodedBody:s}=t,{contentType:n,body:r,estimatedSize:o}=null!=s?s:{},a=new Headers;Dr(e.headers,function(e,t){a.append(t,e)}),n&&a.append("Content-Type",n);let c=null,d=!1;if(u){const t=new u;c={signal:t.signal,timeout:setTimeout(()=>{d=!0;try{t.abort(wc(e.timeout))}catch(e){_(e)}},e.timeout)}}let h=!1;const _=t=>{var i;h||(h=!0,d&&"AbortError"===(null==t?void 0:t.name)||Ec(t)?Mr.warn(t):Mr.error(t),null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))};let p=0;const g=()=>{pc-=p,p=0,c&&clearTimeout(c.timeout)};try{var f;const t=ls({method:(null==e?void 0:e.method)||"GET",headers:a,referrerPolicy:"strict-origin",body:r,signal:null==c?void 0:c.signal},e.fetchOptions);null===(f=e.onSend)||void 0===f||f.call(e,i);const s=null!=o?o:mt(r)?0:void 0;t.keepalive="POST"===t.method&&!e._keepaliveDisabled&&!1!==t.keepalive&&t.body===r&&!mt(s)&&s>=0&&52428.8>pc+s,t.keepalive&&(p=s,pc+=p),l(i,t).then(t=>t.text().then(i=>{var s;if(h)return;const n={statusCode:t.status,text:i};if(200===t.status)try{n.json=JSON.parse(i)}catch(e){Mr.error(e)}h=!0,g(),null===(s=e.callback)||void 0===s||s.call(e,n,kc(()=>t.headers.get("Retry-After")))})).catch(e=>{g(),_(e)}).finally(g)}catch(e){g(),_(e)}},Tc=e=>{try{var t;const{url:i,encodedBody:s}=yc(e),{contentType:n,body:o,estimatedSize:a}=null!=s?s:{};if(!o)return;const c=o instanceof Blob?o:new Blob([o],{type:n});if(r.sendBeacon(i,c))return;const u=pt(e.data)?e.data:null===(t=e.data)||void 0===t?void 0:t.batch;if(pt(u)&&u.length>1&&(null!=a?a:0)>16384){const t=Math.ceil(u.length/2),i=t=>pt(e.data)?t:ls(ls({},e.data),{},{batch:t});return Tc(ls(ls({},e),{},{data:i(u.slice(0,t))})),void Tc(ls(ls({},e),{},{data:i(u.slice(t))}))}Mr.warn(`Beacon of ~${null!=a?a:0} bytes was rejected by the browser, falling back to ${l?"fetch":"XHR"}`),l?Pc(ls(ls({},e),{},{_keepaliveDisabled:!0})):xc(e)}catch(e){Mr.warn("Beacon send failed",e)}},Ic=(e,t,i,s)=>{const n="query"===s?"POST"===t?"sent_at":"_":void 0;return vc(i===dl.GZipJS?fc(e,"compression"):e,ls(ls({},n?{[n]:Date.now().toString()}:{}),i===dl.GZipJS?{}:{compression:i}))},Fc=(()=>{const e=[];return l&&e.push({transport:"fetch",method:Pc}),c&&e.push({transport:"XHR",method:xc}),(null==r?void 0:r.sendBeacon)&&e.push({transport:"sendBeacon",method:Tc}),e})();let Rc=!dc&&-1===(null==h?void 0:h.indexOf("MSIE"))&&-1===(null==h?void 0:h.indexOf("Mozilla"));function Ac(e,t,i){var s,n,r,o;i&&(t=ls(ls({},t),{},{callback:e=>i(e)})),e.__loaded?Rc?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,(mt(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,null===(n=t.onDispatch)||void 0===n||n.call(t),((e,t)=>{var i,s,n;const r=ls(ls({},e),{},{callback:null!=t?t:t=>{var i;return null===(i=e.callback)||void 0===i?void 0:i.call(e,t)}});r.timeout=r.timeout||6e4;const o=null!==(i=r.transport)&&void 0!==i?i:"fetch";"sendBeacon"===o&&mt(r.compression)&&r.data&&(r.compression=dl.Base64),"POST"===r.method&&r.data&&("capture-body"===r.timestampMode?r.data=(e=>{var t,i;const s=(pt(e)?e:[e]).map(e=>ls(ls({},e),e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{})),n=s[0];return{api_key:null!==(t=null==n||null===(i=n.properties)||void 0===i?void 0:i.token)&&void 0!==t?t:null==n?void 0:n.token,batch:s,sent_at:(new Date).toISOString()}})(r.data):"body"===r.timestampMode&&(r.data=((e,t=(new Date).toISOString())=>pt(e)?e.map(e=>ls(ls({},e),{},{sent_at:t})):ls(ls({},e),{},{sent_at:t}))(r.data))),r.url=Ic(r.url,r.method,r.compression,r.timestampMode);const a=Fc.filter(e=>!r.disableTransport||!e.transport||!r.disableTransport.includes(e.transport)),l=null!==(s=null===(n=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===n?void 0:n.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;Ec(e)?Mr.warn(e):Mr.error(e),null===(t=r.callback)||void 0===t||t.call(r,{statusCode:0,error:e})}};"sendBeacon"!==o&&!r.preferSyncCompression&&r.data&&r.compression===dl.GZipJS&&d&&"undefined"!=typeof Promise&&!gc?Sc(r).then(e=>{c(e)}).catch(t=>{if(ln(t))return gc=!0,void c(ls(ls({},r),{},{compression:void 0,url:Ic(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 ln(e)||t===rn})(t)&&(gc=!0),c(r)}):c(r)})(t,(s,n)=>{var r,o,a;e.rateLimiter.checkForLimiting(s),400>s.statusCode||null===(r=(o=e.config).on_request_error)||void 0===r||r.call(o,s),i?i(s,n):null===(a=t.callback)||void 0===a||a.call(t,s)})):t.fireCallbackOnDrop&&(null===(o=t.callback)||void 0===o||o.call(t,{statusCode:0}))}var $c=class{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=zt((null==t?void 0:t.flush_interval_ms)||3e3,250,5e3,Mr.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){Mr.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){const e={},t={};Dr(this._queue,i=>{var s;const n=i,r=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");mt(e[r])&&(e[r]=ls(ls({},n),{},{data:[],callback:void 0,fireCallbackOnDrop:void 0}),t[r]=[]),null===(s=e[r].data)||void 0===s||s.push(n.data),n.callback&&t[r].push(n.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 Mc=["retriesPerformedSoFar"];var Oc=class{constructor(e){this._instance=e,this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._queue=[],this._areWeOnline=!0,this.resume()}resume(){if(!mt(s)&&"onLine"in s.navigator){if(this._areWeOnline=s.navigator.onLine,this._onlineListener)return;this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},Wr(s,"online",this._onlineListener),Wr(s,"offline",this._offlineListener)}}get length(){return this._queue.length}retriableRequest(e,t){let{retriesPerformedSoFar:i}=e,s=gn(e,Mc);Et(i)&&(s.url=vc(s.url,{retry_count:i})),Ac(this._instance,t?ls(ls({},s),{},{transport:t}):s,(e,t)=>{var n;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&&Mr.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===(n=s.callback)||void 0===n||n.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),n=(Math.random()-.5)*(s-i);return Math.ceil(s+n)}(i),null!=t?t:0),n=Date.now()+s;this._queue.push({retryAt:n,requestOptions:e});let r=`Enqueued failed request for retry in ${s}`;navigator.onLine||(r+=" (Browser is offline)"),Mr.warn(r),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,mt(s)||(this._onlineListener&&(s.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(s.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0));for(const{requestOptions:e}of this._queue)try{this._instance._send_request(ls(ls({},e),{},{callback:pt(e.data)?void 0:e.callback,transport:"sendBeacon"}))}catch(e){Mr.error(e)}this._queue=[]}},Lc=class{constructor(e){this._instance=e,this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});const n=this.scrollElement(),r=this.scrollY(),o=n?Math.max(0,n.scrollHeight-n.clientHeight):0,a=r+((null==n?void 0:n.clientHeight)||0),l=(null==n?void 0:n.scrollHeight)||0;this._context.lastScrollY=Math.ceil(r),this._context.maxScrollY=Math.max(r,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(){Wr(s,"scroll",this._updateScrollData,{capture:!0}),Wr(s,"scrollend",this._updateScrollData,{capture:!0}),Wr(s,"resize",this._updateScrollData)}scrollElement(){if(this._scrollRoot){const t=pt(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(const i of t){var e;const t=null==s||null===(e=s.document)||void 0===e?void 0:e.querySelector(i);if(t)return t}return}var t;return null==s||null===(t=s.document)||void 0===t?void 0:t.documentElement}_scrollPosition(e){var t,i;const n="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){const e=this.scrollElement();return e&&e[n]||0}return s?"y"===e?s.scrollY||s.pageYOffset||(null===(t=s.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.scrollTop)||0:s.scrollX||s.pageXOffset||(null===(i=s.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 Dc=e=>Ya(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 Nc=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({[Ie]:i})},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Dc,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[Ie]}getSetOnceProps(){var e;const t=null===(e=this._getStored())||void 0===e?void 0:e.props;return t?"r"in t?Qa(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 Dr(zr(this.getSetOnceProps()),(t,i)=>{"$current_url"===i&&(i="url"),e[`$session_entry_${ct(i)}`]=t}),e}},Bc=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 Uc=Or("[SessionId]"),zc=864e5;var Hc=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 Bc,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||eo,this._windowIdGenerator=i||eo;const n=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*zt(this._config.session_idle_timeout_seconds||1800,60,36e3,Uc.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+n+"_window_id",this._primary_window_exists_storage_key="ph_"+n+"_primary_window_exists",this._canUseSessionStorage()){const e=wo._parse(this._window_id_storage_key),t=wo._parse(this._primary_window_exists_storage_key);e&&!t?this._windowId=e:wo._remove(this._window_id_storage_key),wo._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 mt(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&&wo._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&wo._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?wo._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){const t=this._lastPersistedActivityTimestamp;return!St(t)&&!St(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){const s=t!==this._sessionActivityTimestamp,n=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,n&&!s||n&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[_e]:[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(_e):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(St(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({[_e]:[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[_e];return pt(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 Uc.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void Uc.error("Invalid sessionID in bootstrap",e)}})(e);return!mt(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&&s&&(s.removeEventListener(Ze,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&wo._remove(this._primary_window_exists_storage_key)},Wr(s,Ze,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(),n=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(St(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var r,o;null===(r=(o=this._persistence).syncCookieProperties)||void 0===r||r.call(o),this._lastCookieSyncTimestamp=s}let[,a,l]=this._getSessionId();const c=!mt(n)&&a!==n,u=this._freshestActivityTimestamp();let d=this._getWindowId();const h=this._pendingBootstrapSession,_=!!h&&(h.sessionStartTimestamp>s+6e4||s-h.sessionStartTimestamp>zc),p=h?_:Et(l)&&Math.abs(s-l)>zc;let g=!1,f=c,v=!a||!!h;const m=a;let y=!v&&!e&&this._sessionHasBeenIdleTooLong(s,u);if(y&&(y=this._isSessionIdleAfterCrossTabRefresh(s),y||Uc.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,l]=this._getSessionId(),y||(v=!a||!!h)),v||y||p){f=!1;const e=h&&!_;a=e?h.sessionId:this._sessionIdGenerator(),d=this._windowIdGenerator(),Uc.info("new session ID assigned",{sessionId:a,windowId:d,bootstrapped:!!e,changeReason:{noSessionId:v,activityTimeout:y,sessionPastMaximumLength:p}}),l=e?h.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,g=!0}else d||(d=this._windowIdGenerator(),g=!0),f=f||a!==m,f&&(Uc.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:v,activityTimeout:y,sessionPastMaximumLength:p,crossTabAdoption:f};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 qc=Object.freeze(["2026-08-30","2026-08-29","2026-06-25","2026-05-30","2026-01-30","2025-11-30","2025-05-24"]),jc=function(e,t){if(!e)return!1;const i=e.userAgent;if(i&&Ut(i,t))return!0;try{const i=null==e?void 0:e.userAgentData;if((null==i?void 0:i.brands)&&i.brands.some(e=>Ut(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver};function Wc(){return(Wc=Dt(function*(){const e=null==r?void 0:r.userAgentData;if(null==e?void 0:e.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return yt(i)&&i.length>0?i:void 0}catch(e){return void Mr.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function Vc(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 Gc(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 Kc=(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}},Yc=e=>e.toLowerCase(),Qc={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=>Kc(t,e))),not_regex:(e,t)=>t.every(t=>e.every(e=>!Kc(t,e))),icontains:(e,t)=>t.map(Yc).some(t=>e.map(Yc).some(e=>t.includes(e))),not_icontains:(e,t)=>t.map(Yc).every(t=>e.map(Yc).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 Jc(e,t){return!e||Object.entries(e).every(([e,i])=>{const s=null==t?void 0:t[e];if(null==s)return!1;const n=Qc[i.operator];return!!n&&n(i.values.map(String),[String(s)])})}function Zc(e,t,i){return Ma({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}const Xc="custom",eu="i.posthog.com",tu=/^\/static\//,iu=["/s/","/e/","/i/"];var su=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(`.${eu}`,".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":Xc),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(!tu.test(e))return;const t=this.instance.config.asset_host;return"string"==typeof t&&t.trim().replace(/\/$/,"")||void 0}_urlKey(e){const t=Fa(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;let s=i;const n=this.instance.config.rewriteRequestPath;if(n){var r;const e=(null===(r=Fa(i))||void 0===r?void 0:r.href)||i;s=n(new URL(e)).toString()}if(n&&"api"===e&&iu.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===n||(i={apiHost:t,rewriteRequestPath:n,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===Xc)return this._prepareEndpoint(e,t,this.apiHost+t);const i=eu+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 nu=Or("[Surveys]"),ru=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){nu.error("Failed to persist survey seen state",e)}},ou=[fl.Popover,fl.Widget,fl.API],au={ignoreConditions:!1,ignoreDelay:!1,displayType:wl.Popover},lu=Or("[PostHog ExternalIntegrations]"),cu={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var uu=class{constructor(e){this._instance=e}_loadScript(e,t){var i;null===(i=g(this._instance))||void 0===i||i(this._instance,e,e=>{if(e)return lu.error("failed to load script",e);t()})}startIfEnabledOrStop(){var e;for(const[n,r]of Object.entries(null!==(e=this._instance.config.integrations)&&void 0!==e?e:{})){var t,i,s;r&&!(null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.integrations)||void 0===t?void 0:t[n])&&this._loadScript(cu[n],()=>{var e;null===(e=p.__PosthogExtensions__)||void 0===e||null===(e=e.integrations)||void 0===e||null===(e=e[n])||void 0===e||e.start(this._instance)}),!r&&(null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.integrations)||void 0===i?void 0:i[n])&&(null===(s=p.__PosthogExtensions__)||void 0===s||null===(s=s.integrations)||void 0===s||null===(s=s[n])||void 0===s||s.stop())}}},du=class{constructor(e){this.disabled=!1===e;const t=ft(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 hu=()=>typeof window>"u"?void 0:window,_u=()=>typeof document>"u"?void 0:document,pu="$copy_autocapture",gu=["password","hidden","file","checkbox","button","submit","reset","image"],fu=Or("[AutoCapture]");function vu(e,t){return t.length>e?t.slice(0,e)+"...":t}function mu(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do{t=t.previousSibling}while(t&&!xo(t));return t}function yu(e,{e:t,maskAllElementAttributes:i,maskAllText:s,elementAttributeIgnoreList:n,elementsChainAsString:r,disableCaptureUrlHashes:o}){var a,l;if(!xo(e))return{props:{}};const c=[e],u=new Set([e]);let d=e;for(;!Po(d,"body")&&1e3>c.length;){const e=d.assignedSlot||d.parentNode,t=Io(e)?e.host:e&&xo(e)?e:null;if(!t||u.has(t))break;u.add(t),c.push(t),d=t}const h="click"===t.type&&"http://www.w3.org/2000/svg"===e.namespaceURI?c.findIndex(e=>Po(e,"button")||Po(e,"a")):-1;h>0&&(s=s||c.slice(0,h+1).some(e=>!ta(e)||ia(e)));const _=[],p={};let g,f=!1,v=!1;if(Dr(c,e=>{const t=ta(e);if(t&&Po(e,"a")&&!i&&!(null==n?void 0:n.includes("href"))){const i=e.getAttribute("href");f=!!(t&&i&&ua(i))&&(o?es(i):i)}at(Ao(e),"ph-no-capture")&&(v=!0),_.push(function(e,t,i,s,n=!1){const r=e.tagName.toLowerCase(),o={tag_name:r};Lo.indexOf(r)>-1&&!i&&(o.$el_text="a"===r.toLowerCase()||"button"===r.toLowerCase()?vu(1024,da(e)):vu(1024,Mo(e)));const a=Ao(e);t||(null==s?void 0:s.includes("class"))||0>=a.length||(o.classes=a.filter(function(e){return""!==e})),Dr(ea(e)?[]:e.attributes,function(i){var r;if((!ia(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&!(null==s?void 0:s.includes(i.name))&&!t&&ua(i.value)&&(!yt(r=i.name)||"_ngcontent"!==r.substring(0,10)&&"_nghost"!==r.substring(0,7))){let e=i.value;"class"===i.name&&(e=Fo(e).join(" ")),o["attr__"+i.name]=vu(1024,"href"===i.name&&n?es(e):e)}});let l=1,c=1,u=e;for(;u=mu(u);)l++,u.tagName===e.tagName&&c++;return o.nth_child=l,o.nth_of_type=c,o}(e,i,s,n,o)),Dr(function(e){if(!ta(e))return{};const t={};return Dr(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&&ua(s)&&(t[i]=s)}}),t}(e),(e,t)=>{({}).hasOwnProperty.call(p,t)||(p[t]=e)})}),v)return{props:{},explicitNoCapture:v};if(h>0&&(e=c[h],_.splice(0,h)),s||(_[0].$el_text=Po(e,"a")||Po(e,"button")?da(e):Mo(e)),f){var m,y;_[0].attr__href=f;const e=null===(m=Fa(f))||void 0===m?void 0:m.host,t=null===(y=hu())||void 0===y||null===(y=y.location)||void 0===y?void 0:y.host;e&&t&&e!==t&&(g=f)}return{props:Nr((S=t.type,{$event_type:S,$ce_version:1}),r?{}:{$elements:_},{$elements_chain:(b=_,pt(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 n=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),r={};return Br(n).sort(([e],[t])=>function(e,t){return t>e?-1:e>t?1:0}(e,t)).forEach(([e,t])=>r[_a(e.toString())]=_a(t.toString())),s+=":",s+=Br(r).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:pa(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Br(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}const bu="autocapture";var Su=class{_clearPointer(){this._pointerDown=void 0,clearTimeout(this._pointerExpiry),this._pointerExpiry=void 0}_isExcludedPointerTarget(e){var t;if(!ta(e))return!0;const i=null!==(t=this._refreshConfig().css_selector_ignorelist)&&void 0!==t?t:Uo,s=new Set;let n=e;for(;n;){if(s.size>=1e3||s.has(n))return!0;s.add(n);const e=n,t=Ao(e);if(at(t,"ph-no-capture")||at(t,"ph-sensitive")||ia(e)||i.some(t=>Do(e,t)))return!0;const r=n.assignedSlot||n.parentNode;n=Io(r)?r.host:r&&xo(r)?r:null}return!1}_trackPointer(e){if(!this.isEnabled||"pointercancel"===e.type)return void this._clearPointer();if("pointerdown"===e.type){var t;this._clearPointer();const i=Oo(e);return void(e.isPrimary&&0===e.button&&!e.ctrlKey&&i&&xo(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=Oo(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&&(Po(s,"html")||Po(s,"body"))){var n,r,o;if(i.excluded)return null;const e=null!==(n=this._refreshConfig().css_selector_ignorelist)&&void 0!==n?n:Uo;return[s,null===(r=_u())||void 0===r?void 0:r.documentElement,null===(o=_u())||void 0===o?void 0:o.body].some(t=>{if(!t)return!1;const i=Ao(t);return at(i,"ph-no-capture")||at(i,"ph-sensitive")||!ta(t)||ia(t)||e.some(e=>Do(t,e))})?null:i.target}}constructor(e){this._configSource=e,this.name=bu,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 du(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(){const e=hu(),t=_u();if(!this.isBrowserSupported())return void fu.info("Disabling Automatic Event Collection because this browser is not supported");if(!e||!t)return;this._listenerWindow=e,this._listenerDocument=t;const i=this._domEventHandler=t=>{t=t||(null==e?void 0:e.event);try{if("blur"===t.type)return void this._clearPointer();if(0===t.type.indexOf("pointer"))return void this._trackPointer(t);const e="click"===t.type?this._recoverClickTarget(t):void 0;if(St(e))return;this._captureEvent(t,"$autocapture",e)}catch(e){fu.error("Failed to capture event",e)}};if(Wr(e,"blur",i),Wr(t,"submit",i,{capture:!0}),Wr(t,"change",i,{capture:!0}),Wr(t,"click",i,{capture:!0}),Dr(["pointerdown","pointermove","pointerup","pointercancel"],e=>{Wr(t,e,i,{capture:!0})}),this._refreshConfig().capture_copied_text){const i=this._copiedTextHandler=t=>{t=t||(null==e?void 0:e.event);try{this._captureEvent(t,pu)}catch(e){fu.error("Failed to capture clipboard event",e)}};Wr(t,"copy",i,{capture:!0}),Wr(t,"cut",i,{capture:!0}),Wr(t,"paste",i,{capture:!0})}}_removeDomEventHandlers(){const e=this._listenerWindow,t=this._listenerDocument;this._clearPointer(),this._domEventHandler&&(null==e||e.removeEventListener("blur",this._domEventHandler),Dr(["pointerdown","pointermove","pointerup","pointercancel"],e=>{null==t||t.removeEventListener(e,this._domEventHandler,!0)}),null==t||t.removeEventListener("submit",this._domEventHandler,!0),null==t||t.removeEventListener("change",this._domEventHandler,!0),null==t||t.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==t||t.removeEventListener("copy",this._copiedTextHandler,!0),null==t||t.removeEventListener("cut",this._copiedTextHandler,!0),null==t||t.removeEventListener("paste",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._listenerWindow=void 0,this._listenerDocument=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;kt(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=>{var n;const r=null===(n=_u())||void 0===n?void 0:n.querySelectorAll(i);null==r||r.forEach(n=>{e!==n&&t!==n||at(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(A),s=this._isDisabledServerSide,n=this._refreshConfig();if(!n.remoteRequestsDisabled&&!this._hasReceivedConfigResponse)return!1;const r=n.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(St(s)&&!kt(i)&&!r)return!1;const o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!n.enabled&&!o}_captureEvent(e,t="$autocapture",i){if(!this.isEnabled)return void this._clearPointer();let s=i||Oo(e);To(s)&&(s=s.parentNode||null);const n=this._compileUrlPatterns();var r;"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&n.rageclick&&(null===(r=this.rageclicks)||void 0===r?void 0:r.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime()))&&Jo(s,n.rageclick)&&this._captureEvent(e,"$rageclick",i);const o=t===pu,a=o?ls(ls({},n),{},{dom_event_allowlist:void 0}):n;if(s&&function(e,t,i,s,n,r){var o;const a=typeof window>"u"?void 0:window;if(!a||Zo(e))return!1;if((null==i?void 0:i.url_allowlist)&&!Ro(i.url_allowlist,r))return!1;if((null==i?void 0:i.url_ignorelist)&&Ro(i.url_ignorelist,r))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:l,targetElementList:c,isComplete:u}=Xo(e,s);if(!u)return!1;if(!function(e,t){const i=null==t?void 0:t.element_allowlist;if(mt(i))return!0;for(const t of e)if(i.some(e=>t.tagName.toLowerCase()===e))return!0;return!1}(c,i))return!1;if(!No(c,null==i?void 0:i.css_selector_allowlist))return!1;if(No(c,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Uo))return!1;try{const i=a.getComputedStyle(e);if(i&&"pointer"===i.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}const d=e.tagName.toLowerCase();switch(d){case"html":return!1;case"form":return(n||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(n||["change","click"]).indexOf(t.type)>=0;default:return l?(n||["click"]).indexOf(t.type)>=0:(n||["click"]).indexOf(t.type)>=0&&(Lo.indexOf(d)>-1||"true"===e.getAttribute("contenteditable"))}}(s,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:n.getCurrentUrl}})){var l;const{props:i,explicitNoCapture:r,target:o}=yu(s,{e:e,maskAllElementAttributes:n.maskAllElementAttributes,maskAllText:n.maskAllText,elementAttributeIgnoreList:n.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:n.disableCaptureUrlHashes});if(r)return!1;const a=this.getElementSelectors(s,o);if(a&&a.length>0&&(i.$element_selectors=a),t===pu){const t=e.type||"clipboard";if("paste"!==t){var c,u;const e=null===(c=hu())||void 0===c||null===(c=c.getSelection())||void 0===c?void 0:c.toString(),t=$o(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}if("$autocapture"===t&&"change"===e.type&&n.capture_value_css_selector_allowlist&&!n.maskAllText&&(Po(d=s,"input")?!at(gu,d.type):Po(d,"textarea")||Po(d,"select")&&!d.multiple)&&function(e,t){var i;if(!ta(e))return!1;const s=null!==(i=t.css_selector_ignorelist)&&void 0!==i?i:Uo,n=new Set;let r=e;for(Po(e,"select")&&(r=e.options[e.selectedIndex]||e);r;){const e=r,t=Ao(e);if(n.size>=1e3||n.has(r)||at(t,"ph-sensitive")||at(t,"ph-no-capture")||s.some(t=>Do(e,t)))return!1;n.add(r);const i=r.assignedSlot||r.parentNode;r=Io(i)?i.host:i&&xo(i)?i:null}return!0}(s,n)&&!s.querySelector(".ph-no-capture, .ph-sensitive")){const e=n.capture_value_css_selector_allowlist;let t=!1;try{t=gt(e)?!!e(s):pt(e)&&e.some(e=>Do(s,e))}catch(e){fu.error("capture_value_css_selector_allowlist threw",e)}t&&(i.$input_value=s.value)}return null===(l=this._client)||void 0===l||l.capture(t,i),!0}var d}isBrowserSupported(){var e;return gt(null===(e=_u())||void 0===e?void 0:e.querySelectorAll)}};const wu="featureFlags",Cu="logs",Eu=()=>{var e;return(null==s||null===(e=s.performance)||void 0===e?void 0:e.now)?s.performance.now():Date.now()},ku=[],xu=[50,75,100,150,200,300,400,500,750,1e3,1500,2e3,3e3,5e3,1e4],Pu=[5,10,25,...xu];var Tu=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);mt(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)}},Iu=class{constructor(e){this.instance=e,this._logger=Mr,this.kv=new Tu(e),this.onSession=e=>Cl(this.instance.onSessionId(t=>{try{e(t)}catch(e){this._logger.error("Browser extension session listener failed",e)}})),this.onEvent=e=>Cl(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),Cl(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(H);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,n;const r=null===(e=this.instance.sessionManager)||void 0===e?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==r?void 0:r.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==r?void 0:r.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==r?void 0:r.sessionStartTimestamp)&&void 0!==s?s:0,lastActivityTimestamp:null!==(n=null==r?void 0:r.lastActivityTimestamp)&&void 0!==n?n:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return gt(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get isRateLimited(){var e;return!!(null===(e=this.instance.rateLimiter)||void 0===e?void 0:e.isClientRateLimited)}get projectToken(){return this.instance.config.token}getExtension(e){let t;switch(e){case wu:case"featureFlagsCommon":t=this.instance.featureFlags;break;case Cu:t=this.instance.logs;break;case"surveys":t=this.instance.surveys;break;case bu:t=this.instance.autocapture}return t}capture(e,t,i){if(!i)return this._notRateLimited(this.instance.capture(e,t));const s=ls({timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce},"unload"===i.delivery?{transport:"sendBeacon",send_instantly:!0}:{});return this._notRateLimited(this.instance.capture(e,t,s))}_notRateLimited(e){var t;return!mt(e)||!(null===(t=this.instance.rateLimiter)||void 0===t?void 0:t.lastEventRateLimited)}registerDynamicEventProperties(e){return Cl(this.instance._registerExtensionEventProperties(e))}sendRequest(e){var t=this;return Dt(function*(e,i={}){var n;const r=null!==(n=i.target)&&void 0!==n?n:"api",o=i.query?vc(e,i.query):e,a=t.instance.requestRouter.endpointFor(r,o),l={method:i.method,url:a,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?nt.Base64:void 0,timestampMode:i.sentAt};return"api"===r&&"/i/v1/logs"===e&&(l.batchKey="logs"),"sendBeacon"===i.transport?(t.instance._send_request(l),{statusCode:202}):new Promise(e=>{var i;if(l.callback=e,"flags"===r&&(null===(i=t.instance.config.metrics)||void 0===i?void 0:i.flags)){let i,n;l.onDispatch=()=>{i=Eu()},l.onSend=e=>{n=(e=>{try{return(e=>{var t;const i=null==s?void 0:s.PerformanceObserver,n=null===(t=Fa(e))||void 0===t?void 0:t.href;if(!i||!n)return;const r=Eu(),o={name:n,before:1/0,inFlight:!0};let a,l,c,u=1/0,d=!1;const h=()=>{d||(d=!0,clearTimeout(c),g.disconnect(),ku.splice(ku.indexOf(o),1))};let _=!1;const p=e=>{for(const t of e){const e=t.startTime;t.name!==n||(_?r>=e:r>e)||e>=o.before||a&&e>=a.startTime||(a=t)}if(a&&l&&u>=a.startTime){const e=l;h(),e(a)}},g=new i(e=>p(e.getEntriesByName(n,"resource")));g.observe({entryTypes:["resource"]});for(const e of ku)e.name===n&&(e.before=Math.min(e.before,r),_=_||e.inFlight);return ku.push(o),{take(e,t){d||(u=e,o.inFlight=!1,l=t,c=setTimeout(h,5e3),gt(g.takeRecords)&&p(g.takeRecords()))},stop:h}})(e)}catch(e){return}})(e)},l.callback=s=>{if(e(s),mt(i))return;const r=i,o=Eu();try{const e=((e,t)=>{var i,s;const n=t.statusCode||void 0,r={"server.address":(null!==(i=null===(s=Fa(e))||void 0===s?void 0:s.hostname)&&void 0!==i?i:e).replace(/^\[(.*)\]$/,"$1")};n&&(r["http.response.status_code"]=n);const o=((e,t)=>e?400>e?void 0:String(e):"AbortError"===(null==t?void 0:t.name)?"timeout":"_OTHER")(n,t.error);o&&(r["error.type"]=o);const a=Ia();return a&&(r["client.timezone"]=a),r})(a,s);if(t._recordFlagsHistogram("posthog.flags.request.duration",o-r,xu,e),s.statusCode&&n)return void n.take(o,i=>t._recordFlagsSplit(i,r,o,e))}catch(e){Mr.error("Failed to record the /flags request timing",e)}null==n||n.stop()}}t.instance._send_request(l)})}).apply(this,arguments)}_recordFlagsSplit(e,t,i,s){if(e.responseEnd>=e.startTime)try{const n=Math.min(e.responseEnd,i);this._recordFlagsHistogram("posthog.flags.request.pre_send_duration",e.startTime-t,Pu,s),this._recordFlagsHistogram("posthog.flags.request.network_duration",n-e.startTime,xu,s),this._recordFlagsHistogram("posthog.flags.request.main_thread_duration",i-n,Pu,s)}catch(e){Mr.error("Failed to record the /flags request timing split",e)}}_recordFlagsHistogram(e,t,i,s){var n;null===(n=this.instance.metrics)||void 0===n||n.histogram(e,t,{unit:"ms",attributes:ls({},s),bounds:i})}};const Fu={};let Ru=0;const Au=()=>{},$u='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Mu="Surveys module not available",Ou="sanitize_properties is deprecated. Use before_send instead",Lu="Invalid value for property_denylist config: ",Du=["$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"],Nu=["$feature_flag_called","$$heatmap","$snapshot"],Bu=e=>"$"===e.charAt(0)&&!at(Nu,e),Uu=/^[A-Za-z0-9_-]{1,400}$/,zu=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,Hu=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,qu=["token","distinct_id",Le],ju="posthog",Wu=[...qc].sort()[qc.length-1],Vu=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},Gu=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:jr(null==o?void 0:o.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Au,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:!0,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:a&&yt(null==a?void 0:a.search)&&-1!==a.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==s||null===(t=s.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){Mr.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:Je,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:Au},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:Ho,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:Vu(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))},Ku=[["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"]],Yu=e=>{const t={};for(const[i,s]of Ku)mt(e[i])||(t[s]=e[i]);const i=Nr({},t,e),s=e.__preview_external_dependency_versioned_paths;return mt(s)||(mt(e.strict_script_versioning)&&(i.strict_script_versioning=!!s),yt(s)&&mt(e.asset_host)&&(i.asset_host=s)),pt(e.property_blacklist)&&(mt(e.property_denylist)?i.property_denylist=e.property_blacklist:pt(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:Mr.error(Lu+e.property_denylist)),i};var Qu=class{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){Mr.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Ju=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()}_warnIfHistoryAutocaptureMissing(){if(this._hasWarnedAboutMissingHistoryAutocapture)return;if(!this._originalUserConfig||!("capture_pageview"in this._originalUserConfig))return;if(ls(ls({},e.__defaultExtensionClasses),this.config.__extensionClasses).historyAutocapture)return;const t=this.config.capture_pageview;("history_change"===t||ft(t)&&(t.path||t.search||t.hash&&!this.config.disable_capture_url_hashes))&&(this._hasWarnedAboutMissingHistoryAutocapture=!0,Mr.warn("capture_pageview is set to capture history changes, but the history autocapture extension is not loaded, so only the first pageview of each page load is captured. With the slim bundle, pass __extensionClasses: { historyAutocapture: AnalyticsExtensions.historyAutocapture } from 'posthog-js/dist/extension-bundles', or set capture_pageview: true to capture page loads only."))}_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(eo());this.register({distinct_id:t,$device_id:t}),e.set_property(Te,Ye)}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._botFilterWarned=!1,this._isPageUnloading=!1,this._isShutdown=!1,this.webPerformance=new Qu,this._personProcessingSetOncePropertiesSent=!1,this.version=i.LIB_VERSION,this.__loadExternalDependency=void 0,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new Bc,this._extensions=[],this._extensionEventPropertyProducers=[],this._replayDebugPropertiesPaused=!1,this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._hasWarnedAboutMissingHistoryAutocapture=!1,this._isConsentTransition=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Gu(),this.SentryIntegration=Ca,this.sentryIntegration=e=>function(e,t){const i=wa(e,t);return{name:Sa,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 Lc(this),this.pageViewManager=new Ea(this),this.rateLimiter=new Tl(this),this.requestRouter=new su(this),this.consent=new Co(this),this.externalIntegrations=new uu(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=yt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{const s=yt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",e=>Mr.info(`send "${null==e?void 0:e.event}"`,e))}init(t,i,s){if(s&&s!==ju){var n;const r=null!==(n=Fu[s])&&void 0!==n?n:new e;return r._init(t,i,s),Fu[s]=r,Fu[ju][s]=r,r}return this._init(t,i,s)}_init(e,t={},n){var r,o,a;const l=yt(e)?e.trim():"";if(!l)return Mr.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var c;if(this.__loaded)return l!==(null===(c=this.config)||void 0===c?void 0:c.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('${l}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Gu(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 u=Gu(t.defaults),d=Yu(t),h=Nr({},u,d,{name:n,token:l});ft(u.rageclick)&&ft(d.rageclick)&&(h.rageclick=Nr({},u.rageclick,d.rageclick)),ft(u.session_recording)&&ft(d.session_recording)&&(h.session_recording=Nr({},u.session_recording,d.session_recording)),this.set_config(h),this.config.on_xhr_error&&Mr.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:dl.GZipJS;const _=this._is_persistence_disabled(),p=!this._inCookielessMode();if(this.persistence=new ul(this.config,_,!0,p),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new ul(ls(ls({},this.config),{},{persistence:"sessionStorage"}),_,!1,p),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!_&&wo._is_supported()){const e=wo._parse(this._sessionRegisteredPropertiesStorageKey);pt(e)&&e.forEach(e=>{yt(e)&&this._sessionRegisteredPropKeys.add(e)})}else wo._remove(this._sessionRegisteredPropertiesStorageKey);const g=ls({},this.persistence.props),f=ls({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new $c((e,t)=>this._send_retriable_request(e,t),this.config.request_queue_config),this._retryQueue=new Oc(this),this.__request_queue=[];const v=this._inCookielessMode();v||(this.sessionManager=new Hc(this),this.sessionPropsManager=new Nc(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?(Mr.info("Deferring extension initialization to improve startup performance"),this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._initExtensions(v)},0)):(Mr.info("Initializing extensions synchronously"),this._initExtensions(v)),i.DEBUG=i.DEBUG||this.config.debug,i.DEBUG&&Mr.info("Starting in debug mode",{this:this,config:t,thisC:ls({},this.config),p:g,s:f}),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 m=null===(o=t.bootstrap)||void 0===o?void 0:o.distinctID;if(this._hasStableInitialDistinctId=!!m&&!bt(m),null===(a=t.bootstrap)||void 0===a?void 0:a.distinctID){const e=t.bootstrap.distinctID,i=this.get_distinct_id(),s=this.persistence.get_property(Te);if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"anonymous"===s)this.identify(e);else if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"identified"===s)Mr.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(eo()),s=t.bootstrap.isIdentifiedID?i:e;this.persistence.set_property(Te,t.bootstrap.isIdentifiedID?Qe:Ye),this.register({distinct_id:e,$device_id:s})}}if(v)this.register_once({distinct_id:Oe,$device_id:null},"");else if(!this.get_distinct_id()){const e=this.config.get_device_id(eo());this.register_once({distinct_id:e,$device_id:e},""),this.persistence.set_property(Te,Ye)}return Wr(s,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Wr(s,"pageshow",e=>{if(this._isPageUnloading=!1,!this._isShutdown){var t;if(e.persisted&&this.persistence){const e=this.persistence.get_property(z),t=this.persistence.get_property(Te);this.persistence.load(),this._processCookieIdentityChange()||e===this.persistence.get_property("distinct_id")&&t===this.persistence.get_property("$user_state")||this._processIdentityChange()}null===(t=this._retryQueue)||void 0===t||t.resume()}}),t.segment?ba(this,()=>this._loaded()):this._loaded(),gt(this.config._onCapture)&&this.config._onCapture!==Au&&(Mr.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",e=>this.config._onCapture(e.event,e))),this.config.ip&&Mr.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 Wc.apply(this,arguments)}().then(e=>{e&&this.register({[q]:e})}).catch(Au),this}_isSharedExtension(e){const t=e;return yt(t.name)&&gt(t.setup)}_enrollExtension(e,t){var i=this;this._isSharedExtension(e)?t.push(Dt(function*(){try{yield e.setup(i._getBrowserClientAdapter())}catch(i){Mr.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){Mr.error(`Failed to dispose extension "${e.name}"`,t)}}})):this._extensions.push(e)}_enrollFeatureFlags(){var t,i,s,n=this;const r=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(r)if(this.featureFlags&&this.featureFlags instanceof r||(null===(o=this._featureFlagsReloadingUnsubscribe)||void 0===o||o.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new r(this)),gt(this.featureFlags.onReloading)&&gt(this.featureFlags.setup)){if(!this._featureFlagsReloadingUnsubscribe){this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading(()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)});const e=this.featureFlags;Dt(function*(){try{yield e.setup(n._getBrowserClientAdapter())}catch(t){Mr.error("Failed to set up feature flags",t);const i=n._featureFlagsReloadingUnsubscribe;n._featureFlagsReloadingUnsubscribe=void 0;try{null==i||i()}catch(e){Mr.error("Failed to unsubscribe feature flag reloading",e)}try{yield e.dispose()}catch(e){Mr.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),n=[];var r,o,a,l,c,u,d,h;s.exceptions&&this._extensions.push(this.exceptions=null!==(r=this.exceptions)&&void 0!==r?r:new s.exceptions(this)),s.historyAutocapture&&this._extensions.push(this.historyAutocapture=new s.historyAutocapture(this)),this._warnIfHistoryAutocaptureMissing(),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)),s.autocapture&&this._enrollExtension(this.autocapture=new s.autocapture(this),n),s.surveys&&this._enrollExtension(this.surveys=null!==(o=this.surveys)&&void 0!==o?o:new s.surveys(this),n),s.logs&&this._enrollExtension(this.logs=null!==(a=this.logs)&&void 0!==a?a:new s.logs(this),n),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,va)),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));const _=this._extensions.length>0||n.length>0;this.config.disable_scroll_properties||n.unshift(()=>{this.scrollManager.startMeasuringScrollPosition()}),this._extensions.forEach(e=>{e.initialize&&n.push(()=>{var t;null===(t=e.initialize)||void 0===t||t.call(e)})}),n.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(n,i,_)}_processInitTaskQueue(e,t,i){for(var s,n;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,i)},0));const s=e.shift();if(s)try{s()}catch(e){Mr.error("Error initializing extension:",e)}}const r=Math.round(performance.now()-t);i&&r>0?this.register_for_session({[De]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ne]:r}):mt(null===(s=this.sessionPersistence)||void 0===s?void 0:s.props.$sdk_debug_extensions_init_method)&&mt(null===(n=this.sessionPersistence)||void 0===n?void 0:n.props.$sdk_debug_extensions_init_time_ms)||(this.unregister_for_session(De),this.unregister_for_session(Ne)),this.config.__preview_deferred_init_extensions&&Mr.info(`PostHog extensions initialized (${r}ms)`)}_onRemoteConfig(e){if(!o||!o.body)return Mr.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=at(i.supportedCompression,dl.GZipJS)?dl.GZipJS:at(i.supportedCompression,dl.Base64)?dl.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:Je}),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){Mr.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&(null==a?void 0:a.hostname)){const e=a.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()&&Lr(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,n,r;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(et),null===(s=this.logs)||void 0===s||s.flushLogs("sendBeacon"),null===(n=this._requestQueue)||void 0===n||n.unload(),null===(r=this._retryQueue)||void 0===r||r.unload()):this._shouldCapturePageleave()&&this.capture(et,null,{transport:"sendBeacon"})}_send_request(e){Ac(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){Ru++;try{let t;const i=[],s=[],n=[];Lr(e,e=>{if(e)if(t=e[0],pt(t))n.push(e);else if(gt(e))try{e.call(this)}catch(t){Mr.error("Error executing queued PostHog call",e,t)}else pt(e)&&"alias"===t?i.push(e):pt(e)&&-1!==t.indexOf("capture")&&gt(this[t])?n.push(e):s.push(e)});const r=function(e,t){Lr(e,function(e){try{if(pt(e[0])){let i=t;Dr(e,function(e){i=i[e[0]].apply(i,e.slice(1))})}else t[e[0]].apply(t,e.slice(1))}catch(t){Mr.error("Error executing queued PostHog call",e,t)}})};r(i,this),r(s,this),r(n,this)}finally{Ru--}}push(t){if(Ru>0&&pt(t)&&yt(t[0])){const i=e.prototype[t[0]];return void(gt(i)&&i.apply(this,t.slice(1)))}this._execute_array([t])}get _facebookClickIdChannel(){return{property:V,persistenceKey:G,cookieName:"_fbc",pattern:zu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[G]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(G)}}}get _facebookBrowserIdChannel(){return{property:K,persistenceKey:Y,cookieName:"_fbp",pattern:Hu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[Y]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(Y)}}}_getPersistedMetaIdentifier(e){var t;const i=null===(t=this.persistence)||void 0===t?void 0:t.get_property(e.persistenceKey);return yt(i)&&e.pattern.test(i)?{value:i,delivered:!1}:ft(i)&&yt(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=Gr(e.cookieName);return yt(t)&&e.pattern.test(t)?t:void 0}_updateFacebookClickId(e,t,i,s){if(!this.persistence)return;const n=this._facebookClickIdChannel,r=this._getPersistedMetaIdentifier(n);if(s)return void n.unregister();if(i)return yt(t)&&zu.test(t)?this._storeMetaIdentifier(n,t,r):void n.unregister();const o=yt(e)&&Uu.test(e)?e:void 0,a=this._readMetaCookie(n);return a&&((e,t,i)=>{const s=e.split(".");if(t)return s[3]===t;if(!i)return!0;const n=i.value.split(".");return s[3]===n[3]||Number(s[2])>Number(n[2])})(a,o,r)?this._storeMetaIdentifier(n,a,r):o?(null==r?void 0:r.value.split(".")[3])===o?{value:r.value,pending:!r.delivered}:this._storeMetaIdentifier(n,`fb.1.${Date.now()}.${o}`,r):r?{value:r.value,pending:!r.delivered}:void 0}_updateFacebookBrowserId(e,t,i){if(!this.persistence)return;const s=this._facebookBrowserIdChannel,n=this._getPersistedMetaIdentifier(s);if(i)return void s.unregister();if(t)return yt(e)&&Hu.test(e)?this._storeMetaIdentifier(s,e,n):void s.unregister();const r=this._readMetaCookie(s);return r?this._storeMetaIdentifier(s,r,n):n?{value:n.value,pending:!n.delivered}:void 0}_markMetaIdentifiersDelivered(e){if(!this.persistence)return;const t=({channel:e,value:t})=>{const i=this._getPersistedMetaIdentifier(e);return(null==i?void 0:i.value)===t&&!i.delivered},i=e.filter(t);i.length&&(this.persistence.refreshMetaIdentifiers(),i.filter(t).forEach(({channel:e,value:t})=>e.register(t,!0)))}capture(e,t,i){var s,n,r;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue))return void Mr.uninitializedWarning("posthog.capture");if(!this.is_capturing())return void Mr.info(`Event "${e}" was not captured because capturing is disabled (opted out or consent pending).`);if(mt(e)||!yt(e))return void Mr.error("No event name provided to posthog.capture");if(this._syncCookielessIdentity(),"$snapshot"===e&&this._inCookielessMode())return;const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return this._botFilterWarned||(this._botFilterWarned=!0,console.warn("[PostHog.js] Events are being dropped because the user agent looks like a bot. Set `opt_out_useragent_filter: true` to capture them, e.g. in end-to-end tests. Note that logs from `captureLog` are not subject to this filter.")),void Mr.info(`Event "${e}" was not captured because the user agent looks like a bot. Set \`opt_out_useragent_filter: true\` to capture it.`);const a=(null==i?void 0:i.skip_client_rate_limiting)?void 0:this.rateLimiter.clientRateLimitContext();if(null==a?void 0:a.isRateLimited)return void Mr.critical("This capture call is ignored due to client rate limiting.");let l;(null==t?void 0:t.$current_url)&&!yt(null==t?void 0:t.$current_url)&&(Mr.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)||Mr.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&&(l=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 c=new Date,u=(null==i?void 0:i.timestamp)||c,d=Zi(null==i?void 0:i.uuid,eo);let h={uuid:d,event:e,properties:this.calculateEventProperties(e,t||{},u,d)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&o&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),a&&(h.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const _="$feature_flag_called"===e&&!1===h.properties.$feature_flag_has_experiment&&!0===this.get_property("$minimal_flag_called_events");(null==i?void 0:i.$set)&&!_&&(h.$set=null==i?void 0:i.$set);const p=ft(null==t?void 0:t.$set)?t.$set:void 0,g=pt(null==t?void 0:t.$unset)?t.$unset:[],f=(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||!!p&&e in p,provided:s?null==i||null===(t=i.$set)||void 0===t?void 0:t[e]:null==p?void 0:p[e],unset:-1!==g.indexOf(e)||-1!==f.indexOf(e)}};this.persistence.refreshMetaIdentifiersBeforeCapture();const m=v(V),y=v(K),b=[{channel:this._facebookClickIdChannel,hasProvided:m.hasProvided,update:this._updateFacebookClickId(null==l?void 0:l.fbclid,m.provided,m.hasProvided,m.unset)},{channel:this._facebookBrowserIdChannel,hasProvided:y.hasProvided,update:this._updateFacebookBrowserId(y.provided,y.hasProvided,y.unset)}];for(const{channel:e,hasProvided:t,update:i}of b)i&&!0===h.properties.$process_person_profile&&i.pending&&!t&&!_&&(h.$set=ls({[e.property]:i.value},h.$set));const S=null==i?void 0:i.$unset;S&&(h.$unset=S);const w=_?void 0:this._calculate_set_once_properties(null==i?void 0:i.$set_once,e!==it,e===tt);if(w&&(h.$set_once=w),(null==i?void 0:i._noTruncate)||(C=this.config.properties_string_max_length,h=function(e,t){const i=new Set;return function e(s,n){if(s!==Object(s))return t?t(s):s;if(i.has(s))return;let r;if(i.add(s),pt(s))r=[],Lr(s,t=>{r.push(e(t))});else{const t={};Dr(Ft(s)?Hr(s):s,(s,n)=>{i.has(s)||(t[n]=e(s,n))}),r=t}return r}(e)}(h,e=>yt(e)?e.slice(0,C):e)),h.timestamp=u,mt(null==i?void 0:i.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=c),_&&(h.properties=((e,t=[])=>{const i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return nn.forEach(s),t.forEach(s),i})(h.properties,qu)),e===bl.DISMISSED||e===bl.SENT){const i=null==t?void 0:t[Sl.SURVEY_ID],s=null==t?void 0:t[Sl.SURVEY_ITERATION];ru({id:i,current_iteration:s}),h.$set=ls(ls({},h.$set),{},{[Vc({id:i,current_iteration:s},e===bl.SENT?"responded":"dismissed")]:!0})}else e===bl.SHOWN&&(h.$set=ls(ls({},h.$set),{},{[Sl.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));var C;if(e===kl.SHOWN){const e=null==t?void 0:t[xl.TOUR_TYPE];e&&(h.$set=ls(ls({},h.$set),{},{[`${xl.TOUR_LAST_SEEN_DATE}/${e}`]:(new Date).toISOString()}))}const E=ls(ls({},h.properties.$set),h.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!wt(this.config.before_send)){const e=this._runBeforeSend(h);if(!e)return;h=e,h.uuid=Zi(h.uuid,eo)}this.sessionRecording&&!this._replayDebugPropertiesPaused&&Bu(e)&&(this._replayDebugPropertiesPaused=!0,setTimeout(()=>this._replayDebugPropertiesPaused=!1,3e4));const k=[];b.forEach(({channel:e,update:t})=>{var i,s,n;const r=null!==(i=null===(s=h.$set)||void 0===s?void 0:s[e.property])&&void 0!==i?i:ft(null===(n=h.properties)||void 0===n?void 0:n.$set)?h.properties.$set[e.property]:void 0;(null==t?void 0:t.pending)&&r===t.value&&k.push({channel:e,value:t.value})}),this._internalEventEmitter.emit("eventCaptured",h);const x=null!==(s=null==i?void 0:i._url)&&void 0!==s?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),P="recordings"===(null==i?void 0:i._batchKey)||/\/s\/(?:\?|$)/.test(x),T=ls(ls(ls({method:"POST",url:x,data:h,compression:"best-available",preferSyncCompression:null==i?void 0:i.send_instantly,timestampMode:P?"body":"capture-body",batchKey:null==i?void 0:i._batchKey},P&&(null===(n=h.properties)||void 0===n?void 0:n.$session_id)?{batchGroup:h.properties.$session_id+(h.properties.$window_id?`-${h.properties.$window_id}`:"")}:{}),(null==i?void 0:i.transport)?{transport:i.transport}:{}),k.length?{fireCallbackOnDrop:!0,callback:e=>{e.statusCode>=200&&300>e.statusCode&&this._markMetaIdentifiersDelivered(k)}}:{});if(!this.config.request_batching||i&&!(null==i?void 0:i._batchKey)||(null==i?void 0:i.send_instantly)){var I;let e;!T.transport&&!T.callback&&vt(null!==(I=this.config.request_headers)&&void 0!==I?I:{})&&this._isPageUnloading&&(e="sendBeacon"),this._send_retriable_request(T,e)}else this._requestQueue.enqueue(T);return null===(r=this.featureFlags)||void 0===r||r.sendFlagCallsPendingCapture(),h}_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 Iu(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;return!!(null===(t=this.persistence)||void 0===t?void 0:t.consumeCookieIdentityChange())&&(this._processIdentityChange(e),!0)}_processIdentityChange(e=!0){var t,i,s;this._cachedPersonProperties=null,"anonymous"===(null===(t=this.persistence)||void 0===t?void 0:t.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()}calculateEventProperties(e,i,n,r,l){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return i;this._syncCookielessIdentity(),this.persistence.syncCookieProperties(),this._processCookieIdentityChange();const c=l?void 0:this.persistence.remove_event_timer(e);let u=ls({},i);if(u.token=this.config.token,u.$config_defaults="latest"===this.config.defaults?Wu:this.config.defaults,this._inCookielessMode()&&(u[Le]=!0),"$snapshot"===e){const e=ls(ls({},this.persistence.properties()),this.sessionPersistence.properties());return u.distinct_id=e.distinct_id,(!yt(u.distinct_id)&&!Ct(u.distinct_id)||bt(u.distinct_id))&&Mr.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),u}const d=function(e,i,n,r=!1){var o,l,c,u;if(!h)return{};const d=e?[...Na,...i||[]]:[],[_,p]=Ui(h),[g,f]=function(e){for(let t=0;ji.length>t;t++){const[i,s,n]=ji[t],r=e.match(i);if(r){const t=n&&e.match(n)||r;return[s,(null==t?void 0:t[1])||""]}}return["",""]}(h),v=function(){const e="u">typeof navigator?navigator:void 0;return(null==e?void 0:e.brave)?{brave:!0}:{}}(),m={};mt(n)||(m.detectGoogleSearchApp=n);const y={},b=null===(o=navigator)||void 0===o||null===(o=o.userAgentData)||void 0===o?void 0:o.platform,S=null===(l=navigator)||void 0===l?void 0:l.maxTouchPoints,w=null==s||null===(c=s.screen)||void 0===c?void 0:c.width,C=null==s||null===(u=s.screen)||void 0===u?void 0:u.height,E=null==s?void 0:s.devicePixelRatio;mt(b)||(y.userAgentDataPlatform=b),mt(S)||(y.maxTouchPoints=S),mt(w)||(y.screenWidth=w),mt(C)||(y.screenHeight=C),mt(E)||(y.devicePixelRatio=E);const k=Nr(zr({$os:_,$os_version:p,$browser:Li(h,navigator.vendor,v,m),$webview_app:g,$webview_app_version:f,$device:zi(h),$device_type:Hi(h,y),$timezone:Ia(),$timezone_offset:Ja()}),{$current_url:La(r?es(null==a?void 0:a.href):null==a?void 0:a.href,d,Ua),$host:null==a?void 0:a.host,$pathname:null==a?void 0:a.pathname,$raw_user_agent:h.length>1e3?h.substring(0,997)+"...":h,$browser_version:Ni(h,navigator.vendor,v,m),$browser_language:Wa(),$browser_language_prefix:Va(),$screen_height:null==s?void 0:s.screen.height,$screen_width:null==s?void 0:s.screen.width,$viewport_height:null==s?void 0:s.innerHeight,$viewport_width:null==s?void 0:s.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&&(k.$sdk_dist_channel=t.SDK_DIST_CHANNEL),k}(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(l,n.getTime(),!0);u.$session_id=e,u.$window_id=t}let _,p;this.sessionPropsManager&&Nr(u,this.sessionPropsManager.getSessionProps());try{var g;if(this.sessionRecording){const t=this.sessionRecording.sdkDebugProperties,i=!this._replayDebugPropertiesPaused&&Bu(e);for(const e in t)(i||at(Du,e))&&(u[e]=t[e])}_=null===(g=this._retryQueue)||void 0===g?void 0:g.length}catch(e){u.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===Xc&&(u.$lib_custom_api_host=this.config.api_host),p="$pageview"!==e||l?"$pageleave"!==e||l?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,r),u=Nr(u,p),"$pageview"===e&&o&&(u.title=o.title),!mt(c)){const e=n.getTime()-c;u.$duration=parseFloat((e/1e3).toFixed(3))}h&&this.config.opt_out_useragent_filter&&(u.$browser_type=this._is_bot()?"bot":"browser");const f=this.persistence.properties(),v=this.sessionPersistence.properties(),m=u.$groups,y=f.$groups;ft(m)&&!vt(m)&&(u.$groups=ls(ls({},ft(y)?y:{}),m)),Dr(["$referrer","$referring_domain"],e=>{e in f&&delete v[e]});const b={};if(this._extensionEventPropertyProducers.length>0)for(const e of this._extensionEventPropertyProducers.slice())try{Nr(b,e())}catch(e){Mr.error("Failed to produce browser extension event properties",e)}u=Nr({},d,f,v,ls(ls({},b),u)),_?u.$sdk_debug_retry_queue_size=_:delete u.$sdk_debug_retry_queue_size,u.$is_identified=this._isIdentified(),pt(this.config.property_denylist)?Dr(this.config.property_denylist,function(e){delete u[e]}):Mr.error(Lu+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const S=this.config.sanitize_properties;S&&(Mr.error(Ou),u=S(u,e));const w=this._hasPersonProcessing();return u.$process_person_profile=w,w&&!l&&this._requirePersonProcessing("_calculate_event_properties"),u}_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 n=this.persistence.get_initial_props(),r=null===(s=this.sessionPropsManager)||void 0===s?void 0:s.getSetOnceProps();let o=Nr({},n,r||{},e||{});const a=this.config.sanitize_properties;return a&&(Mr.error(Ou),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)||!wo._is_supported())return void wo._remove(this._sessionRegisteredPropertiesStorageKey);const t=[];this._sessionRegisteredPropKeys.forEach(e=>t.push(e)),t.length>0?wo._set(this._sessionRegisteredPropertiesStorageKey,t):wo._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:Mu}),()=>{})}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:Mu})}getActiveMatchingSurveys(e,t=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:Mu})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:Mu}),()=>{})}renderSurvey(e,t){var i;null===(i=this.surveys)||void 0===i||i.renderSurvey(e,t)}displaySurvey(e,t=au){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:Mu}}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:Mu})}_validateIdentifyId(e){return!e||bt(e)?(Mr.critical("Unique user id has not been set in posthog.identify"),!1):"$posthog_cookieless"===e?(Mr.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())||(Mr.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 Mr.uninitializedWarning("posthog.identify");if(Ct(e)&&(e=e.toString(),Mr.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(),n=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,r=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(j),this.register({distinct_id:e}));const o=(this.persistence.get_property("$user_state")||"anonymous")===Ye,c=e!==s,u=!c&&o;if(c&&o){var l;const n=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:s};this.persistence.set_property(Te,Qe),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$identify",n,{$set:t||{},$set_once:i||{}})&&(this._cachedPersonProperties=Zc(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(Te,Qe);const s=t||{},n=i||{};this.setPersonPropertiesForFlags({$set:s,$set_once:n},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:s,$set_once:n})&&(this._cachedPersonProperties=Zc(e,t,i))}else(t||i)&&this.setPersonProperties(t,i);c||n||r?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(x)):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=Zc(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)):Mr.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var t;const i=(pt(e)?e:[e]).filter(e=>yt(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 Mr.error("posthog.group requires a group type and group key");null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange();const n=this.getGroups(),r=n[e]!==t;if(r&&this.resetGroupPropertiesForFlags(e),this.register({$groups:ls(ls({},n),{},{[e]:t})}),(r||i)&&this._hasPersonProcessing()){const s={$group_type:e,$group_key:t};i&&(s.$group_set=i),this.capture(it,s)}i&&this.setGroupPropertiesForFlags({[e]:i}),r&&!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=kt(e)?e:null==e?void 0:e.resetDeviceID,i=kt(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t=!1,i){var s,n,r,o,a,l;if(Mr.info("reset"),!this.__loaded)return Mr.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===(n=this.featureFlags)||void 0===n||null===(r=n.updateConfig)||void 0===r||r.call(n,this.config,this._shouldDisableFlags());const u=this.get_property(H),d=this.get_property(q),h=this.get_property(oe);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 f=!1;try{var v,m,y,b,S,w,C,E,k,x,P,T,I;if(null===(v=this.persistence)||void 0===v||v.clear(),null===(m=this.sessionPersistence)||void 0===m||m.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),mt(h)||null===(x=this.persistence)||void 0===x||x.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===(S=this.conversations)||void 0===S||S.reset(),null===(w=this.logs)||void 0===w||w.reset(),null===(C=this.metrics)||void 0===C||C.reset(),null===(E=this.persistence)||void 0===E||E.set_property("$user_state","anonymous"),null===(k=this.sessionManager)||void 0===k||k.resetSessionId(),this._cachedPersonProperties=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:Oe,$device_id:null},"");else{const t=this.config.get_device_id(eo());this.register_once({distinct_id:t,$device_id:e?t:u},""),e||mt(d)||this.register({[q]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),i)if(i.distinctID&&!this._inCookielessMode()&&(null===(I=this.persistence)||void 0===I||I.set_property("$user_state",i.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:i.distinctID})),null===(P=this.featureFlags)||void 0===P||P.initialize(),!wt(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,f=!0}finally{var F,R;this._isConsentTransition=g,p&&(null===(F=this.persistence)||void 0===F||null===(R=F._endCookieSyncSuppression)||void 0===R||R.call(F,f))}var A;this._lastRemoteConfig&&(null===(A=this.conversations)||void 0===A||A.onRemoteConfig(this._lastRemoteConfig)),this.reloadFeatureFlags()}shutdown(e){var t=this;return Dt(function*(){if(!t.__loaded)return void Mr.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&&gt(e.then)&&e.then(void 0,e=>{Mr.error("Error during shutdown",e)})}catch(e){Mr.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 n;const t=null!==(n=e.timestampLookBack)&&void 0!==n?n: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")?(Mr.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(mt(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(j,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(Mr.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const t=ls({},this.config);if(ft(e)){var s,n,r,o,a,l,c,u,d,h,_,p,g,f;Nr(this.config,Yu(e));const S=this._is_persistence_disabled();if(this.persistence){const e="sessionStorage"===this.config.persistence||"memory"===this.config.persistence;var v,m;if(e&&this.sessionPersistence!==this.persistence&&(null===(v=this.sessionPersistence)||void 0===v||v.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 ul(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;kt(w)&&(this.config.debug=w),kt(this.config.debug)&&(this.config.debug?(i.DEBUG=!0,ao._is_supported()&&ao._set("ph_debug",!0),Mr.info("set_config",{config:e,oldConfig:t,newConfig:ls({},this.config)})):(i.DEBUG=!1,ao._is_supported()&&ao._remove("ph_debug"))),null===(s=this.featureFlags)||void 0===s||null===(n=s.updateConfig)||void 0===n||n.call(s,this.config,this._shouldDisableFlags()),null===(r=this.exceptionObserver)||void 0===r||r.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===(f=this.externalIntegrations)||void 0===f||f.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&ba(this,Au,!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,n,r,o,a;Object.values(i).some(Boolean)&&(null===(s=this.sessionManager)||void 0===s||s.checkAndGetSessionAndWindowId(),i.sampling&&(null===(n=this.sessionRecording)||void 0===n||n.overrideSampling()),i.linked_flag&&(null===(r=this.sessionRecording)||void 0===r||r.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:ju;return t!==ju&&(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?(Mr.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(Me,!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,n,r;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===(n=this.persistence)||void 0===n||n.set_disabled(i)),(null===(t=this.sessionPersistence)||void 0===t?void 0:t._disabled)!==i&&(null===(r=this.sessionPersistence)||void 0===r||r.set_disabled(i)),this._persistSessionRegisteredPropKeys(),i}opt_in_capturing(t){var i,s,n;if("always"===this.config.cookieless_mode)return void Mr.warn($u);if(this._inCookielessMode()){var r,o,a,l,c,u;null===(r=this.sessionRecording)||void 0===r||r.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null===(o=this.sessionManager)||void 0===o||o.destroy(),null===(a=this.pageViewManager)||void 0===a||a.destroy(),this.sessionManager=new Hc(this),this.pageViewManager=new Ea(this),this.persistence&&(this.sessionPropsManager=new Nc(this,this.sessionManager,this.persistence));const t=null!==(l=null===(c=this.config.__extensionClasses)||void 0===c?void 0:c.sessionRecording)&&void 0!==l?l:null===(u=e.__defaultExtensionClasses)||void 0===u?void 0:u.sessionRecording;var d,h;t&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new t(this)),this._lastRemoteConfig&&(null===(d=this.sessionRecording)||void 0===d||null===(h=d.onRemoteConfig)||void 0===h||h.call(d,this._lastRemoteConfig)))}const _=1===this.consent.consent;var p,g,f;_&&this._syncCookielessIdentity(),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===(p=this.surveys)||void 0===p||p.loadIfEnabled(),null===(g=this.conversations)||void 0===g||g.loadIfEnabled()),_||!mt(null==t?void 0:t.captureEventName)&&!(null==t?void 0:t.captureEventName)||this.capture(null!==(f=null==t?void 0:t.captureEventName)&&void 0!==f?f:"$opt_in",null==t?void 0:t.captureProperties,{send_instantly:!0}),null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange(),null===(n=this.featureFlags)||void 0===n||n.sendFlagCallsPendingCapture(),this.config.capture_pageview&&this._captureInitialPageview()}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()):Mr.warn($u)}_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:Oe,$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 r?jc(r,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){o&&("visible"===o.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(Xe,{title:o.title},{send_instantly:!0}),this._visibilityStateListener&&(o.removeEventListener(R,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),Wr(o,R,this._visibilityStateListener)))}debug(e){!1===e?(null==s||s.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==s||s.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?(Mr.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,n){const r=t in e&&!wt(e[t]),o=i in e&&!wt(e[i]);return r?e[t]:!!o&&(n&&n.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,Mr)}_runBeforeSend(e){var t;if(wt(this.config.before_send))return e;const i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Pt),s=pt(this.config.before_send)?this.config.before_send:[this.config.before_send];let n=e;for(const t of s)try{if(n=t(n),wt(n)){const t=`Event '${e.event}' was rejected in beforeSend function`;return xt(e.event)?Mr.warn(`${t}. This can cause unexpected behavior.`):Mr.info(t),null}n.properties&&!vt(n.properties)||Mr.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(t){return Mr.error(`Error in beforeSend function for event '${e.event}':`,t),null}for(const t of i)if(n.properties&&wt(n.properties[t]))return Mr.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 n}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=kt(e)&&!e,i=ao._is_supported()&&"true"===ao._get("ph_debug");return!t&&(!!i||e)}};Ju.__defaultExtensionClasses={},Ju._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]]=Ur(e.prototype[t[i]])}(Ju,["identify"]);const Zu=["[data-ph-capture-value]"];var Xu=class{constructor(e){this._instance=e}refresh(e){var t;const i=this._instance.config,s=ft(i.autocapture)?i.autocapture:void 0;e.enabled=!!i.autocapture,e.rageclick=i.rageclick,e.maskAllElementAttributes=i.mask_all_element_attributes,e.maskAllText=i.mask_all_text,e.disableCaptureUrlHashes=i.disable_capture_url_hashes,e.getCurrentUrl=i.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==s?void 0:s.url_allowlist,e.url_ignorelist=null==s?void 0:s.url_ignorelist,e.dom_event_allowlist=null==s?void 0:s.dom_event_allowlist,e.element_allowlist=null==s?void 0:s.element_allowlist,e.css_selector_allowlist=null==s?void 0:s.css_selector_allowlist,e.css_selector_ignorelist=null==s?void 0:s.css_selector_ignorelist,e.element_attribute_ignorelist=null==s?void 0:s.element_attribute_ignorelist,e.capture_copied_text=null==s?void 0:s.capture_copied_text,e.capture_value_css_selector_allowlist=null!==(t=null==s?void 0:s.capture_value_css_selector_allowlist)&&void 0!==t?t:Zu}};const ed=Or("[ExceptionAutocapture]"),td=()=>{},id=e=>{var t;if(gt(e))return null!==(t=e.__posthog_layer__)&&void 0!==t?t:e.__rrweb_layer__};function sd(e,t,i){try{if(!(t in e))return td;const s={next:e[t]},n=i(function(...e){return s.next.apply(this,e)});return gt(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=n,()=>{if(e[t]===n)return void(e[t]=s.next);let i=e[t],r=id(i);for(;r;){if(r.next===n)return void(r.next=s.next);i=r.next,r=id(i)}}}catch(e){return td}}const nd=Or("[TracingHeaders]"),rd=Or("[Web Vitals]"),od=9e5,ad=["CLS","FCP","INP","LCP"],ld=["INP","LCP"],cd=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],ud="disabled",dd="lazy_loading";function hd(e){return"ph_replay_pending_buffer_"+JSON.stringify([e.persistence_name||e.token,e.token])}const _d=Or("[SessionRecording]"),pd=[Be,Ue,ze,He,qe,je,We,Ve,Ge],gd=Or("[Heatmaps]");function fd(e){return ft(e)&&"clientX"in e&&"clientY"in e&&Ct(e.clientX)&&Ct(e.clientY)}const vd=Or("[Product Tours]"),md=e=>{var t;return!e.config.disable_product_tours&&!!(null===(t=e.persistence)||void 0===t?void 0:t.get_property(se))},yd=["$set_once","$set"],bd=Or("[SiteApps]"),Sd="Error while initializing PostHog app with config id ";function wd(e,t,i){if(wt(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 Cd=class{constructor(e){this._host=e,this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new Bc,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;mt(null===(e=this._host)||void 0===e?void 0:e.subscribeCapture)||(this._captureHookUnsubscribe=null===(t=this._host)||void 0===t?void 0:t.subscribeCapture((e,t)=>{this.on(e,t)}))}dispose(){var e,t,i;null===(e=this._captureHookUnsubscribe)||void 0===e||e.call(this),this._captureHookUnsubscribe=void 0,null===(t=this._host)||void 0===t||null===(i=t.setElementSelectors)||void 0===i||i.call(t,new Set,this),this._debugEventEmitter=new Bc}register(e){var t,i;if(!mt(null===(t=this._host)||void 0===t?void 0:t.subscribeCapture)&&(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._host)||void 0===i?void 0:i.setElementSelectors)){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._host.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;let r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$current_url;if(!(null==e?void 0:e.properties)||!("$current_url"in e.properties))try{var s,n;r=null===(s=this._host)||void 0===s||null===(n=s.getActionUrl)||void 0===n?void 0:n.call(s)}catch(e){return!1}if(!r||"string"!=typeof r)return!1;if(!wd(r,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=>wd(e.href,t.href,t.href_matching||"exact"));const n=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!n&&wd(function(e){const t=e.match(/(?::|")href="(.*?)"/);return t?t[1]:""}(n),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=>wd(e.text,t.text,t.text_matching||"exact")||wd(e.$el_text,t.text,t.text_matching||"exact"));const n=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!n&&(r=function(e){const t=[],i=/(?::|")text="(.*?)"/g;let s;for(;!wt(s=i.exec(e));)t.includes(s[1])||t.push(s[1]);return t}(n),o=t.text,a=t.text_matching||"exact",r.some(e=>wd(e,o,a)));var r,o,a}_checkStepSelector(e,t){var i,s;if(!(null==t?void 0:t.selector))return!0;const n=null==e||null===(i=e.properties)||void 0===i?void 0:i.$element_selectors;if(null==n?void 0:n.includes(t.selector))return!0;const r=(null==e||null===(s=e.properties)||void 0===s?void 0:s.$elements_chain)||"";if(t.selector_regex&&r)try{return new RegExp(t.selector_regex).test(r)}catch(e){}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||Jc(t.properties.reduce((e,t)=>{const i=pt(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)}},Ed=class{constructor(e,t){this._onActivationChanged=t,this._pendingActivatedItems=[],this._host=e,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map}_subscribeSession(){var e,t;this._sessionIdUnsubscribe=null===(e=(t=this._host).subscribeSession)||void 0===e?void 0:e.call(t,e=>this._onSessionIdChanged(e))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Jc(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===hl.Activation?this._eventToItems:this._cancelEventToItems).get(e);let n=[];return this._getItems(e=>{n=e.filter(e=>null==s?void 0:s.includes(e.id))}),n.filter(s=>{var n;const r=null===(n=s.conditions)||void 0===n||null===(n=n[i])||void 0===n||null===(n=n.values)||void 0===n?void 0:n.find(t=>t.name===e);return this._doesEventMatchFilter(r,t)})}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){mt(this._host.subscribeCapture)||(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 Cd(this._host),this._actionMatcher.init(),this._actionMatcher._addActionHook(e=>this.onAction(e)));const n=[];i.forEach(e=>{var t;null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||t.values.forEach(t=>{if(n.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(n):this._actionMatcher.register(n)}_mergeItemMaps(e,t){t.forEach((t,i)=>{var s;const n=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach(e=>{n.includes(e)||n.push(e)}),e.set(i,n)})}_setupEventBasedItems(e,t){var i,s,n;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}),o=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}),a=this._buildEventToItemMap(e,hl.Activation),l=this._buildEventToItemMap(e,hl.Cancellation);t?(this._eventToItems=a,this._cancelEventToItems=l):(this._mergeItemMaps(this._eventToItems,a),this._mergeItemMaps(this._cancelEventToItems,l)),(0!==r.length||0!==o.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=(n=this._host).subscribeCapture)||void 0===s?void 0:s.call(n,(e,t)=>{this.onEvent(e,t)})))}onEvent(e,t){var i,s;const n=this._getLogger(),r=(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(r&&this.getActivatedIds().includes(r)){const i=this._activationOutcome(e,r,t);if("consume"===i)return n.info("event consumed activated item, removing it",{event:e,itemId:r}),void this._deactivateItems([r]);if("persist"===i)return n.info("shown item promoted to persisted activation",{event:e,itemId:r}),this._persistActivation(r),void this._clearActivationTimestamps([r])}if(this._cancelEventToItems.has(e)){const i=this._getMatchingItems(e,t,hl.Cancellation);i.length>0&&(n.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;n.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});const o=this._getMatchingItems(e,t,hl.Activation);this._activateItems(o.map(e=>e.id))}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){if(0===e.length)return;const t=!!this._host.getSessionId(),i=[];for(const s of e)t&&this._shouldPersistArmedActivation(s)?this._persistActivation(s)&&this._recordActivationTimestamp(s):i.push(s);i.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...i])]),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(){const e=this._getActivationTimestampsKey();if(!e)return{};const t=this._host.getProperty(e);return t&&"object"==typeof t?t:{}}_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[n,r]of Object.entries(t))e.includes(n)?s=!0:i[n]=r;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 Ct(t)?t:void 0}_getRawPersistedActivatedIds(){const e=this._getActivatedKey();return this._host.getProperty(e)||[]}_getPersistedActivatedIds(){const e=this._getRawPersistedActivatedIds();if(0===e.length)return[];const t=this._host.getProperty(this._getActivatedSessionKey()),i=this._host.getSessionId();return i&&t===i?e:[]}_stampActivationSession(){const e=this._host.getSessionId();e&&this._setActivatedSession(e)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){const t=this._host.getProperty(this._getActivatedSessionKey());if(t&&t!==e){const e=this._getRawPersistedActivatedIds(),t=this._getRawActivationTimestamps();e.length>0&&(this._setActivatedItems([]),e.filter(e=>Ct(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}},kd=class extends Ed{constructor(e,t,i,s){var n;super({subscribeCapture(t){const i=e.onEvent(e=>t(e.event,e));return()=>i.dispose()},subscribeSession(t){const i=e.onSession(t);return()=>i.dispose()},getSessionId(){var t;return null===(t=e.session)||void 0===t?void 0:t.sessionId},getProperty:t=>e.kv.get(t),getActionUrl:null==i?void 0:i.getActionUrl,setElementSelectors:null!==(n=null==i?void 0:i.setElementSelectors)&&void 0!==n?n:(t,i)=>{var s;return null===(s=e.getExtension("autocapture"))||void 0===s?void 0:s.setElementSelectors(t,i)}},s),this._client=e,this._surveys=t,this._subscribeSession()}_getActivatedKey(){return D}_getActivatedSessionKey(){return N}_getActivationTimestampsKey(){return B}_writeActivationTimestamps(e){this._client.kv.set({[B]:e})}_clearActivationTimestampsStore(){this._client.kv.remove(B)}_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 Ct(s)&&s>0}_getShownEventName(){return bl.SHOWN}_getItems(e){this._surveys.getSurveys(e)}_cancelPendingItem(e){this._surveys.cancelPendingSurvey(e)}_getLogger(){return nu}_setActivatedItems(e){this._client.kv.set({[D]:e})}_setActivatedSession(e){this._client.kv.set({[N]:e})}_clearActivatedSession(){this._client.kv.remove(N)}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t,i){var s;if(e===bl.SENT&&!1===(null==i||null===(s=i.properties)||void 0===s?void 0:s.$survey_completed))return"ignore";let n;return this._getItems(e=>{n=e.find(e=>e.id===t)}),!n||function(e){var t;return Gc(e)&&!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t?void 0:t.repeatedActivation)||"always"===e.schedule}(n)?e===bl.SHOWN?"consume":"ignore":e===bl.SHOWN?"persist":e===bl.DISMISSED||e===bl.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}};const xd=(e,t)=>(null==e?void 0:e.then)?e.then(t):t(e),Pd="SDK is not enabled or survey functionality is not yet loaded",Td="Disabled. Not loading surveys.";var Id=class{constructor(e){this._configSource=e,this.name="surveys",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."}),nu.warn("Remote config unavailable. Not loading surveys.");const t=e.config.surveys;if(wt(t))return nu.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=kt(t)?t:t.length>0,nu.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,xd(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,n;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===(n=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===n||n.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0,this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach(e=>clearTimeout(e)),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}getRenderContext(){if(!this._client)return;const e=this;return{client:this._client,get config(){return e._config},surveys:e}}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 nu.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void nu.info(Td);if(e.cookielessMode&&this._client.isOptedOut)return void nu.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(mt(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(L),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;if(this._disposed)return;this._surveyManager=e(t),this._surveyEventReceiver=this._createEventReceiver(this._client,this._notifyActiveMatchingSurveyCallbacks);const s=null===(i=this._client)||void 0===i?void 0:i.kv.get(M);s&&this._registerEventOrActionBasedSurveys(s),nu.info("Surveys loaded successfully"),this._startActiveMatchingSurveyConditions(),this._notifyActiveMatchingSurveyCallbacks(),this._notifySurveyCallbacks({isLoaded:!0})}_createEventReceiver(e,t){return new kd(e,this,void 0,t)}_handleSurveyLoadError(e,t){this._surveyInitializationFailed=!0,nu.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){if(this._disposed)return;const i=this._client;if(!i)return e([],{isLoaded:!1,error:Pd});if(this._config.disableSurveys)return nu.info(Td),e([]);const s=i.kv.get(M);if(s&&!t)return e(s,{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=>nu.error("Error in survey callback",e));const n=i.sendRequest("/api/surveys/",{method:"GET",query:{token:i.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then(e=>{try{return this._handleSurveyResponse(i,e)}catch(e){return nu.error("Error processing surveys response",e),this._handleSurveyResponse(i,{statusCode:0,error:e})}},e=>this._handleSurveyResponse(i,{statusCode:0,error:e}));this._getSurveysInFlightPromise=n;const r=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then(t=>{r(),this._disposed||(this._notifyActiveMatchingSurveyCallbacks(t.context),e(t.surveys,t.context))},r).catch(e=>nu.error("Error in survey callback",e))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Pd}};const i=t.statusCode;if(200!==i||!t.json){const e=`Surveys API could not be loaded, status: ${i}`;return 0!==i?nu.error(e):t.error||nu.warn(e),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:e}}}this._lastSurveyRefreshFailedAt=null;const s=t.json.surveys||[];return e.kv.set({[M]:s,[O]:Date.now()}),this._registerEventOrActionBasedSurveys(s),{surveys:s,context:{isLoaded:!0}}}_registerEventOrActionBasedSurveys(e){const t=e.filter(e=>function(e){return!(!e.start_date||e.end_date)}(e)&&(Gc(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)));this._registerSurveyTriggers(t)}_registerSurveyTriggers(e){var t;null===(t=this._surveyEventReceiver)||void 0===t||t.replace(e)}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e;const t=null===(e=this._client)||void 0===e?void 0:e.kv.get(O);return Ct(t)&&Date.now()-t>3e5}_isSurveyRefreshBackingOff(){return Ct(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};ru(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}_notifySurveyCallbacks(e){for(const t of this._surveyCallbacks){if(this._disposed)return;try{e.isLoaded?this.getSurveys(t):t([],e)}catch(e){nu.error("Error in survey callback",e)}}}getActiveMatchingSurveys(e,t=!1){if(!wt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);nu.warn("init was not called")}onActiveMatchingSurveysChanged(e){var t;if(this._disposed)return()=>{};const i={callback:e,active:!0,revision:0};this._activeMatchingSurveyCallbacks.push(i),this._startActiveMatchingSurveyConditions();const s=null===(t=this._client)||void 0===t?void 0:t.kv.get(M);return this._config.disableSurveys||!this._surveyManager&&this._surveyInitializationFailed&&!this._isInitializingSurveys||!s&&!wt(this._lastSurveyRefreshFailedAt)&&!this._getSurveysInFlightPromise?this._notifyActiveMatchingSurveyCallback(i,{isLoaded:!1}):this._surveyManager&&this._notifyActiveMatchingSurveyCallback(i),()=>{var e;i.active=!1,this._activeMatchingSurveyCallbacks=this._activeMatchingSurveyCallbacks.filter(e=>e!==i),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},n=JSON.stringify([s,i]);if(n===e.lastResult)return;e.lastResult=n,e.callback(s,i)}catch(e){nu.error("Error in active matching surveys callback",e)}};try{t&&!t.isLoaded?s([]):this.getActiveMatchingSurveys(s)}catch(e){nu.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(wt(this._surveyManager))return{eligible:!1,reason:Pd};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){var t;if(!(null===(t=this._client)||void 0===t?void 0:t.canCapture))return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(wt(this._surveyManager))return{eligible:!1,reason:Pd};const i="string"==typeof e?this._getSurveyById(e):e;return i?this._surveyManager.checkSurveyRenderability(i):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(wt(this._surveyManager))return nu.warn("init was not called"),{visible:!1,disabledReason:Pd};const t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return wt(this._surveyManager)?(nu.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Pd})):new Promise(i=>{this.getSurveys(t=>{var s;const n=null!==(s=t.find(t=>t.id===e))&&void 0!==s?s:null;if(n){const e=this._checkSurveyRenderability(n);i({visible:e.eligible,disabledReason:e.reason})}else i({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,i){var s,n,r;if(!(null===(s=this._client)||void 0===s?void 0:s.canCapture))return;if(wt(this._surveyManager))return void nu.warn("init was not called");const o="string"==typeof e?this._getSurveyById(e):e;if(!(null==o?void 0:o.id))return void nu.warn("Survey not found");if(!ou.includes(o.type))return void nu.warn(`Surveys of type ${o.type} cannot be rendered in the app`);const a=null===(n=typeof document>"u"?void 0:document)||void 0===n?void 0:n.querySelector(t);if(a){if(null===(r=o.appearance)||void 0===r?void 0:r.surveyPopupDelaySeconds){nu.info(`Rendering survey ${o.id} with delay of ${o.appearance.surveyPopupDelaySeconds} seconds`);const e=setTimeout(()=>{var t,s,n;this._renderTimeouts.delete(e),!this._disposed&&(null===(t=this._client)||void 0===t?void 0:t.canCapture)&&(nu.info(`Rendering survey ${o.id} with delay of ${null===(s=o.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds} seconds`),null===(n=this._surveyManager)||void 0===n||n.renderSurvey(o,a,i),nu.info(`Survey ${o.id} rendered`))},1e3*o.appearance.surveyPopupDelaySeconds);return void this._renderTimeouts.add(e)}this._surveyManager.renderSurvey(o,a,i)}else nu.warn("Survey element not found")}displaySurvey(e,t){var i,s;if(!(null===(i=this._client)||void 0===i?void 0:i.canCapture))return;if(wt(this._surveyManager))return void nu.warn("init was not called");const n=this._getSurveyById(e);if(!n)return void nu.warn("Survey not found");let r=n;if((null===(s=n.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds)&&t.ignoreDelay&&(r=ls(ls({},n),{},{appearance:ls(ls({},n.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==wl.Popover&&t.initialResponses&&nu.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){const e=this._checkSurveyEligibility(n);if(!e.eligible)return void nu.warn("Survey is not eligible to be displayed: ",e.reason)}t.displayType!==wl.Inline?this._surveyManager.handlePopoverSurvey(r,t):this.renderSurvey(r,t.selector,t.properties)}cancelPendingSurvey(e){wt(this._surveyManager)?nu.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)}},Fd=class{constructor(e){this._instance=e}get(){var e,t,i,s;const n=null===(e=this._instance)||void 0===e?void 0:e.config;return{disableSurveys:!!(null==n?void 0:n.disable_surveys),cookielessMode:!!(null==n?void 0:n.cookieless_mode),advancedEnableSurveys:!!(null==n?void 0:n.advanced_enable_surveys),requestTimeoutMs:null!==(t=null==n?void 0:n.surveys_request_timeout_ms)&&void 0!==t?t:1e4,prefillFromUrl:!!(null==n||null===(i=n.surveys)||void 0===i?void 0:i.prefillFromUrl),automaticDisplay:!(null==n?void 0:n.disable_surveys_automatic_display),featureFlagEvaluation:!(null==n?void 0:n.advanced_disable_feature_flags),overrideLanguage:null==n?void 0:n.override_display_language,prepareStylesheet:null==n?void 0:n.prepare_external_dependency_stylesheet,get_current_url:null==n?void 0:n.get_current_url,uiHost:null===(s=this._instance)||void 0===s||null===(s=s.requestRouter)||void 0===s?void 0:s.endpointFor("ui","")}}getExtensions(){const e=null==p?void 0:p.__PosthogExtensions__;if(!e||!this._instance)return;const t=this._instance,{generateSurveys:i}=e,s=g(t);return{generateSurveys:i?e=>i(t,e):void 0,loadExternalDependency:s?e=>s(t,"surveys",e):void 0}}onMatchingConditionsChanged(e){var t,i;const n=null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook(t=>{"$pageview"!==t&&t!==bl.SHOWN&&t!==bl.DISMISSED&&t!==bl.SENT||e()}),r=()=>e();Wr(s,"PHSurveyShown",r);let o=!1;const a=null===(i=this._instance)||void 0===i?void 0:i.onFeatureFlags(()=>{o&&e()});return o=!0,()=>{o=!1,null==n||n(),null==a||a(),null==s||s.removeEventListener("PHSurveyShown",r)}}};const Rd=(()=>(null==s?void 0:s.location)?Da(s.location.hash,"__posthog")||Da(location.hash,"state"):null)(),Ad="_postHogToolbarParams",$d=Or("[Toolbar]"),Md=Or("[FeatureFlags]"),Od=Or("[FeatureFlags]",{debugEnabled:!0}),Ld="\" failed. Feature flags didn't load in time.",Dd=[502,504],Nd=["click","keydown","wheel","touchstart","pointerdown"],Bd="connection_error",Ud=(e,t)=>{const i=Object.keys(t||{}).filter(e=>{var i;return null==t||null===(i=t[e])||void 0===i?void 0:i.failed});if(!i.length)return e||{};const s=ls({},e);return i.forEach(e=>delete s[e]),s},zd=(e,t)=>{const i=ls({},e);return t.forEach(e=>{var t;(null===(t=i[e])||void 0===t?void 0:t.failed)&&delete i[e]}),i},Hd=(e,t)=>!!(null==t?void 0:t.partialResponse)||!!e.errorsWhileComputingFlags,qd=e=>{const t={};for(let i=0;e.length>i;i++)t[e[i]]=!0;return t},jd=e=>{const t={};for(const[i,s]of Br(e||{}))s&&(t[i]=s);return t},Wd=(e,t)=>e.distinctId===t.distinctId&&e.sessionId===t.sessionId&&((e,t)=>{const i=Object.keys(e);return i.length===Object.keys(t).length&&i.every(i=>e[i]===t[i])})(e.groups,t.groups);var Vd=class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=Md,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._firingFeatureFlagsCallbacks=!1,this._flagCallsPendingCapture=new Map,this._sendingFlagCallsPendingCapture=!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;mt(i)||mt(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]"),xd(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&&Wr(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&&!mt(t)&&t>0?t:void 0;this._config.idleRefreshBackoff||(this._dueRefreshIntervalMs=i),i!==this._refreshIntervalMs&&(this._stopAutomaticRefresh(),mt(i)||(this._refreshIntervalMs=i,this._dueRefreshIntervalMs=i,this._scheduleNextRefresh(),(null===(e=this._document)||void 0===e?void 0:e.addEventListener)&&(Wr(this._document,R,this._onVisibilityChange),Lr(Nd,e=>{Wr(this._document,e,this._onUserInteraction,{capture:!0})}))))}_scheduleNextRefresh(){mt(this._refreshIntervalMs)||(mt(this._refreshInterval)||clearInterval(this._refreshInterval),this._lastRefreshAt=Date.now(),this._refreshInterval=setInterval(this._refreshIfDue,this._refreshIntervalMs))}_stopAutomaticRefresh(){var e,t;mt(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),Lr(Nd,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!mt(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")||{},n=e.$enabled_feature_flags||{},r=t.flags||t.featureFlags,o=t.flags?Object.entries(t.flags).filter(([,e])=>!(null==e?void 0:e.failed)).map(([e])=>e):[],a=!!t.errorsWhileComputingFlags&&!!t.flags,l=a||i&&t.flags?o:i&&!pt(r)?Object.keys(r||{}):Array.from(new Set([...Object.keys(s),...Object.keys(n)])),c=this._prop("$feature_flag_payloads")||{},u=e.$feature_flag_payloads||{},d=a||i?l:Array.from(new Set([...Object.keys(c),...Object.keys(u)])),h=!a&&!i,_=!!h||l,p=!!h||d,g={[v]:_,[C]:_,[T]:p};e.$feature_flag_details&&(g[m]=_);for(const t of[S,b,w])mt(e[t])||(g[t]=!0);this._crossTabPersistence.markCrossTabFeatureFlagChanges(g)}_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={},t=this._prop(m);for(const t of[S,I]){const i=this._prop(t);mt(i)||(e[t]=i)}const i=this._prop(v);i&&(e[v]=i.filter(e=>{var i;return!(null==t||null===(i=t[e])||void 0===i?void 0:i.failed)}));const s=this._prop(T);s&&(e[T]=Ud(s,t)),this._baseEventProperties=e;const n=ls({},e),r=Ud(this._prop(C),t);if(r)for(const[e,t]of Object.entries(r))n[`$feature/${e}`]=t;this._eventPropertiesWithFlagValues=n}_isCacheStale(){const e=this._config.cacheTtlMs;if(!e||0>=e)return!1;const t=this._prop(b);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(!mt(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 n,r;const e=null!==(n=null===(r=i.bootstrap)||void 0===r?void 0:r.featureFlagPayloads)&&void 0!==n?n:{},t=Object.keys(s).filter(e=>!mt(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){const s=(null==i?void 0:i.merge)?Ud(this._prop(C),this._prop(m)):{},n=(null==i?void 0:i.merge)?Ud(this._prop(T),this._prop(m)):{},r=ls(ls({},s),e),o=ls(ls({},n),t),a={};for(const[e,t]of Object.entries(r))a[e]={key:e,enabled:tn(t),variant:sn(t),reason:void 0,metadata:mt(null==o?void 0:o[e])?void 0:{id:0,version:void 0,description:void 0,payload:o[e]}};this._receivedFeatureFlags({flags:a})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this._prop(m),t=this._prop(I),i=this._prop(F);if(!i&&!t)return e||{};const s=Nr({},e||{}),n=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(const e of n){var r,o;const n=s[e],a=null==t?void 0:t[e],l=mt(a)?null!==(r=null==n?void 0:n.enabled)&&void 0!==r&&r:!!a,c=mt(a)?null==n?void 0:n.variant:"string"==typeof a?a:void 0,u=null==i?void 0:i[e],d=ls(ls({},n),{},{enabled:l,variant:l?null!=c?c:null==n?void 0:n.variant:void 0});l!==(null==n?void 0:n.enabled)&&(d.original_enabled=null==n?void 0:n.enabled),c!==(null==n?void 0:n.variant)&&(d.original_variant=null==n?void 0:n.variant),u&&(d.metadata=ls(ls({},null==n?void 0:n.metadata),{},{payload:u,original_payload:null==n||null===(o=n.metadata)||void 0===o?void 0:o.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:tn(s),variant:sn(s),payload:en(t[i])}})}getFlagVariants(){const e=Ud(this._prop(C),this._prop(m)),t=this._prop(I);if(!t)return e||{};const i=Nr({},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=Ud(this._prop(T),this._prop(m)),t=this._prop(F);if(!t)return e||{};const i=Nr({},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._firingFeatureFlagsCallbacks&&this._logger.warn("reloadFeatureFlags() was called inside an onFeatureFlags callback. This callback also runs when flags change in other tabs, so this can cause a request loop."),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(x),this._flagCallsPendingCapture=new Map}sendFlagCallsPendingCapture(){var e;if(0!==this._flagCallsPendingCapture.size&&!this._sendingFlagCallsPendingCapture&&(null===(e=this._client)||void 0===e?void 0:e.canCapture)&&!this._client.isRateLimited){this._sendingFlagCallsPendingCapture=!0;try{const e=this.getFlagVariants();for(const t of Array.from(this._flagCallsPendingCapture.keys())){const i=this._flagCallsPendingCapture.get(t);if(i){if(i.value!==String(e[t])||!Wd(i.context,this._flagCallContext())){this._flagCallsPendingCapture.delete(t);continue}if(this.getFeatureFlagResult(t),this._flagCallsPendingCapture.has(t))break}}}finally{this._sendingFlagCallsPendingCapture=!1}}}_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(E),timezone:Ia()};mt(i.deviceId)||(s.$device_id=i.deviceId),((null==e?void 0:e.disableFlags)||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);const n=this._getValidEvaluationEnvironments();n.length&&(s.evaluation_contexts=n);const r=this._getValidFlagKeys();mt(r)||(s.flag_keys=r);const o=this._config.onlyEvaluateSurveyFeatureFlags,a="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),l=this._requestGeneration,c=this._pendingReloads;this._pendingReloads=new Set,this._activeReloads=c,this._requestInFlight=!0;const u=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},d=e=>{var t,i;const n=null!==(t=e.json)&&void 0!==t?t:{},r=200!==e.statusCode;if(this._requestInFlight=!1,l!==this._requestGeneration)return void u();if(this._trackStatusZeroReachability(e.statusCode),r||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),s.disable_flags&&!this._additionalReloadRequested)return void this._settleReloads(c,"skipped");this._flagsLoadedFromRemote=!r;const a=[];e.error?a.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?Bd:"unknown_error"):200!==e.statusCode&&a.push(`api_error_${e.statusCode}`),n.errorsWhileComputingFlags&&a.push("errors_while_computing_flags");const d=!!(null===(i=n.quotaLimited)||void 0===i?void 0:i.includes("feature_flags"));d&&a.push("quota_limited"),this._set({[y]:a}),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(n,r,{partialResponse:o}),this._settleReloads(c,s.disable_flags?"skipped":a.length||!n.flags&&!n.featureFlags?"error":"loaded"),u()},h=e=>{this._requestInFlight=!1,l===this._requestGeneration?(this._set({[y]:[Bd]}),this._logger.error("Feature flag request failed",e),this._fallBackToPersistedFlags()&&this._fireFeatureFlagsCallbacks(!0),this._settleReloads(c,"error"),u()):u()};let _=null!==(t=this._config.requestMaxRetries)&&void 0!==t?t:1;const p=()=>_>0&&l===this._requestGeneration,g=()=>{if(l!==this._requestGeneration||!this._client||this._config.remoteRequestsDisabled)return this._requestInFlight=!1,this._settleReloads(c,"skipped"),void u();try{i.sendRequest(a,{target:"flags",method:"POST",body:s,compression:this._config.compression,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then(e=>{if((e=>Dd.includes(e.statusCode)||(e=>0===e.statusCode&&e.error instanceof Error&&"AbortError"===e.error.name)(e))(e)&&p())return _--,void setTimeout(g,500);d(e)}).catch(h)}catch(e){h(e)}};g()}_hasStatusZeroCircuitBreakerTripped(){return Aa(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=$a(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."))}_flagsNotLoaded(e){var t;return!this._hasLoadedFlags&&!this.getFlags().length&&!(null===(t=this.getFeatureFlagDetails(e))||void 0===t?void 0:t.failed)}getFeatureFlag(e,t={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(this._flagsNotLoaded(e))return void this._logger.warn('getFeatureFlag for key "'+e+Ld);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={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(this._flagsNotLoaded(e))return void this._logger.warn('getFeatureFlagResult for key "'+e+Ld);if(this._checkAndTriggerStaleRefresh())return;const s=null===(i=this._prop("$feature_flag_details"))||void 0===i||null===(i=i[e])||void 0===i?void 0:i.failed,n=s?void 0:this._prop(C),r=s?void 0:this._prop(T),o=this._prop(I),a=!!o&&{}.hasOwnProperty.call(o,e),l=a||!!n&&e in n,c=a?o[e]:null==n?void 0:n[e],u=this._prop(F),d=u&&{}.hasOwnProperty.call(u,e)?u[e]:null==r?void 0:r[e],h=String(c),_=this._prop("$feature_flag_request_id")||void 0,p=this._prop("$feature_flag_evaluated_at")||void 0;let g,f=this._prop("$flag_call_reported")||{};if(this._config.deduplicateCallsPerSession){var v;const e=null===(v=this._client)||void 0===v||null===(v=v.session)||void 0===v?void 0:v.sessionId,t=this._prop(P);e&&e!==t&&(f={},g=e)}if(!t.send_event&&"send_event"in t)g&&this._set({[x]:f,[P]:g});else{var m,y,b;const t=!(null===(m=this._client)||void 0===m?void 0:m.canCapture),i=!t&&!(null===(y=this._client)||void 0===y?void 0:y.isRateLimited);var S;if(i?this._flagCallsPendingCapture.delete(e):(t&&Object.keys(f).length>0&&(f={},this._set({[x]:f})),(null===(S=f[e])||void 0===S?void 0:S.includes(h))||this._holdFlagCall(e,h)),i&&!(null===(b=f[e])||void 0===b?void 0:b.includes(h))){var w,E,k,R,A,M,O,L,D,N,B,U,z;pt(f[e])?f[e].push(h):f[e]=[h],this._set(ls({[x]:f},g?{[P]:g}:{}));const t=this.getFeatureFlagDetails(e),i=[...null!==(w=this._prop("$feature_flag_errors"))&&void 0!==w?w:[]];mt(c)&&i.push((null==t?void 0:t.failed)?"evaluation_failed":"flag_missing");const s={$feature_flag:e,$feature_flag_response:c,$feature_flag_payload:null!=d?d:null,$feature_flag_request_id:_,$feature_flag_evaluated_at:p,$feature_flag_bootstrapped_response:null!==(E=null===(k=this._config.bootstrap)||void 0===k||null===(k=k.featureFlags)||void 0===k?void 0:k[e])&&void 0!==E?E:null,$feature_flag_bootstrapped_payload:null!==(R=null===(A=this._config.bootstrap)||void 0===A||null===(A=A.featureFlagPayloads)||void 0===A?void 0:A[e])&&void 0!==R?R:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};mt(null==t||null===(M=t.metadata)||void 0===M?void 0:M.has_experiment)||(s.$feature_flag_has_experiment=t.metadata.has_experiment),mt(null==t||null===(O=t.metadata)||void 0===O?void 0:O.version)||(s.$feature_flag_version=t.metadata.version);const n=null!==(L=null==t||null===(D=t.reason)||void 0===D?void 0:D.description)&&void 0!==L?L:null==t||null===(N=t.reason)||void 0===N?void 0:N.code;n&&(s.$feature_flag_reason=n),(null==t||null===(B=t.metadata)||void 0===B?void 0:B.id)&&(s.$feature_flag_id=t.metadata.id),mt(null==t?void 0:t.original_variant)&&mt(null==t?void 0:t.original_enabled)||(s.$feature_flag_original_response=mt(t.original_variant)?t.original_enabled:t.original_variant),(null==t||null===(U=t.metadata)||void 0===U?void 0:U.original_payload)&&(s.$feature_flag_original_payload=null==t||null===(z=t.metadata)||void 0===z?void 0:z.original_payload),i.length&&(s.$feature_flag_error=i.join(",")),this._captureFeatureFlagCalled(s)||(this._unmarkFlagCallReported(e,h),this._holdFlagCall(e,h))}else g&&this._set({[x]:f,[P]:g})}return l?{key:e,enabled:!!c,variant:"string"==typeof c?c:void 0,payload:en(d)}:void 0}_captureFeatureFlagCalled(e){try{var t;return!1!==(null===(t=this._client)||void 0===t?void 0:t.capture("$feature_flag_called",e))}catch(e){return this._logger.error("Failed to capture feature flag call",e),!0}}_holdFlagCall(e,t){this._flagCallsPendingCapture.set(e,{value:t,context:this._flagCallContext()})}_flagCallContext(){var e,t,i;return{distinctId:null===(e=this._client)||void 0===e?void 0:e.distinctId,groups:ls({},null===(t=this._client)||void 0===t?void 0:t.groups),sessionId:this._config.deduplicateCallsPerSession?null===(i=this._client)||void 0===i||null===(i=i.session)||void 0===i?void 0:i.sessionId:void 0}}_unmarkFlagCallReported(e,t){const i=this._prop("$flag_call_reported")||{},s=i[e];pt(s)&&s.includes(t)&&(i[e]=s.filter(e=>e!==t),this._set({[x]:i}))}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,t){var i=this;return Dt(function*(){const s=i._client;if(!s)return;const n={distinct_id:s.distinctId,token:s.projectToken,person_properties:{$lib:s.library.name,$lib_version:s.library.version}},r=i._getValidEvaluationEnvironments();r.length&&(n.evaluation_contexts=r);const o=i._getValidFlagKeys();let a;mt(o)||(n.flag_keys=o);try{var l;const t=null===(l=(yield s.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,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._flagsNotLoaded(e))return this._logger.warn('isFeatureEnabled for key "'+e+Ld),t.defaultValue;const i=this.getFeatureFlag(e,t);return mt(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;var s,n;this._hasLoadedFlags=!0,!1!==(null==i?void 0:i.persist)&&Hd(e,i)&&(null===(s=this._crossTabPersistence)||void 0===s||null===(n=s.reconcileFeatureFlagsBeforeMerge)||void 0===n?void 0:n.call(s))&&this._clearBootstrapState();const r=this.getFlagVariants(),o=!e.flags&&pt(e.featureFlags),a=((e,t={},i={},s={},n,r=Md)=>{const o=((e,t)=>{const i=e.flags;if(i){const t=Object.fromEntries(Object.keys(i).filter(e=>!i[e].failed).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].failed&&i[e].enabled).filter(e=>{var t;return!mt(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,r),a=o.flags,l=o.featureFlags,c=o.featureFlagPayloads;if(!l)return;const u=e.requestId,d=e.evaluatedAt;if(pt(l)){r.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const e={};if(l)for(let t=0;l.length>t;t++)e[l[t]]=!0;return{[v]:l,[C]:e,[m]:zd(s,l),[T]:Ud(i,s),[w]:!1}}let h=l,_=c,p=a;if(Hd(e,n)){const e=e=>({}.hasOwnProperty.call(t,e)&&!mt(t[e])),r=Object.keys(h),o=_||{};h=ls(ls({},t),h),_=ls(ls({},i),o),((null==n?void 0:n.partialResponse)||a)&&r.forEach(e=>{e in o||null==_||delete _[e]}),p=a?ls(ls({},s),Object.fromEntries(Object.entries(a).filter(([t,i])=>!i.failed||!e(t)))):zd(s,r)}return ls(ls({[v]:Object.keys(jd(h)),[C]:h||{},[T]:_||{},[m]:p||{},[w]:!0===e.minimalFlagCalledEvents},u?{[S]:u}:{}),d?{[b]:d}:{})})(e,r,o?this._prop("$feature_flag_payloads")||{}:this.getFlagPayloads(),o?this._prop("$feature_flag_details")||{}:this.getFlagsWithDetails(),i,this._logger);if(a)if(!1===(null==i?void 0:i.persist)){const e=!mt(this._client.kv.get(C));this._bootstrapState=a,e||this._set(a)}else this._clearBootstrapState(),this._markCrossTabFeatureFlagSnapshot(a,e,!!(null==i?void 0:i.partialResponse)),this._set(a);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([I,F]),this._fireFeatureFlagsCallbacks(),void Od.info("All overrides cleared");if(pt(e))return this._set({[I]:qd(e)}),this._fireFeatureFlagsCallbacks(),void Od.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={},n=i.flags,r=i.payloads;return n&&(s[I]=pt(n)?qd(n):n),r&&(s[F]=r),Object.keys(s).length&&this._set(s),!1===n&&!1===r?this._remove([I,F]):!1===n?this._remove(I):!1===r&&this._remove(F),this._fireFeatureFlagsCallbacks(),!1===n?Od.info("Flag overrides cleared"):n&&Od.info("Flag overrides set",{flags:n}),void(!1===r?Od.info("Payload overrides cleared"):r&&Od.info("Payload overrides set",{payloads:r}))}if(e&&"object"==typeof e)return this._set({[I]:e}),this._fireFeatureFlagsCallbacks(),void Od.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,n;const r=(this._prop("$early_access_features")||[]).find(t=>t.flagKey===e),o={[`$feature_enrollment/${e}`]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};r&&(a.$early_access_feature_name=r.name),i&&(a.$feature_enrollment_stage=i);const l=ls(ls({},this.getFlagVariants()),{},{[e]:t}),c=ls({},this._prop(m)),u=null===(s=c[e])||void 0===s?void 0:s.failed,d=ls({},this._prop(T));u&&(delete c[e],delete d[e]),null===(n=this._crossTabPersistence)||void 0===n||n.markCrossTabFeatureFlagChanges(ls(ls({$active_feature_flags:[e],$enabled_feature_flags:[e]},u?{$feature_flag_details:[e],$feature_flag_payloads:[e]}:{}),{},{$stored_person_properties:Object.keys(o)})),this._set(ls(ls({[v]:Object.keys(jd(l)),[C]:l},u?{[m]:c,[T]:d}:{}),{},{[k]:ls(ls({},this._prop("$stored_person_properties")||{}),o)})),this._fireFeatureFlagsCallbacks();try{var h;null===(h=this._client)||void 0===h||h.capture("$feature_enrollment_update",a)}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t=!1,i){const s=this._prop(f);!s||t?this._getEarlyAccessFeatures(e,i):e(s)}_getEarlyAccessFeatures(e,t){var i=this;return Dt(function*(){const s=i._client;if(!s)return;const n=t?`&${t.map(e=>`stage=${e}`).join("&")}`:"";let r;try{const e=yield s.sendRequest(`/api/early_access_features/?token=${s.projectToken}${n}`,{target:"api",method:"GET",sentAt:"query"});if(!e.json)return;r=e.json.earlyAccessFeatures,i._set({[f]:r})}catch(e){return void i._logger.error("Early access feature request failed",e)}try{e(r)}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(),s=this._firingFeatureFlagsCallbacks;this._firingFeatureFlagsCallbacks=!0,this.featureFlagEventHandlers.forEach(s=>{try{s(t,i,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}}),this._firingFeatureFlagsCallbacks=s}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),n=null==e?void 0:e.$set_once,r={};if(n)for(const e in n)({}).hasOwnProperty.call(n,e)&&(e in i||(r[e]=n[e]));this._set({[k]:ls(ls(ls({},i),r),s)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const i=ls({},this._prop("$stored_person_properties")||{});e.forEach(e=>{delete i[e]}),this._set({[k]:i}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this._remove(k),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({[E]:s}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this._prop("$stored_group_properties")||{};this._set({[E]:ls(ls({},t),{},{[e]:{}})})}else this._remove(E)}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,this._flagCallsPendingCapture=new Map}};const Gd=Or("[FeatureFlags]");var Kd=class{constructor(e,t=!1){this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,n,r,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!==(n=null===(r=e.bootstrap)||void 0===r?void 0:r.featureFlagPayloads)&&void 0!==n?n: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:mt(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:pt(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(Gd.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),mt(e.flag_keys)||pt(e.flag_keys)||Gd.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}};const Yd=e=>Ft(e)&&("RangeError"===e.name&&0===e.message.indexOf("Maximum call stack size exceeded")||"InternalError"===e.name&&"too much recursion"===e.message),Qd=Or("[Error tracking]"),Jd="webkit-masked-url:",Zd=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],Xd=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",Jd],eh=["__firefox__","__gCrWeb"];function th(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=Array(t);t>i;i++)s[i]=e[i];return s}function ih(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var s,n,r,o,a=[],l=!0,c=!1;try{if(r=(i=i.call(e)).next,0===t);else for(;!(l=(s=r.call(i)).done)&&(a.push(s.value),a.length!==t);l=!0);}catch(e){c=!0,n=e}finally{try{if(!l&&null!=i.return&&(o=i.return(),Object(o)!==o))return}finally{if(c)throw n}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return th(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?th(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}const sh=Object.entries,nh=Object.setPrototypeOf,rh=Object.isFrozen,oh=Object.getPrototypeOf,ah=Object.getOwnPropertyDescriptor;let lh=Object.freeze,ch=Object.seal,uh=Object.create,dh="undefined"!=typeof Reflect&&Reflect,hh=dh.apply,_h=dh.construct;lh||(lh=function(e){return e}),ch||(ch=function(e){return e}),hh||(hh=function(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),n=2;i>n;n++)s[n-2]=arguments[n];return e.apply(t,s)}),_h||(_h=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];return new e(...i)});const ph=Oh([].forEach),gh=Oh([].lastIndexOf),fh=Oh([].pop),vh=Oh([].push),mh=Oh([].splice),yh=Array.isArray,bh=Oh("".toLowerCase),Sh=Oh("".toString),wh=Oh("".match),Ch=Oh("".replace),Eh=Oh("".indexOf),kh=Oh("".trim),xh=Oh((0).toString),Ph=Oh(Boolean.prototype.toString),Th="undefined"==typeof BigInt?null:Oh(BigInt.prototype.toString),Ih="undefined"==typeof Symbol?null:Oh(Symbol.prototype.toString),Fh=Oh({}.hasOwnProperty),Rh=Oh({}.toString),Ah=Oh(/t/.test),$h=(Mh=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];return _h(Mh,t)});var Mh;function Oh(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var i=arguments.length,s=new Array(i>1?i-1:0),n=1;i>n;n++)s[n-1]=arguments[n];return hh(e,t,s)}}function Lh(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:bh;if(nh&&nh(e,null),!yh(t))return e;let s=t.length;for(;s--;){let n=t[s];if("string"==typeof n){const e=i(n);e!==n&&(rh(t)||(t[s]=e),n=e)}e[n]=!0}return e}function Dh(e){for(let t=0;e.length>t;t++)Fh(e,t)||(e[t]=null);return e}function Nh(e){const t=uh(null);for(const s of sh(e)){var i=ih(s,2);const n=i[0],r=i[1];Fh(e,n)&&(t[n]=yh(r)?Dh(r):r&&"object"==typeof r&&r.constructor===Object?Nh(r):r)}return t}function Bh(e,t){for(;null!==e;){const i=ah(e,t);if(i){if(i.get)return Oh(i.get);if("function"==typeof i.value)return Oh(i.value)}e=oh(e)}return function(){return null}}const Uh=lh(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),zh=lh(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Hh=lh(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),qh=lh(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),jh=lh(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Wh=lh(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Vh=lh(["#text"]),Gh=lh(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Kh=lh(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Yh=lh(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Qh=lh(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Jh=ch(/{{[\w\W]*|^[\w\W]*}}/g),Zh=ch(/<%[\w\W]*|^[\w\W]*%>/g),Xh=ch(/\${[\w\W]*/g),e_=ch(/^data-[\-\w.\u00B7-\uFFFF]+$/),t_=ch(/^aria-[\-\w]+$/),i_=ch(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),s_=ch(/^(?:\w+script|data):/i),n_=ch(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),r_=ch(/^html$/i),o_=ch(/^[a-z][.\w]*(-[.\w]+)+$/i),a_=ch(/<[/\w!]/g),l_=ch(/<[/\w]/g),c_=ch(/<\/no(script|embed|frames)/i),u_=ch(/\/>/i),d_=function(){return"undefined"==typeof window?null:window},h_=function(e,t,i,s){return Fh(e,t)&&yh(e[t])?Lh(s.base?Nh(s.base):{},e[t],s.transform):i};var __=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d_();const i=t=>e(t);if(i.version="3.4.13",i.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return i.isSupported=!1,i;let s=t.document;const n=s,r=n.currentScript,o=t.HTMLTemplateElement,a=t.Node,l=t.NodeFilter,c=t.DOMParser,u=t.trustedTypes,d=t.Element.prototype,h=Bh(d,"cloneNode"),_=Bh(d,"remove"),p=Bh(d,"nextSibling"),g=Bh(d,"childNodes"),f=Bh(d,"parentNode"),v=Bh(d,"shadowRoot"),m=Bh(d,"attributes"),y=a&&a.prototype?Bh(a.prototype,"nodeType"):null,b=a&&a.prototype?Bh(a.prototype,"nodeName"):null,S=a&&a.prototype?Bh(a.prototype,"ownerDocument"):null;if("function"==typeof o){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let w,C,E="",k=!1,x=0;const P=function(){if(x>0)throw $h('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},T=function(e){P(),x++;try{return w.createHTML(e)}finally{x--}},I=s.implementation,F=s.createNodeIterator,R=s.createDocumentFragment,A=s.getElementsByTagName,M=n.importNode;let O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"==typeof sh&&"function"==typeof f&&I&&void 0!==I.createHTMLDocument;const L=Jh,D=Zh,N=Xh,B=e_,U=t_,z=s_,H=n_,q=o_;let j=i_,W=null;const V=Lh({},[...Uh,...zh,...Hh,...jh,...Vh]);let G=null;const K=Lh({},[...Gh,...Kh,...Yh,...Qh]);let Y=Object.seal(uh(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Q=null,J=null;const Z=Object.seal(uh(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let X=!0,ee=!0,te=!1,ie=!0,se=!1,ne=!0,re=!1,oe=!1,ae=null,le=null,ce=!1,ue=!1,de=!1,he=!1,_e=!0,pe=!1;const ge="user-content-";let fe=!0,ve=!1,me={},ye=null;const be=Lh({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Se=null;const we=Lh({},["audio","video","img","source","image","track"]);let Ce=null;const Ee=Lh({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ke="http://www.w3.org/1998/Math/MathML",xe="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Te=Pe,Ie=!1,Fe=null;const Re=Lh({},[ke,xe,Pe],Sh),Ae=lh(["mi","mo","mn","ms","mtext"]);let $e=Lh({},Ae);const Me=lh(["annotation-xml"]);let Oe=Lh({},Me);const Le=Lh({},["title","style","font","a","script"]);let De=null;const Ne=["application/xhtml+xml","text/html"];let Be=null,Ue=null;const ze=s.createElement("form"),He=function(e){return e instanceof RegExp||e instanceof Function},qe=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Ue&&Ue===e)return;e&&"object"==typeof e||(e={}),e=Nh(e),De=-1===Ne.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Be="application/xhtml+xml"===De?Sh:bh,W=h_(e,"ALLOWED_TAGS",V,{transform:Be}),G=h_(e,"ALLOWED_ATTR",K,{transform:Be}),Fe=h_(e,"ALLOWED_NAMESPACES",Re,{transform:Sh}),Ce=h_(e,"ADD_URI_SAFE_ATTR",Ee,{transform:Be,base:Ee}),Se=h_(e,"ADD_DATA_URI_TAGS",we,{transform:Be,base:we}),ye=h_(e,"FORBID_CONTENTS",be,{transform:Be}),Q=h_(e,"FORBID_TAGS",Nh({}),{transform:Be}),J=h_(e,"FORBID_ATTR",Nh({}),{transform:Be}),me=!!Fh(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Nh(e.USE_PROFILES):e.USE_PROFILES),X=!1!==e.ALLOW_ARIA_ATTR,ee=!1!==e.ALLOW_DATA_ATTR,te=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ie=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,se=e.SAFE_FOR_TEMPLATES||!1,ne=!1!==e.SAFE_FOR_XML,re=e.WHOLE_DOCUMENT||!1,ue=e.RETURN_DOM||!1,de=e.RETURN_DOM_FRAGMENT||!1,he=e.RETURN_TRUSTED_TYPE||!1,ce=e.FORCE_BODY||!1,_e=!1!==e.SANITIZE_DOM,pe=e.SANITIZE_NAMED_PROPS||!1,fe=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,j=function(e){try{return Ah(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:i_,Te="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,$e=Fh(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Nh(e.MATHML_TEXT_INTEGRATION_POINTS):Lh({},Ae),Oe=Fh(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Nh(e.HTML_INTEGRATION_POINTS):Lh({},Me);const t=Fh(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Nh(e.CUSTOM_ELEMENT_HANDLING):uh(null);if(Y=uh(null),Fh(t,"tagNameCheck")&&He(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Fh(t,"attributeNameCheck")&&He(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Fh(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),ch(Y),se&&(ee=!1),de&&(ue=!0),me&&(W=Lh({},Vh),G=uh(null),!0===me.html&&(Lh(W,Uh),Lh(G,Gh)),!0===me.svg&&(Lh(W,zh),Lh(G,Kh),Lh(G,Qh)),!0===me.svgFilters&&(Lh(W,Hh),Lh(G,Kh),Lh(G,Qh)),!0===me.mathMl&&(Lh(W,jh),Lh(G,Yh),Lh(G,Qh))),Z.tagCheck=null,Z.attributeCheck=null,Fh(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Z.tagCheck=e.ADD_TAGS:yh(e.ADD_TAGS)&&(W===V&&(W=Nh(W)),Lh(W,e.ADD_TAGS,Be))),Fh(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Z.attributeCheck=e.ADD_ATTR:yh(e.ADD_ATTR)&&(G===K&&(G=Nh(G)),Lh(G,e.ADD_ATTR,Be))),Fh(e,"ADD_URI_SAFE_ATTR")&&yh(e.ADD_URI_SAFE_ATTR)&&Lh(Ce,e.ADD_URI_SAFE_ATTR,Be),Fh(e,"FORBID_CONTENTS")&&yh(e.FORBID_CONTENTS)&&(ye===be&&(ye=Nh(ye)),Lh(ye,e.FORBID_CONTENTS,Be)),Fh(e,"ADD_FORBID_CONTENTS")&&yh(e.ADD_FORBID_CONTENTS)&&(ye===be&&(ye=Nh(ye)),Lh(ye,e.ADD_FORBID_CONTENTS,Be)),fe&&(W["#text"]=!0),re&&Lh(W,["html","head","body"]),W.table&&(Lh(W,["tbody"]),delete Q.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw $h('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw $h('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=w;w=e.TRUSTED_TYPES_POLICY;try{E=T("")}catch(e){throw w=t,e}}else null===e.TRUSTED_TYPES_POLICY?(w=void 0,E=""):(void 0===w&&(k||(C=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let i=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(i=t.getAttribute(s));const n="dompurify"+(i?"#"+i:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(u,r),k=!0),w=C),w&&"string"==typeof E&&(E=T("")));lh&&lh(e),Ue=e},je=Lh({},[...zh,...Hh,...qh]),We=Lh({},[...jh,...Wh]),Ve=function(e){vh(i.removed,{element:e});try{f(e).removeChild(e)}catch(t){if(_(e),!f(e))throw $h("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Qe(e);const t=g(e);if(t){const e=[];ph(t,t=>{vh(e,t)}),ph(e,e=>{try{_(e)}catch(e){}})}const i=m(e);if(i)for(let t=i.length-1;t>=0;--t){const s=i[t],n=s&&s.name;if("string"==typeof n)try{e.removeAttribute(n)}catch(e){}}},Ke=function(e,t){try{vh(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vh(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ue||de)try{Ve(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=m(e);if(t)for(let i=t.length-1;i>=0;--i){const s=t[i],n=s&&s.name;if("string"==typeof n&&!G[Be(n)])try{e.removeAttribute(n)}catch(e){}}},Qe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(y?y(e):e.nodeType)&&Ye(e);const i=g(e);if(i)for(let e=i.length-1;e>=0;--e)t.push(i[e])}},Je=function(e){let t=null,i=null;if(ce)e="<remove></remove>"+e;else{const t=wh(e,/^[\r\n\t ]+/);i=t&&t[0]}"application/xhtml+xml"===De&&Te===Pe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const n=w?T(e):e;if(Te===Pe)try{t=(new c).parseFromString(n,De)}catch(e){}if(!t||!t.documentElement){t=I.createDocument(Te,"template",null);try{t.documentElement.innerHTML=Ie?E:n}catch(e){}}const r=t.body||t.documentElement;return e&&i&&r.insertBefore(s.createTextNode(i),r.childNodes[0]||null),Te===Pe?A.call(t,re?"html":"body")[0]:re?t.documentElement:r},Ze=function(e){const t=S?S(e):e.ownerDocument;return F.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Xe=function(e){return e=Ch(e,L," "),e=Ch(e,D," "),Ch(e,N," ")},et=function(e){var t;e.normalize();const i=S?S(e):e.ownerDocument,s=F.call(i||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let n=s.nextNode();for(;n;)n.data=Xe(n.data),n=s.nextNode();const r=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");r&&ph(r,e=>{it(e.content)&&et(e.content)})},tt=function(e){const t=b?b(e):null;return"string"==typeof t&&"form"===Be(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==m(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==y(e)||e.childNodes!==g(e))},it=function(e){if(!y||"object"!=typeof e||null===e)return!1;try{return 11===y(e)}catch(e){return!1}},st=function(e){if(!y||"object"!=typeof e||null===e)return!1;try{return"number"==typeof y(e)}catch(e){return!1}};function nt(e,t,s){0!==e.length&&ph(e,e=>{e.call(i,t,s,Ue)})}const rt=function(e,t,i,s){return 0===e.length?t:t===i||t===s?Nh(t):t},ot=function(e,t){if(nt(O.beforeSanitizeElements,e,null),e!==t&&null===f(e))return ve&&Qe(e),!0;if(tt(e))return Ve(e),!0;const s=Be(b?b(e):e.nodeName);if(W=rt(O.uponSanitizeElement,W,V,ae),nt(O.uponSanitizeElement,e,{tagName:s,allowedTags:W}),e!==t&&null===f(e))return ve&&Qe(e),!0;if(function(e,t){return!!(ne&&e.hasChildNodes()&&!st(e.firstElementChild)&&Ah(a_,e.textContent)&&Ah(a_,e.innerHTML))||!(!ne||e.namespaceURI!==Pe||"style"!==t||!st(e.firstElementChild))||7===e.nodeType||!(!ne||8!==e.nodeType||!Ah(l_,e.data))}(e,s))return Ve(e),!0;if(Q[s]||!(Z.tagCheck instanceof Function&&Z.tagCheck(s))&&!W[s]){const i=function(e,t,i){if(!Q[t]&&ct(t)){if(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(fe&&!ye[t]){const t=f(e),s=g(e);if(s&&t)for(let n=s.length-1;n>=0;--n){const r=e===i?h(s[n],!0):s[n];t.insertBefore(r,p(e))}}return Ve(e),!0}(e,s,t);return!1===i&&nt(O.afterSanitizeElements,e,null),i}if(1===(y?y(e):e.nodeType)&&!function(e){let t=f(e);t&&t.tagName||(t={namespaceURI:Te,tagName:"template"});const i=bh(e.tagName),s=bh(t.tagName);return!!Fe[e.namespaceURI]&&(e.namespaceURI===xe?function(e,t,i){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===ke?"svg"===e&&("annotation-xml"===i||$e[i]):Boolean(je[e])}(i,t,s):e.namespaceURI===ke?function(e,t,i){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===xe?"math"===e&&Oe[i]:Boolean(We[e])}(i,t,s):e.namespaceURI===Pe?function(e,t,i){return!(t.namespaceURI===xe&&!Oe[i])&&!(t.namespaceURI===ke&&!$e[i])&&!We[e]&&(Le[e]||!je[e])}(i,t,s):!("application/xhtml+xml"!==De||!Fe[e.namespaceURI]))}(e))return Ve(e),!0;if(("noscript"===s||"noembed"===s||"noframes"===s)&&Ah(c_,e.innerHTML))return Ve(e),!0;if(se&&3===e.nodeType){const t=Xe(e.textContent);e.textContent!==t&&(vh(i.removed,{element:e.cloneNode()}),e.textContent=t)}return nt(O.afterSanitizeElements,e,null),!1},at=function(e,t,i){if(J[t])return!1;if(ne&&"patchsrc"===t)return!1;if(ne&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(_e&&("id"===t||"name"===t)&&(i in s||i in ze))return!1;const n=G[t]||Z.attributeCheck instanceof Function&&Z.attributeCheck(t,e);if(ee&&Ah(B,t));else if(X&&Ah(U,t));else if(n){if(Ce[t]);else if(Ah(j,Ch(i,H,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Eh(i,"data:")||!Se[e])if(te&&!Ah(z,Ch(i,H,"")));else if(i)return!1}else if(!(ct(e)&&(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Ah(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,i)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(i))))return!1;return!0},lt=Lh({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ct=function(e){return!lt[bh(e)]&&Ah(q,e)},ut=function(e,t,i,s){if(w&&"object"==typeof u&&"function"==typeof u.getAttributeType&&!i)switch(u.getAttributeType(e,t)){case"TrustedHTML":return T(s);case"TrustedScriptURL":return function(e){P(),x++;try{return w.createScriptURL(e)}finally{x--}}(s)}return s},dt=function(e,t,s,n){try{s?e.setAttributeNS(s,t,n):e.setAttribute(t,n),tt(e)?Ve(e):fh(i.removed)}catch(i){Ke(t,e)}},ht=function(e){nt(O.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||tt(e))return;G=rt(O.uponSanitizeAttribute,G,K,le);const i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let s=t.length;const n=Be(e.nodeName);for(;s--;){const r=t[s],o=r.name,a=r.namespaceURI,l=r.value,c=Be(o),u=l;let d="value"===o?u:kh(u);i.attrName=c,i.attrValue=d,i.keepAttr=!0,i.forceKeepAttr=void 0,nt(O.uponSanitizeAttribute,e,i),d=i.attrValue,!pe||"id"!==c&&"name"!==c||0===Eh(d,ge)||(Ke(o,e),d=ge+d),ne&&Ah(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)||"attributename"===c&&wh(d,"href")?Ke(o,e):i.forceKeepAttr||(!i.keepAttr||!ie&&Ah(u_,d)?Ke(o,e):(se&&(d=Xe(d)),at(n,c,d)?(d=ut(n,c,a,d),d!==u&&dt(e,o,a,d)):Ke(o,e)))}nt(O.afterSanitizeAttributes,e,null)},_t=function(e){let t=null;const i=Ze(e);for(nt(O.beforeSanitizeShadowDOM,e,null);t=i.nextNode();)if(nt(O.uponSanitizeShadowNode,t,null),ot(t,e),ht(t),it(t.content)&&_t(t.content),1===(y?y(t):t.nodeType)){const e=v(t);it(e)&&(pt(e),_t(e))}nt(O.afterSanitizeShadowDOM,e,null)},pt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){_t(e.shadow);continue}const i=e.node,s=1===(y?y(i):i.nodeType),n=g(i);if(n)for(let e=n.length-1;e>=0;--e)t.push({node:n[e],shadow:null});if(s){const e=b?b(i):null;if("string"==typeof e&&"template"===Be(e)){const e=i.content;it(e)&&t.push({node:e,shadow:null})}}if(s){const e=v(i);it(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,r=null,o=null,a=null;if(Ie=!e,Ie&&(e="\x3c!--\x3e"),"string"!=typeof e&&!st(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return xh(e);case"boolean":return Ph(e);case"bigint":return Th?Th(e):"0";case"symbol":return Ih?Ih(e):"Symbol()";case"undefined":default:return Rh(e);case"function":case"object":{if(null===e)return Rh(e);const t=e,i=Bh(t,"toString");if("function"==typeof i){const e=i(t);return"string"==typeof e?e:Rh(e)}return Rh(e)}}}(e)))throw $h("dirty is not a string, aborting");if(!i.isSupported)return e;oe?(W=ae,G=le):qe(t),(O.uponSanitizeElement.length>0||O.uponSanitizeAttribute.length>0)&&(W=Nh(W)),O.uponSanitizeAttribute.length>0&&(G=Nh(G)),i.removed=[];const l=ve&&"string"!=typeof e&&st(e);if(l){!function(e){if(!ne)return;const t=[e];for(;t.length>0;){const e=t.pop(),i=y?y(e):e.nodeType;if(7===i||8===i&&Ah(l_,e.data)){try{_(e)}catch(e){}continue}if(1===i){const t=e,i=Be(b?b(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==i&&"output"!==i&&t.removeAttribute("for")}catch(e){}}const s=g(e);if(s)for(let e=s.length-1;e>=0;--e)t.push(s[e])}}(e);const t=b?b(e):e.nodeName;if("string"==typeof t){const i=Be(t);if(!W[i]||Q[i])throw Ge(e),$h("root node is forbidden and cannot be sanitized in-place")}if(tt(e))throw Ge(e),$h("root node is clobbered and cannot be sanitized in-place");try{pt(e)}catch(t){throw Ge(e),t}}else if(st(e))s=Je("\x3c!----\x3e"),r=s.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?s=r:s.appendChild(r),pt(r);else{if(!ue&&!se&&!re&&-1===e.indexOf("<"))return w&&he?T(e):e;if(s=Je(e),!s)return ue?null:he?E:""}s&&ce&&Ve(s.firstChild);const c=l?e:s;try{const e=Ze(c);for(;o=e.nextNode();)ot(o,c),ht(o),it(o.content)&&_t(o.content)}catch(t){throw l&&(Ge(e),ph(i.removed,e=>{e.element&&Qe(e.element)})),t}if(l)return ph(i.removed,e=>{e.element&&Qe(e.element)}),se&&et(e),e;if(ue){if(se&&et(s),de)for(a=R.call(s.ownerDocument);s.firstChild;)a.appendChild(s.firstChild);else a=s;return(G.shadowroot||G.shadowrootmode)&&(a=M.call(n,a,!0)),a}let u=re?s.outerHTML:s.innerHTML;return re&&W["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&Ah(r_,s.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+u),se&&(u=Xe(u)),w&&he?T(u):u},i.setConfig=function(){qe(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),oe=!0,ae=W,le=G},i.clearConfig=function(){Ue=null,oe=!1,ae=null,le=null,w=C,E=""},i.isValidAttribute=function(e,t,i){Ue||qe({});const s=Be(e),n=Be(t);return at(s,n,i)},i.addHook=function(e,t){"function"==typeof t&&Fh(O,e)&&vh(O[e],t)},i.removeHook=function(e,t){if(Fh(O,e)){if(void 0!==t){const i=gh(O[e],t);return-1===i?void 0:mh(O[e],i,1)[0]}return fh(O[e])}},i.removeHooks=function(e){Fh(O,e)&&(O[e]=[])},i.removeAllHooks=function(){O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}();const p_="Refusing to render web experiment since the viewer is a likely bot",g_={ADD_ATTR:(e,t)=>"target"===e&&"a"===t||"form"===e&&/^(button|fieldset|input|output|select|textarea)$/.test(t),ADD_URI_SAFE_ATTR:["form"]};let f_;const v_={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Kc(t,e),not_regex:(e,t)=>!Kc(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},m_=Or("[Conversations]"),y_="Conversations not available yet.";function b_(e,t){var i,s,n,r,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!==(n=null==e?void 0:e.maxLogsPerInterval)&&void 0!==n?n:1e3,h=mt(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,n=null==s||null===(i=s.navigator)||void 0===i?void 0:i.userAgent;n&&([e,t]=Ui(n))}catch(e){}return function(e,t){const i=function(e){if(e)return{}.hasOwnProperty.call(dr,e)?dr[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!==(r=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==r?r: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 S_=["debug","log","warn","error","info"],w_=e=>{for(;null==e?void 0:e.__rrweb_original__;)e=e.__rrweb_original__;return e},C_="console",E_="__posthogHandledLogsRequestError",k_=(e,t)=>{const i=e instanceof Error?e:new Error(t);return i[E_]=!0,i},x_=e=>!!e&&"object"==typeof e&&!0===e[E_];var P_=class{get _coreLogger(){return ls(ls({},this._logger),{},{error:(...e)=>{e.some(x_)||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=Or("[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&&(Wr(this._window,"online",this._onReconnect),this._listeningForReconnect=!0)}}_buildCore(e,t,i,s){this._listenForReconnect();const n=b_(this._configSource.get(),i);return[new Sr(this._createHost(e,t),n,this._coreLogger,()=>this._getSdkContext(),e=>e(),void 0,s),n]}_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},C_)),this._consoleCore}setup(e){if(!this._disposed&&!this._setupStarted)return this._setupStarted=!0,this._client=e,this._logger=e.logger.createLogger("[logs]"),xd(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,n,r,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===(n=this._consoleCore)||void 0===n||n.clearQueue(),null===(r=this._core)||void 0===r||r.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;wt(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=b_(this._configSource.get()).maxBufferSize;let i=!0;this._consoleRecorderUnpatchers.push(()=>{i=!1});for(const e of S_){let s;try{s=w_(this._window.console[e])}catch(e){continue}s&&this._consoleRecorderUnpatchers.push(sd(this._window.console,e,n=>{const r=(...s)=>{try{i&&this._recordConsoleEntry(e,s,t)}catch(e){}return n.apply(this._window.console,s)};return r.__rrweb_original__=s,r}))}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 Dt(function*(){var t,i;const s=null===(t=e._core)||void 0===t?void 0:t.flush().catch(t=>e._logFlushError(t)),n=null===(i=e._consoleCore)||void 0===i?void 0:i.flush().catch(t=>e._logFlushError(t));yield s,yield n})()}_logFlushError(e){x_(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===st.LogsQueue?e():void 0,setPersistedProperty(e,i){e===st.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(Aa(this._consecutiveStatusZeroFailures,3))return void t({kind:"fatal",error:k_(void 0,"logs endpoint is unreachable, dropping batch")});let i=!1;const s=e=>{i||(i=!0,clearTimeout(n),t(e))},n=setTimeout(()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:k_(void 0,"logs request timed out")})},9e4),r=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,r),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:k_(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=$a(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,C_,e=>{this._consoleQueue=e})}_drainQueueViaTransport(e,t,i,s,n){if(0===t.length)return;const r=t.map(e=>e.record);n([]);const o=vr(r,fr(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 T_=Or("[NetworkMetrics]"),I_={"http:":80,"https:":443},F_=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),R_=e=>yt(e)&&0===e.toLowerCase().indexOf("text/event-stream"),A_=e=>{try{return e()}catch(e){return}},$_=(e,t)=>{var i;const s=String(t);return{method:String(e).toUpperCase(),url:(null===(i=Fa(s))||void 0===i?void 0:i.href)||s}},M_=(e,t,i,s,n,r,o=!1)=>{try{var a,l;const c=n();if(!c)return;const u=i||void 0,d=Eu()-s,h=Fa(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=gt(c.name)?c.name(_):yt(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,r),f=ls(ls(ls(ls(ls({},(e=>{const t=F_.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)||I_[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:f})}catch(e){T_.error("Failed to record network metric",e)}},O_=()=>{},L_=(e,t)=>gt(null==s?void 0:s.fetch)?sd(s,"fetch",i=>function(...s){const n=Eu(),r=i.apply(this,s);if(!t())return r;try{var o,a,l;const[i,c]=s,u=$_(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 r.then(i=>(R_(A_(()=>{var e;return null==i||null===(e=i.headers)||void 0===e?void 0:e.get("content-type")}))||M_(e,u,null==i?void 0:i.status,n,t,void 0,!0),i),i=>{throw M_(e,u,void 0,n,t,i),i})}catch(e){return T_.error("Failed to observe fetch",e),r}}):O_,D_=(e,t)=>{var i;const n=null==s||null===(i=s.XMLHttpRequest)||void 0===i?void 0:i.prototype;if(!n)return O_;const r=new WeakMap,o=sd(n,"open",e=>function(...t){try{(()=>hc.has(this))()||r.set(this,$_(t[0],t[1]))}catch(e){T_.error("Failed to observe XHR open",e)}return e.apply(this,t)}),a=sd(n,"send",i=>function(...s){let n,o;try{const i=r.get(this);if(i&&t()){const s=Eu(),r=()=>R_(A_(()=>this.getResponseHeader("content-type")));let a=!1;o=()=>{2===this.readyState&&(a=r())},n=()=>{this.removeEventListener("loadend",n),this.removeEventListener("readystatechange",o),a||r()||M_(e,i,this.status,s,t)},Wr(this,"readystatechange",o),Wr(this,"loadend",n)}}catch(e){T_.error("Failed to observe XHR send",e)}try{return i.apply(this,s)}catch(e){throw n&&this.removeEventListener("loadend",n),o&&this.removeEventListener("readystatechange",o),e}});return()=>{o(),a()}},N_=new WeakMap,B_=new Set(["$comment","$defs","$id","$schema","additionalProperties","default","definitions","deprecated","description","examples","minProperties","properties","readOnly","required","title","type","writeOnly"]),U_={maxStringLength:2048,truncationSuffix:"..."},z_={maxStringLength:2048,truncationSuffix:"..."};function H_(e){if(e)return!0===e?{intent:!0,model:!0}:{intent:!1!==e.intent,model:!1!==e.model}}function q_(e,t){return{}.hasOwnProperty.call(e,t)}function j_(e,t){const i=Object.create(e);return t&&Object.defineProperty(i,"inputSchema",{configurable:!0,enumerable:!0,writable:!0,value:t}),i}function W_(e,t,i=!1){if(!yt(e))return;const s=e.trim();return s?(i?Qn(s,U_):s).slice(0,t):void 0}function V_(e){try{return ft(e)&&!0===e.isError}catch(e){return!1}}function G_(e){return Qn(e||"Unknown error",z_).slice(0,2048)}function K_(e,t){try{return G_(t?function(e){try{if(!ft(e)||!pt(e.content))return;return e.content.filter(e=>ft(e)&&"text"===e.type&&yt(e.text)).map(e=>e.text).join(" ").trim()||void 0}catch(e){return}}(e):ft(e)&&yt(e.message)?e.message:yt(e)?e:String(e))}catch(e){return"Unknown error"}}function Y_(e,t,i){return t.errorResult?[{type:"Error",value:i,mechanism:{type:"generic",handled:!0,synthetic:!0,exception_id:0}}]:e.buildProperties(t.error,{handled:!0}).$exception_list.map(e=>ls(ls({},e),{},{value:G_(e.value)}))}function Q_(e,t){if(t)return"Error";try{if(!ft(e))return"Error";let t=yt(e.name)?e.name.trim():"";const i=e.constructor;return t&&"Error"!==t||!gt(i)||"Error"===i.name||(t=i.name),(t||"Error").slice(0,256)}catch(e){return"Error"}}function J_(e,t){return{message:K_(e,t),type:Q_(e,t)}}Ju.__defaultExtensionClasses=ls({},{featureFlags:class extends Vd{constructor(e){const t=new Kd(e.config,e._shouldDisableFlags());super(t),this.name=wu,this._instance=e,this._mutableConfigSource=t}get _crossTabPersistence(){return this._instance.persistence}updateConfig(e,t){this._mutableConfigSource.update(e,t),this._onConfigUpdated()}},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=ud,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._selectMaskingFn=void 0,this._documentWasEverVisible=(()=>{var e,t;if(!(null==o?void 0:o.visibilityState)||"visible"===o.visibilityState)return!0;const i=null==s||null===(e=s.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==o?void 0:o.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 _d.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"');const t=this._instance.get_property(pe);var i;yt(t)&&"!"===t[0]&&(null===(i=this._persistence)||void 0===i||i.unregister("$session_is_sampled")),(null==o?void 0:o.addEventListener)&&Wr(o,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this._sessionRecordingDisposed=!0,null==o||null===(t=o.removeEventListener)||void 0===t||t.call(o,"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,n=this._config.disable_session_recording||this._instance.consent.isOptedOut();return s&&t&&i&&!n}startIfEnabledOrStop(e){if(this._sessionRecordingDisposed)return;var t;if(this._lazyLoadedSessionRecording)if(this._selectMaskingFn!==(null===(t=this._config.session_recording)||void 0===t?void 0:t.selectMaskingFn))wo._remove(hd(this._config)),this._lazyLoadedSessionRecording.discard({discardProducerEvents:!0}),this._selectMaskingFn=void 0;else if(this._lazyLoadedSessionRecording.isStarted&&this._isRecordingEnabled)return void(this._checkSelectMaskingSupport()||this._discardRecording(!0));const i=!mt(Object.assign)&&!mt(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),_d.info("starting")):(this._recordingStatus=ud,this.stopRecording())}_lazyLoadAndStart(e){var t,i;if(this._isRecordingEnabled)if("awaiting_config"!==this._recordingStatus&&"missing_config"!==this._recordingStatus&&(this._recordingStatus=dd),(null==p||null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t?void 0:t.record)&&(null===(i=p.__PosthogExtensions__)||void 0===i?void 0:i.initSessionRecording))this._onScriptLoaded(e);else{var s;const t=this._instance.sessionManager;null===(s=g(this._instance))||void 0===s||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}),_d.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,s;e&&(this._selectMaskingFn||(null===(t=this._config.session_recording)||void 0===t?void 0:t.selectMaskingFn))&&wo._remove(hd(this._config)),null===(i=this._persistFlagsOnSessionListener)||void 0===i||i.call(this),this._persistFlagsOnSessionListener=void 0,null===(s=this._lazyLoadedSessionRecording)||void 0===s||s.discard({discardProducerEvents:e}),this._selectMaskingFn=void 0}_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(wt(e))return null;const i=Ct(e)?e:parseFloat(e);return"number"!=typeof(s=i)||!Number.isFinite(s)||0>s||s>1?(_d.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,n=()=>{var t;const i=!1===e.sessionRecording?void 0:e.sessionRecording,n=this._validateSampleRate(null===(t=this._config.session_recording)||void 0===t?void 0:t.sampleRate,"session_recording.sampleRate"),r=this._validateSampleRate(null==i?void 0:i.sampleRate,"remote config sampleRate"),o=null!=n?n:r;wt(o)&&this._resetSampling();const a=null==i?void 0:i.minimumDurationMilliseconds;s.register({[oe]: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:mt(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})})};n(),null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=null===(i=this._instance.sessionManager)||void 0===i?void 0:i.onSessionId(n)}}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({[Ue]:!0}),_d.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):_d.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(oe);return(null==i||null===(t=i.scriptConfig)||void 0===t?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){const e=this._instance.get_property(oe);if(!e)return!1;let t;try{t="object"==typeof e?e:JSON.parse(e)}catch(e){return _d.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!wt(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}_checkSelectMaskingSupport(){var e,t,i;return!(null===(e=this._config.session_recording)||void 0===e?void 0:e.selectMaskingFn)||!(!0!==(null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t||null===(t=t.record)||void 0===t?void 0:t.supportsSelectMasking)||!0!==(null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.initSessionRecording)||void 0===i?void 0:i.supportsSelectMasking)||this._lazyLoadedSessionRecording&&!0!==this._lazyLoadedSessionRecording.supportsSelectMasking)||(this._recordingStatus=ud,_d.error("Session recording has not started: the recorder does not support selectMaskingFn."),!1)}_onScriptLoaded(e){var t,i,s,n,r,o;if(this._sessionRecordingDisposed||!this._isRecordingEnabled||!this._instance.sessionManager)return void(this._recordingStatus=ud);if(!(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.initSessionRecording))return _d.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Be]:!0});if(!this._checkSelectMaskingSupport())return;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null===(o=p.__PosthogExtensions__)||void 0===o?void 0:o.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._checkSelectMaskingSupport())return void this._discardRecording(!0);if(!this._isRemoteConfigFresh()){if("missing_config"===this._recordingStatus||"awaiting_config"===this._recordingStatus)return;return this._recordingStatus="awaiting_config",_d.info("persisted remote config is stale, requesting fresh config before starting"),void new Fl(this._instance).load()}this._recordingStatus=dd,null===(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||void 0===i||i.call(s,this._documentWasEverVisible);const a=null===(n=this._config.session_recording)||void 0===n?void 0:n.selectMaskingFn;this._lazyLoadedSessionRecording.start(e),this._selectMaskingFn=a,this._lazyLoadedSessionRecording.isStarted&&a!==(null===(r=this._config.session_recording)||void 0===r?void 0:r.selectMaskingFn)&&this.startIfEnabledOrStop()}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 pd){var i;const s=null===(i=this._instance.sessionPersistence)||void 0===i?void 0:i.get_property(e);mt(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)}},autocapture:class extends Su{constructor(e){super(new Xu(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&&(Mr.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,Mr.info("History API monitoring stopped")}monitorHistoryChanges(){s&&s.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(!s||(null===(t=s.history[e])||void 0===t?void 0:t.__posthog_wrapped__))return;const i=this;sd(s.history,e,t=>function(n,r,o){var a;i._isUrlChanging(o)&&i._flushPendingPageview(),t.call(this,n,r,o),i._capturePageview(e,!i._isFlushingPageview&&"popstate"!==(null==s||null===(a=s.event)||void 0===a?void 0:a.type))})}_getCurrentLocation(){const e=null==s?void 0:s.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}:ft(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(Xe,{navigation_type:e});t?(this._pendingPageview=i,Promise.resolve().then(()=>this._flushPendingPageview())):i()}this._lastLocation=i}catch(t){Mr.error(`Error capturing ${e} pageview`,t)}}_isUrlChanging(e){var t,i;return!(wt(e)||!s)&&(null===(t=Fa(String(e)))||void 0===t?void 0:t.href)!==(null===(i=s.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){Mr.error("Error capturing deferred pageview",e)}finally{this._isFlushingPageview=!1}this._lastLocation=this._getCurrentLocation()}}_setupPopstateListener(){if(this._popstateListener)return;const e=()=>{this._capturePageview("popstate")};Wr(s,"popstate",e),this._popstateListener=()=>{s&&s.removeEventListener("popstate",e)}}_setupHashchangeListener(){if(this._hashchangeListener)return;const e=()=>{this._capturePageview("hashchange")};Wr(s,"hashchange",e),this._hashchangeListener=()=>{s&&s.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[J]),this.rageclicks=new du(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return ft(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return wt(this._config.capture_heatmaps)?wt(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;gd.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({[J]:i}),this._enabledServerSide=i,this.startIfEnabled()}getAndClearBuffer(){const e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){fd(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval="visible"===(null==o?void 0:o.visibilityState)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){s&&o&&(this._flushHandler=this._flush.bind(this),Wr(s,Ze,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==s?void 0:s.event)),Wr(o,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==s?void 0:s.event)),Wr(o,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new ma(this.instance,fa,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),Wr(o,R,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;s&&o&&(this._flushHandler&&s.removeEventListener(Ze,this._flushHandler),this._onClickHandler&&o.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&o.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&o.removeEventListener(R,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(),n=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),o=function(e,t,i){let n=e;for(;n&&xo(n)&&!Po(n,"body");){if(n===i)return!1;let e;try{var r,o,a;e=null===(r=null!==(o=null===(a=n.ownerDocument)||void 0===a?void 0:a.defaultView)&&void 0!==o?o:s)||void 0===r?void 0:r.getComputedStyle(n).position}catch(e){return!1}if(at(t,e))return!0;n=Bo(n)}return!1}(Oo(e),["fixed","sticky"],r);return{x:e.clientX+(o?0:n),y:e.clientY+(o?0:i),target_fixed:o,type:t}}_onClick(e,t="click"){var i;if(ko(e.target)||!fd(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()))&&Jo(Oo(e),this.instance.config.rageclick)&&this._capture(ls(ls({},s),{},{type:"rageclick"})),this._capture(s)}_onMouseMove(e){!ko(e.target)&&fd(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(e,"mousemove"))},500))}_capture(e){if(!s)return;const t=this._config.disable_capture_url_hashes?es(s.location.href):s.location.href,i=this._config.custom_personal_data_properties,n=this._config.mask_personal_data_properties?[...Na,...i||[]]:[],r=La(t,n,Ua);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:ma,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=(e=!1)=>{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}),{})),e?{transport:"sendBeacon",send_instantly:!0}:void 0),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},wt(null==e?void 0:e.name)||wt(null==e?void 0:e.value))return void rd.error("Invalid metric received",e);const i="string"==typeof e.navigationURL?e.navigationURL:void 0,s=this._maskedURL(i);if(mt(s))return;const n=Ct(e.navigationId)||"string"==typeof e.navigationId?`navigation:${e.navigationId}`:`url:${s}`;if(this._maxAllowedValue&&e.value>=this._maxAllowedValue)return void rd.error("Ignoring metric with value >= "+this._maxAllowedValue,e);this._buffer.navigationKey!==n&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),mt(this._buffer.navigationKey)&&(this._buffer.navigationKey=n,this._buffer.url=s),this._buffer.firstMetricTimestamp=mt(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;const r=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,ft(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){const t={};for(const i of cd){const s="url"===i&&"string"==typeof e.attribution[i]?this._maskedURL(e.attribution[i]):e.attribution[i];mt(s)||(t[i]=s)}o.attribution=t}else delete o.attribution;mt(r)||(o.$session_id=r.sessionId,o.$window_id=r.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,n,r=!1;const o=p.__PosthogExtensions__,a=null==o?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(null==a?void 0:a[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&mt(a)?null==o?void 0:o.postHogWebVitalsCallbacks:void 0);if(!mt(l)){const s=l.withoutAttribution,o=this.attributionMetrics;r=!mt(s),e=o.indexOf("LCP")>-1?l.onLCP:(null==s?void 0:s.onLCP)||l.onLCP,t=o.indexOf("CLS")>-1?l.onCLS:(null==s?void 0:s.onCLS)||l.onCLS,i=o.indexOf("FCP")>-1?l.onFCP:(null==s?void 0:s.onFCP)||l.onFCP,n=o.indexOf("INP")>-1?l.onINP:(null==s?void 0:s.onINP)||l.onINP}if(!(e&&t&&i&&n))return void rd.error("web vitals callbacks not loaded - not starting");const c={reportSoftNavs:this.useSoftNavs},u=r&&this.attributionMetrics.indexOf("INP")>-1?ls(ls({},c),{},{includeProcessedEventEntries:!1}):c;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("FCP")>-1&&i(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("INP")>-1&&n(this._addToBuffer.bind(this),u);const d=null==s?void 0:s.document;Wr(d,R,()=>{"hidden"===(null==d?void 0:d.visibilityState)&&this._flushToCapture(!0)}),Wr(s,"pagehide",()=>this._flushToCapture(!0)),this._initialized=!0},this._enabledServerSide=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[te]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const i=ft(this._perfConfig)?null===(e=this._perfConfig)||void 0===e?void 0:e.web_vitals_allowed_metrics:void 0;return wt(i)?(null===(t=this._instance.persistence)||void 0===t?void 0:t.props.$web_vitals_allowed_metrics)||ad:i}get flushToCaptureTimeoutMs(){return(ft(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=ft(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return kt(e)?e?ad:[]:pt(e)?e:ld}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=ft(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){const e=ft(this._perfConfig)&&Ct(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:od;return e>0&&6e4>=e?od:e}get isEnabled(){const e=null==a?void 0:a.protocol;if("http:"!==e&&"https:"!==e)return rd.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=ft(this._perfConfig)?this._perfConfig.web_vitals:kt(this._perfConfig)?this._perfConfig:void 0;return kt(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(rd.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const i=ft(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=ft(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[te]:i}),this._instance.persistence.register({[re]: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=p.__PosthogExtensions__,s=this._callbackFlavor,n=null==i?void 0:i.postHogWebVitalsCallbacksByFlavor;(null==n?void 0:n[s])||"web-vitals"===s&&mt(n)&&(null==i?void 0:i.postHogWebVitalsCallbacks)?e():null===(t=g(this._instance))||void 0===t||t(this._instance,s,t=>{t?rd.error("failed to load script",t):e()})}_maskedURL(e){const t=e||(null==s?void 0:s.location.href);if(!t)return void rd.error("Could not determine current URL");const i=this._instance.config.disable_capture_url_hashes?es(t):t,n=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...Na,...n||[]]:[];return La(i,r,Ua)}},exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(!s||!this.isEnabled||!(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.errorWrappingFunctions))return;const t=p.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=p.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=p.__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=n(this.captureException.bind(this)))}catch(e){ed.error("failed to start",e),this._stopCapturing()}},this._instance=e,this._remoteEnabled=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[Z]),this._rateLimiter=new Ht(ls(ls({},function(e={}){var t,i,s,n;return{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(n=e.exceptionRateLimiterBucketSize)&&void 0!==n?n:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking)),{},{refillInterval:1e4,_logger:ed})),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 ft(e)?t=ls(ls({},t),e):(mt(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?(ed.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.errorWrappingFunctions)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"exception-autocapture",t=>{if(t)return ed.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({[Z]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}onConfigChange(){this._config=this._requiredConfig()}captureException(e){try{var t,i,s;const n=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(n))return void ed.info("Skipping exception capture because of client rate limiting.",{exception:n});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 qs,new Us,new Ws],function(e,...t){return(i,s=0)=>{const n=[],r=i.split("\n"),o=Math.min(r.length,s+1e3),a=[];for(let i=s;o>i;i++){const s=r[i];if(s.length>1024)continue;const o=Ts.test(s)?s.replace(Ts,"$1"):s;if(!o.match(/\S*Error: /)){for(const i of t){const t=i(o,e);if(t){n.push(t);const e=Fs(n);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(Ms(n,a)>=50)break}}const l=[...a].sort((e,t)=>t.start-e.start),c=l[l.length-1];if(c){const e=As(n,c);n.splice(c.start-e,e);for(const t of l)t.start-=e}for(const e of l)Rs(n,e);return a.some(e=>0===e.start&&n.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))}(n),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})}(n)}}("web:javascript",Es,Ps)),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=Js(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new Zs(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=Js(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(!e.ok)return;const n=e.config;if(!("errorTracking"in n))return;const r=null!==(t=null===(i=n.errorTracking)||void 0===i?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null===(s=n.errorTracking)||void 0===s?void 0:s.captureExtensionExceptions;this._suppressionRules=r,this._instance.persistence&&this._instance.persistence.register({[X]:this._suppressionRules,[ee]:o})}get _captureExtensionExceptions(){var e;const t=!!this._instance.get_property(ee),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(!yt(e)||0===e.trim().length)return void Qd.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)=>Ys.has(s)?(t.push(s),i):(i[s]=e[s],i),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t));s.length>0&&Qd.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this._exceptionStepsBuffer.add(ls({[Gs]:e,[Ks]:(new Date).toISOString()},i))}catch(e){Qd.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 Qd.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 Qd.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 Qd.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 Qd.info("Skipping exception capture because it was thrown by the PostHog SDK")}const i=this._exceptionStepsConfig.enabled&&wt(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 Yd(e)||Qd.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void(Yd(e)||Qd.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 Qd.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 ft(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})=>(yt(t)&&t.length>0&&e.$exception_types.push(t),yt(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=Qc[e.operator],s=t[e.key];if(!i||!s)return!1;const n=pt(e.value)?e.value:[e.value];return n.length>0&&i(n,s)});return"OR"===e.type?i.some(Boolean):i.every(Boolean)})}catch(e){return Qd.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&&Xd.some(t=>e.startsWith(t)));return 0!==i.length&&(!i.every(({filename:e})=>!!e&&e.startsWith(Jd))||e.some(({type:e,value:t})=>"NoResponse"===e||yt(t)&&Zd.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(Jd))))}_isInjectedBrowserScriptException(e){return e.some(({value:e})=>yt(e)&&eh.some(t=>e.includes(t)))}_isPostHogException(e){if(e.length>0){var t,i,s,n;const r=null!==(t=null===(i=e[0].stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[],o=r[r.length-1];return null!==(s=null==o||null===(n=o.filename)||void 0===n?void 0:n.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!wt(e)&&pt(e)}},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({[se]:!!t.productTours}),!md(this._instance))return!this._productTourManager&&wt(null===(i=this._persistence)||void 0===i?void 0:i.props.ph_product_tours)||vd.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&&md(this._instance)&&this._loadScript(()=>this._startProductTours())}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.generateProductTours)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"product-tours",t=>{t?vd.error("Could not load product tours script",t):e()})}_startProductTours(){var e;!this._productTourManager&&(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.generateProductTours)&&(this._productTourManager=p.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(pt(this._cachedTours)&&!t)return void e(this._cachedTours,{isLoaded:!0});const i=this._persistence;if(i){const s=i.props[Se];if(pt(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(!md(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||vd.warn(i):vd.error(i),void e([],{isLoaded:!1,error:i})}const n=pt(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=n,i&&i.register({[Se]:n}),e(n,{isLoaded:!0})}})}getActiveProductTours(e){wt(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)}},siteApps:class{constructor(e){this._instance=e,this._siteAppElementPatchCount=0,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps&&!this._instance.config.require_subresource_integrity}_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=p._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.siteApps}initialize(){if(this._instance.config.opt_in_site_apps&&!this.isEnabled&&bd.critical("opt_in_site_apps is ignored: require_subresource_integrity disables site apps"),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,n,r,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({},gn(e,yd)),{},{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===(n=e.properties)||void 0===n?void 0:n.$set_once)&&void 0!==s?s:{}),d)}:{}),elements_chain:null!==(r=null===(o=e.properties)||void 0===o?void 0:o.$elements_chain)&&void 0!==r?r:"",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)||(bd.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)||(bd.error("prepare_external_dependency_script returned null"),null)}return e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,n,r,a,l;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=null==o?void 0:o.defaultView,u=null==c||null===(e=c.Node)||void 0===e?void 0:e.prototype;if(!c||!u)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();const d=[],h=this,_=new WeakSet,p=(e,t,i)=>{if(!(null==e?void 0:e[t]))return;const s=e[t];e[t]=i(s),d.push(()=>{e[t]=s})},g=e=>{if(_.has(e))return e;const t=h._prepareElementForSiteApp(e);return t&&_.add(t),t},f=e=>e.map(e=>"string"==typeof e?e:g(e)).filter(e=>!St(e));return p(u,"appendChild",e=>function(t){const i=g(t);return i?e.call(this,i):t}),p(u,"insertBefore",e=>function(t,i){const s=g(t);return s?e.call(this,s,i):t}),p(u,"replaceChild",e=>function(t,i){const s=g(t);return s?e.call(this,s,i):i}),[null===(t=c.Element)||void 0===t?void 0:t.prototype,null===(i=c.Document)||void 0===i?void 0:i.prototype,null===(s=c.DocumentFragment)||void 0===s?void 0:s.prototype].forEach(e=>{p(e,"append",e=>function(...t){return e.apply(this,f(t))}),p(e,"prepend",e=>function(...t){return e.apply(this,f(t))})}),[null===(n=c.Element)||void 0===n?void 0:n.prototype,null===(r=c.CharacterData)||void 0===r?void 0:r.prototype,null===(a=c.DocumentType)||void 0===a?void 0:a.prototype].forEach(e=>{p(e,"before",e=>function(...t){return e.apply(this,f(t))}),p(e,"after",e=>function(...t){return e.apply(this,f(t))}),p(e,"replaceWith",e=>function(...t){const i=f(t);return t.length&&!i.length?void 0:e.apply(this,i)})}),p(null===(l=c.Element)||void 0===l?void 0:l.prototype,"insertAdjacentElement",e=>function(t,i){const s=g(i);return s?e.call(this,t,s):null}),this._restoreSiteAppElementPatches=()=>{d.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&&(bd.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 n=n=>{t.errored=!n,t.loaded=!0,bd.info(`Site app with id ${e.id} ${n?"loaded":"errored"}`),s&&i()};try{const{processEvent:i}=this._runWithPreparedSiteAppElements(t=>e.init({posthog:this._instance,callback(e){t(),n(e)}}),!1);i&&(t.processEvent=i),s=!0}catch(t){bd.error(Sd+e.id,t),n(!1)}if(s&&t.loaded)try{i()}catch(i){bd.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){bd.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 bd.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 n=e.config;if(null===(s=n.siteApps)||void 0===s?void 0:s.length)if(this.isEnabled)for(const{id:e,url:t}of n.siteApps){var r,o;p[`__$$ph_site_app_${e}`]=this._instance,null===(r=p.__PosthogExtensions__)||void 0===r||null===(o=r.loadSiteApp)||void 0===o||o.call(r,this._instance,t,t=>{if(t)return bd.error(Sd+e,t)})}else bd.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},surveys:class extends Id{constructor(e){super(new Fd(e))}},tracingHeaders:class{constructor(e){this._instance=e,this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._patchedHostnames=void 0,this._traceparentTargetsForPatch=[],this._startCapturing=()=>{const{hostnames:e,traceparentTargets:t}=this._syncForPatch();var i,s;e||t?(e||pt(this._hostnamesForPatch)||(this._hostnamesForPatch=[]),this._patchedHostnames!==this._hostnamesForPatch&&(this._stopCapturing(),this._patchedHostnames=this._hostnamesForPatch),mt(this._restoreXHRPatch)&&(this._restoreXHRPatch=null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.tracingHeadersPatchFns)||void 0===i?void 0:i._patchXHR(this._hostnamesForPatch,()=>this._instance.get_distinct_id(),this._instance.sessionManager,this._traceparentTargetsForPatch)),mt(this._restoreFetchPatch)&&(this._restoreFetchPatch=null===(s=p.__PosthogExtensions__)||void 0===s||null===(s=s.tracingHeadersPatchFns)||void 0===s?void 0:s._patchFetch(this._hostnamesForPatch,()=>this._instance.get_distinct_id(),this._instance.sessionManager,this._traceparentTargetsForPatch))):this._stopCapturing()}}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.tracingHeadersPatchFns)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"tracing-headers",t=>{if(t)return nd.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 pt(e)?(pt(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):!pt(this._hostnamesForPatch)||(this._hostnamesForPatch.splice(0),e)?(this._hostnamesForPatch=e||void 0,this._hostnamesForPatch):void 0}_syncTraceparentTargetsForPatch(){const e=this._instance.config.trace_propagation_targets,t=pt(e)?e.filter(e=>yt(e)&&!!e):[];return this._traceparentTargetsForPatch.splice(0,this._traceparentTargetsForPatch.length,...t),t.length>0?this._traceparentTargetsForPatch:void 0}_syncForPatch(){return{hostnames:this._syncHostnamesForPatch(),traceparentTargets:this._syncTraceparentTargetsForPatch()}}_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(){const{hostnames:e,traceparentTargets:t}=this._syncForPatch();e||t?this._loadScript(this._startCapturing):this._stopCapturing()}},toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){p.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=p.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,i=void 0){var n,r;if(Vr(this.instance.config))return!1;if(!s||!o)return!1;e=null!==(n=e)&&void 0!==n?n:s.location,i=null!==(r=i)&&void 0!==r?r:s.history;try{if(!t){try{s.localStorage.setItem("test","test"),s.localStorage.removeItem("test")}catch(e){return!1}t=null==s?void 0:s.localStorage}const n=Rd||Da(e.hash,"__posthog")||Da(e.hash,"state");let r;const o=n?ts(()=>JSON.parse(atob(decodeURIComponent(n))))||ts(()=>JSON.parse(decodeURIComponent(n))):null;return o&&"ph_authorize"===o.action?(r=o,r.source="url",r&&Object.keys(r).length>0&&(o.desiredHash?e.hash=o.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):(r=JSON.parse(t.getItem(Ad)||"{}"),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=p.ph_load_toolbar||p.ph_load_editor;!wt(t)&&gt(t)?t(e,this.instance):$d.warn("No toolbar load function found")}loadToolbar(e){const t=!!(null==o?void 0:o.getElementById("__POSTHOG_TOOLBAR__"));if(!s||t)return!1;const i="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,n=ls(ls({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},i?{instrument:!1}:{});if(s.localStorage.setItem(Ad,JSON.stringify(ls(ls({},n),{},{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(n);else if(0===this._getToolbarState()){var r;this._setToolbarState(1),null===(r=g(this.instance))||void 0===r||r(this.instance,"toolbar",e=>{if(e)return $d.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(n)}),Wr(s,"turbolinks:load",()=>{this._setToolbarState(0),this.loadToolbar(n)})}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,i=void 0){return this.maybeLoadToolbar(e,t,i)}},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);yt(s)&&t.variants[s]&&this._applyVariantForFlag(t,s)}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(p_);else if(!this._config.disable_web_experiments){if(wt(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._applyVariantForFlag(s,t)}})}}previewWebExperiment(){const t=e.getWindowLocation();if(null==t?void 0:t.search){const i=Oa(null==t?void 0:t.search,"__experiment_id"),s=Oa(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 n=s.filter(e=>e.id===t);n&&n.length>0&&(e._logInfo(`Previewing web experiment [${n[0].name}] with variant [${i}]`),this._applyTransforms(n[0].name,i,n[0].variants[i].transforms))}_applyVariantForFlag(t,i){const s=t.variants[i];e._matchUrlConditions(s,this._instance)?this._applyTransforms(t.name,i,s.transforms):e._logInfo(`skipping variant ${i} of experiment ${t.name} because this page does not match its url conditions`)}static _matchesTestVariant(t,i){return!wt(t.conditions)&&e._matchUrlConditions(t,i)&&e._matchUTMConditions(t)}static _matchUrlConditions(t,i){var s;if(wt(t.conditions)||wt(null===(s=t.conditions)||void 0===s?void 0:s.url))return!0;const n=e.getWindowLocation();if(n){var r,o,a;const e=Eo(i,n.href);return!(null===(r=t.conditions)||void 0===r?void 0:r.url)||v_[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==s?void 0:s.location}static _matchUTMConditions(e){var t;if(wt(e.conditions)||wt(null===(t=e.conditions)||void 0===t?void 0:t.utm))return!0;const i=Ha();if(i.utm_source){var s,n,r,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===(n=e.conditions)||void 0===n||null===(n=n.utm)||void 0===n?void 0:n.utm_campaign)==i.utm_campaign,d=!(null===(r=e.conditions)||void 0===r||null===(r=r.utm)||void 0===r?void 0:r.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){Mr.info(`[WebExperiments] ${e}`,t)}static _logWarn(e,...t){Mr.warn(`[WebExperiments] ${e}`,t)}static _sanitizeLinkTargets(t){("http://www.w3.org/1999/xhtml"===t.namespaceURI&&"template"===t.localName?t.content:t).querySelectorAll("a[target], template").forEach(t=>{var i;if("template"===t.localName)return void("http://www.w3.org/1999/xhtml"===t.namespaceURI&&e._sanitizeLinkTargets(t));if("http://www.w3.org/1999/xhtml"!==t.namespaceURI||"_blank"!==(null===(i=t.getAttribute("target"))||void 0===i?void 0:i.toLowerCase()))return void t.removeAttribute("target");const s=(t.getAttribute("rel")||"").split(/\s+/).filter(e=>e&&!/^(opener|noopener)$/i.test(e));s.push("noopener"),t.setAttribute("rel",s.join(" "))})}_applyTransforms(t,i,s){this._is_bot()?e._logInfo(p_):"control"!==i?s.forEach(s=>{if(s.selector){var n;e._logInfo(`applying transform of variant ${i} for experiment ${t} `,s);const r=null===(n=document)||void 0===n?void 0:n.querySelectorAll(s.selector);if(!(null==r?void 0:r.length))return void e._logWarn(`no element on this page matches selector ${s.selector} of variant ${i} for experiment ${t}`);const o=new Map;null==r||r.forEach(t=>{if("script"===t.localName.toLowerCase())return;const i=t;if(s.html){var n;const a="http://www.w3.org/1998/Math/MathML"===t.namespaceURI&&"annotation-xml"===t.localName&&(null===(n=t.getAttribute("encoding"))||void 0===n?void 0:n.toLowerCase())||"",l=JSON.stringify([t.namespaceURI,t.localName,a]);let c=o.get(l);if(wt(c)){var r;const i=null!==(r=f_)&&void 0!==r?r:f_=__(),n=t.ownerDocument.implementation.createHTMLDocument(""),u=n.createElementNS(t.namespaceURI,t.localName);a&&u.setAttribute("encoding",a);const d=n.createRange();d.selectNodeContents(u);const h="http://www.w3.org/2000/svg"===t.namespaceURI&&/^(foreignObject|desc|title)$/.test(t.localName)||/^(text\/html|application\/xhtml\+xml)$/.test(a)?"http://www.w3.org/1999/xhtml":t.namespaceURI,_=d.createContextualFragment(s.html);"http://www.w3.org/1998/Math/MathML"===t.namespaceURI&&/^(mi|mo|mn|ms|mtext)$/.test(t.localName)?(u.appendChild(_),i.sanitize(u,ls(ls({},g_),{},{NAMESPACE:h||void 0,IN_PLACE:!0}))):("http://www.w3.org/1999/xhtml"===u.namespaceURI&&"template"===u.localName?u.content:u).appendChild(i.sanitize(_,ls(ls({},g_),{},{NAMESPACE:h||void 0,RETURN_DOM_FRAGMENT:!0}))),e._sanitizeLinkTargets(u),c=u.innerHTML,o.set(l,c)}i.innerHTML=c}s.css&&i.setAttribute("style",s.css)})}}):e._logInfo("Control variants leave the page unmodified.")}_is_bot(){return r&&this._instance?jc(r,this._config.custom_blocked_useragents):void 0}},conversations:class{constructor(e){this._instance=e,this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1,this._resetGeneration=0,this._pendingPanelAction=null,this._theme=null}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations)return void(this._pendingPanelAction=null);if(this._remoteConfigSuccessful=e.ok,!e.ok)return;const t=e.config.conversations;wt(t)?this._pendingPanelAction=null:(kt(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this._isConversationsEnabled||(this._pendingPanelAction=null),this.loadIfEnabled())}reset(){var e;null===(e=this._conversationsManager)||void 0===e||e.reset(),this._conversationsManager=null,this._resetGeneration++,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1,this._pendingPanelAction=null}loadIfEnabled(){if(this._conversationsManager)return;if(this._isInitializing)return;if(this._instance.config.disable_conversations)return;if(Vr(this._instance.config))return;if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=null==p?void 0:p.__PosthogExtensions__;if(e&&!mt(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=g(this._instance);if(!i)return void this._handleLoadError(L);const s=this._resetGeneration;i(this._instance,"conversations",t=>{if(s!==this._resetGeneration)return this._isInitializing=!1,void this.loadIfEnabled();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 m_.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,m_.info("Conversations loaded successfully")}catch(e){return void this._handleLoadError("Error completing conversations initialization",e)}this._theme&&this._conversationsManager.setTheme(this._theme),this._applyPendingPanelAction()}else m_.error("Cannot complete initialization: remote config is null")}_applyPendingPanelAction(){const e=this._pendingPanelAction;this._pendingPanelAction=null,this._conversationsManager&&e&&("open"===e?this._conversationsManager.open():this._conversationsManager.close())}_handleLoadError(e,t){m_.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():m_.warn("Conversations not loaded yet.")}hide(){"open"===this._pendingPanelAction&&(this._pendingPanelAction=null),this._conversationsManager&&this._conversationsManager.hide()}open(){this._conversationsManager?(this._pendingPanelAction=null,this._conversationsManager.open()):this._pendingPanelAction="open"}close(){this._conversationsManager?(this._pendingPanelAction=null,this._conversationsManager.close()):this._pendingPanelAction="close"}setTheme(e){var t,i;this._theme=ls(ls(ls({},this._theme),e),{},{dark:ls(ls({},null===(t=this._theme)||void 0===t?void 0:t.dark),null==e?void 0:e.dark)}),null===(i=this._conversationsManager)||void 0===i||i.setTheme(e)}isAvailable(){return!0===this._isConversationsEnabled&&!St(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Vr(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":mt(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?wt(this._remoteConfig)||!this._remoteConfig.token?"missing_token":(null==p?void 0:p.__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 Dt(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,i):(m_.warn(y_),null)})()}getMessages(e,t){var i=this;return Dt(function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(m_.warn(y_),null)})()}markAsRead(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(m_.warn(y_),null)})()}getTickets(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(m_.warn(y_),null)})()}requestRestoreLink(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(m_.warn(y_),null)})()}restoreFromToken(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(m_.warn(y_),null)})()}restoreFromUrlToken(){var e=this;return Dt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(m_.warn(y_),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()}},logs:class extends P_{constructor(e){super({get(){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.logs},captureHintKey:ne,get remoteConfigWillArrive(){var t,i;return!(null===(t=e._shouldDisableFlags)||void 0===t?void 0:t.call(e))||!!(null===(i=p._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:n,lastActivityTimestamp:r}=e.sessionManager.checkAndGetSessionAndWindowId(!0);i.sessionId=t,i.windowId=s,wt(n)||(i.sessionStartTimestamp=n),wt(r)||(i.lastActivityTimestamp=r)}if((null==p||null===(t=p.location)||void 0===t?void 0:t.href)&&(i.currentUrl=e.config.disable_capture_url_hashes?es(p.location.href):p.location.href),e.featureFlags){const t=e.featureFlags.getFlags();t&&t.length>0&&(i.activeFeatureFlags=t)}return i}(e)),this._instance=e,this.name=Cu,this._listenForReconnect()}get _isRequestReady(){return this._instance.__loaded}_getConsoleLoader(){const e=Or("[logs]"),t=null==p?void 0:p.__PosthogExtensions__;if(!t)return void e.error("PostHog Extensions not found.");const i=g(this._instance);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(L)}},metrics:class{constructor(e){this._instance=e,this._logger=Or("[metrics]"),this._disposed=!1,this._visibilityListening=!1,this._onVisibilityChange=()=>{"hidden"===(null==o?void 0:o.visibilityState)&&this.flush()}}initialize(){this.onConfigChange(),this._disposed||this._visibilityListening||!(null==o?void 0:o.addEventListener)||(Wr(o,"visibilitychange",this._onVisibilityChange),this._visibilityListening=!0)}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=L_(e,i),n=D_(e,i);return()=>{t=!1,s(),n()}})(this._instance):!t&&this._stopNetworkMetrics&&(this._stopNetworkMetrics(),this._stopNetworkMetrics=void 0)}_getCore(){var e;if(this._disposed)return;const t=null===(e=this._instance)||void 0===e||null===(e=e.config)||void 0===e?void 0:e.metrics;if(!this._core||this._resolvedFrom!==t){var i;null===(i=this._core)||void 0===i||i.reset(),this._resolvedFrom=t;const e=function(e){var t,i,s,n,r;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!==(n=null==e?void 0:e.flushIntervalMs)&&void 0!==n?n:1e4,maxSeriesPerFlush:null!==(r=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==r?r:1e3}}(t);mt(null==t?void 0:t.flushIntervalMs)&&(e.flushIntervalMs=6e4),this._core=new Ir(this._createHost(),e,this._logger)}return this._core}count(e,t=1,i){var s;null===(s=this._getCore())||void 0===s||s.count(e,t,i)}gauge(e,t,i){var s;null===(s=this._getCore())||void 0===s||s.gauge(e,t,i)}histogram(e,t,i){var s;null===(s=this._getCore())||void 0===s||s.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,i;this._disposed=!0,null==o||null===(e=o.removeEventListener)||void 0===e||e.call(o,"visibilitychange",this._onVisibilityChange),this._visibilityListening=!1,null===(t=this._stopNetworkMetrics)||void 0===t||t.call(this),this._stopNetworkMetrics=void 0,null===(i=this._core)||void 0===i||i.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 n=e=>{s||(s=!0,clearTimeout(r),i(e))},r=setTimeout(()=>n({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(ls(ls(ls({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),"hidden"===(null==o?void 0:o.visibilityState)&&{preferSyncCompression:!0}),{},{fireCallbackOnDrop:!0,callback(e){const t=e.statusCode;if(t>=200&&300>t)n({kind:"ok"});else if(413===t)n({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)n({kind:"fatal",error:new Error(`metrics request failed with status ${t}`)});else{var i;n({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)}},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==o?void 0:o.modelContext;if(!e||!gt(e.registerTool))return;const t=N_.get(e);if(t)return t.instances.add(this._instance),void(this._isPatched=!0);const i={instances:new Set([this._instance])},s=e.registerTool,n=this;sd(e,"registerTool",e=>{const t=e;return function(e,...s){let r=e;try{r=n._wrapTool(e,i)}catch(i){return t.call(this,e,...s)}return t.call(this,r,...s)}}),e.registerTool!==s&&(N_.set(e,i),this._isPatched=!0)}_wrapTool(e,t){if(!e||!gt(e.execute))return e;const i=e.execute,s=this,{tool:n,injected:r}=function(e,t){const i={intent:!1,model:!1},s=e.inputSchema;if(!function(e){return!!mt(e)||ft(e)&&Object.keys(e).every(e=>B_.has(e)||e.startsWith("x-"))&&!0!==e.additionalProperties&&!ft(e.additionalProperties)&&(!e.type||"object"===e.type)&&(!e.properties||ft(e.properties))&&(!e.required||pt(e.required))}(s))return{tool:j_(e),injected:i};const n=(null==s?void 0:s.properties)||{},r=e=>q_(n,e)||pt(null==s?void 0:s.required)&&s.required.includes(e);if(i.intent=t.intent&&!r("context"),i.model=t.model&&!r("llm_model"),!i.intent&&!i.model)return{tool:j_(e),injected:i};const o=ls({},n),a=pt(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 model identifier you are running as, for example "claude-opus-4-8" or "gpt-5.2". Pass "unknown" if you are not certain. Recorded for the site developer\'s analytics.'},a.includes("llm_model")||a.push("llm_model")),{tool:j_(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=H_(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(n,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const a=new Date,l=function(e,t){if(!ft(e))return{};try{const i=t.intent?W_(e.context,2048,!0):void 0,s=t.model?W_(e.llm_model,256):void 0;return ls(ls({},i&&"{}"!==i?{intent:i}:{}),s&&"unknown"!==s.toLowerCase()?{model:s}:{})}catch(e){return{}}}(o[0],r),c=function(e,t){const i=e[0];if(!ft(i))return e;try{const s=t.intent&&q_(i,"context"),n=t.model&&q_(i,"llm_model");if(!s&&!n)return e;const r=ls({},i);return s&&delete r.context,n&&delete r.llm_model,[r,...e.slice(1)]}catch(t){return e}}(o,r);let u;try{u=i.apply(this===n?e:this,c)}catch(e){throw s._captureToolCall(t,n,a,{error:e,errorResult:!1},l),e}if((d=u)&&"function"==typeof d.then)return Promise.resolve(u).then(e=>{const i=V_(e)?{error:e,errorResult:!0}:void 0;return s._captureToolCall(t,n,a,i,l),e},e=>{throw s._captureToolCall(t,n,a,{error:e,errorResult:!1},l),e});var d;const h=V_(u)?{error:u,errorResult:!0}:void 0;return s._captureToolCall(t,n,a,h,l),u}}),n}_captureToolCall(e,t,i,s,n){const r=Date.now()-i.getTime();let o;for(const c of e.instances){var l;const e=H_(c.config.capture_webmcp);if(e){s&&!o&&(o=J_(s.error,s.errorResult));try{c.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==a?void 0:a.hostname,$mcp_duration_ms:r,$mcp_is_error:!!s},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),e.intent&&n.intent?{$mcp_intent:n.intent,$mcp_intent_source:"context_parameter"}:{}),e.model&&n.model?{$mcp_llm_model:n.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:i})}catch(e){continue}if(s&&o&&c.exceptions&&(null===(l=c.exceptionObserver)||void 0===l?void 0:l.isEnabled))try{const e={$exception_list:Y_(c.exceptions,s,o.message),$exception_level:"error",$exception_source:"mcp.tool_call",$mcp_interface:"webmcp",$mcp_tool_name:t.name,$mcp_resource_name:t.name,$mcp_tool_description:t.description,$mcp_server_name:null==a?void 0:a.hostname};c.exceptionObserver.captureException(e)}catch(e){}}}}}});const Z_=function(){i.SDK_DIST_CHANNEL="npm";const e=Fu[ju]=new Ju;return function(){function e(){e.done||(e.done=!0,Rc=!1,Dr(Fu,function(e){e._dom_loaded()}))}(null==o?void 0:o.addEventListener)?"complete"===o.readyState?e():Wr(o,"DOMContentLoaded",e,{capture:!1}):s&&Mr.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),e}();export{dl as Compression,El as DEFAULT_PRODUCT_TOUR_APPEARANCE,wl as DisplaySurveyType,Ju as PostHog,kl as ProductTourEventName,xl as ProductTourEventProperties,bl as SurveyEventName,Sl as SurveyEventProperties,hl as SurveyEventType,pl as SurveyPosition,ml as SurveyQuestionBranchingType,vl as SurveyQuestionType,yl as SurveySchedule,gl as SurveyTabPosition,fl as SurveyType,_l as SurveyWidgetType,Z_ as default,Z_ as posthog,Rl as severityLevels};
1
+ const e="0.12.2",t={DEBUG:(!1,!1),LIB_VERSION:(e,"1.453.2"),LIB_NAME:("browser-common","web"),JS_SDK_VERSION:e};var i=t;const s="u">typeof window?window:void 0,n="u">typeof globalThis?globalThis:s,r=null==n?void 0:n.navigator,o=null==n?void 0:n.document,a=null==n?void 0:n.location,l=null==n?void 0:n.fetch,c=(null==n?void 0:n.XMLHttpRequest)&&"withCredentials"in new n.XMLHttpRequest?n.XMLHttpRequest:void 0,u=null==n?void 0:n.AbortController,d=null==n?void 0:n.CompressionStream,h=null==r?void 0:r.userAgent,_="undefined"!=typeof globalThis?globalThis:s;_&&"undefined"==typeof self&&(_.self=_),_&&"undefined"==typeof File&&(_.File=function(){});const p=null!=s?s:{},g=e=>{var t;return(null==e?void 0:e.config.require_subresource_integrity)?e.__loadExternalDependency:null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.loadExternalDependency},f="$early_access_features",v="$active_feature_flags",m="$feature_flag_details",y="$feature_flag_errors",b="$feature_flag_evaluated_at",S="$feature_flag_request_id",w="$minimal_flag_called_events",C="$enabled_feature_flags",E="$stored_group_properties",k="$stored_person_properties",x="$flag_call_reported",P="$flag_call_reported_session_id",T="$feature_flag_payloads",I="$override_feature_flags",F="$override_feature_flag_payloads",R="visibilitychange",A="$autocapture_disabled_server_side",M="$surveys",O="$surveys_loaded_at",L="PostHog loadExternalDependency extension not found.",D="$surveys_activated",N="$surveys_activated_session",B="$surveys_activated_timestamps",U="$people_distinct_id",z="distinct_id",H="$device_id",q="$device_model",j="__alias",W="__cmpns",V="$fbc",G="$fbc_persistence",K="$fbp",Y="$fbp_persistence",Q="__timers",J="$heatmaps_enabled_server_side",Z="$exception_capture_enabled_server_side",X="$error_tracking_suppression_rules",ee="$error_tracking_capture_extension_exceptions",te="$web_vitals_enabled_server_side",ie="$dead_clicks_enabled_server_side",se="$product_tours_enabled_server_side",ne="$logs_capture_enabled_server_side",re="$web_vitals_allowed_metrics",oe="$session_recording_remote_config",ae="$session_recording_enabled_server_side",le="$replay_sample_rate",ce="$replay_override_sampling",ue="$replay_override_linked_flag",de="$replay_override_url_trigger",he="$replay_override_event_trigger",_e="$sesid",pe="$session_is_sampled",ge="$session_past_minimum_duration",fe="$session_recording_url_trigger_activated_session",ve="$session_recording_event_trigger_activated_session",me="$debug_first_full_snapshot_timestamp",ye="$sess_rec_flush_size",be="$groups",Se="ph_product_tours",we="$product_tours_activated",Ce="$product_tours_activated_session",Ee="$conversations_widget_session_id",ke="$conversations_ticket_id",xe="$conversations_widget_state",Pe="$conversations_user_traits",Te="$user_state",Ie="$client_session_props",Fe="$capture_rate_limit",Re="$initial_campaign_params",Ae="$initial_referrer_info",$e="$initial_person_info",Me="$epp",Oe="$posthog_cookieless",Le="$cookieless_mode",De="$sdk_debug_extensions_init_method",Ne="$sdk_debug_extensions_init_time_ms",Be="$sdk_debug_recording_script_not_loaded",Ue="$sdk_debug_replay_stale_config",ze="$sdk_debug_replay_event_trigger_status",He="$sdk_debug_replay_linked_flag_trigger_status",qe="$sdk_debug_replay_matched_recording_trigger_groups",je="$sdk_debug_replay_pending_trigger_conditions",We="$sdk_debug_replay_remote_trigger_matching_config",Ve="$sdk_debug_replay_trigger_groups_count",Ge="$sdk_debug_replay_url_trigger_status",Ke="$session_recording_start_reason",Ye="anonymous",Qe="identified",Je="identified_only",Ze="beforeunload",Xe="$pageview",et="$pageleave",tt="$identify",it="$groupidentify";var st=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}({}),nt=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"],ot=["token"];function at(e,t){return-1!==e.indexOf(t)}const lt=function(e){return e.trim()},ct=function(e){return e.replace(/^\$/,"")};function ut(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 dt=Object.prototype,ht=dt.hasOwnProperty,_t=dt.toString,pt=Array.isArray||function(e){return"[object Array]"===_t.call(e)},gt=e=>"function"==typeof e,ft=e=>e===Object(e)&&!pt(e),vt=e=>{if(ft(e)){for(const t in e)if(ht.call(e,t))return!1;return!0}return!1},mt=e=>void 0===e,yt=e=>"[object String]"==_t.call(e),bt=e=>yt(e)&&0===e.trim().length,St=e=>null===e,wt=e=>mt(e)||St(e),Ct=e=>"[object Number]"==_t.call(e)&&e==e,Et=e=>Ct(e)&&e>0,kt=e=>"[object Boolean]"===_t.call(e),xt=e=>at(rt,e),Pt=e=>at(ot,e);function Tt(e){return null===e||"object"!=typeof e}function It(e,t){return{}.toString.call(e)===`[object ${t}]`}function Ft(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 At(e,Error)}}function Rt(e){return"u">typeof Event&&At(e,Event)}function At(e,t){try{return e instanceof t}catch(e){return!1}}const $t=[!0,"true",1,"1","yes"],Mt=e=>at($t,e),Ot=[!1,"false",0,"0","no"];function Lt(e,t,i,s,n,r,o){try{var a=e[r](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,n)}function Dt(e){return function(){var t=this,i=arguments;return new Promise(function(s,n){var r=e.apply(t,i);function o(e){Lt(r,s,n,o,a,"next",e)}function a(e){Lt(r,s,n,o,a,"throw",e)}o(void 0)})}}const Nt=["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","lightpanda","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"],Bt=new Map,Ut=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=Bt.get(i);if(void 0!==s)return s;const n=e.toLowerCase(),r=Nt.concat(t).some(e=>-1!==n.indexOf(e.toLowerCase()));return 256>Bt.size||Bt.clear(),Bt.set(i,r),r};function zt(e,t,i,s,n){return t>i&&(s.warn("min cannot be greater than max."),t=i),Ct(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: "+n),zt(null!=n?n:i,t,i,s))}var Ht=class{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=zt(e.bucketSize,0,100,e._logger),this._refillRate=zt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=zt(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 n=this._buckets[s];return n?this._applyRefill(n,i):(n={tokens:this._bucketSize,lastAccess:i},this._buckets[s]=n),0===n.tokens||(n.tokens--,0===n.tokens&&(null===(t=this._onBucketRateLimited)||void 0===t||t.call(this,e)),0===n.tokens)}stop(){this._buckets={}}};const qt="Mobile",jt="Android",Wt="Tablet",Vt="Android Tablet",Gt="iPad",Kt="Apple Watch",Yt="Safari",Qt="BlackBerry",Jt="Samsung Internet",Zt="Chrome",Xt="Chrome iOS",ei="Internet Explorer",ti="Internet Explorer Mobile",ii="Opera",si="Microsoft Edge",ni="Firefox",ri="Firefox iOS",oi="Nintendo",ai="PlayStation",li="Xbox",ci="Android Mobile",ui="Mobile Safari",di="Windows",hi="Windows Phone",_i="Nokia",pi="Ouya",gi="Generic tablet",fi="Konqueror",vi="Oculus Browser",mi="Vivaldi",yi="Yandex",bi="Whale",Si="DuckDuckGo",wi="Pale Moon",Ci="Waterfox",Ei="Brave",ki="Claude",xi="Codex",Pi="ChatGPT",Ti="Google Search App",Ii=new RegExp("Version/(\\d+(\\.\\d+)?)"),Fi=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),Ri=new RegExp(li,"i"),Ai=new RegExp("PlayStation \\w+","i"),$i=new RegExp("Nintendo \\w+","i"),Mi=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 n=function(e){return(null==e?void 0:e.brave)?Ei:null}(i);return n||((null==s?void 0:s.detectGoogleSearchApp)&&at(e,"GSA/")?Ti:at(e," OPR/")&&at(e,"Mini")?"Opera Mini":at(e," OPR/")?ii:Mi.test(e)?Qt:at(e,"IEMobile")||at(e,"WPDesktop")?ti:at(e,"OculusBrowser")?vi:at(e,"SamsungBrowser")?Jt:at(e,"Edge")||at(e,"Edg/")?si:at(e,"Vivaldi/")?mi:at(e,"YaBrowser/")?yi:at(e,"Whale/")?bi:at(e,"DuckDuckGo/")||at(e,"Ddg/")?Si:at(e,"Claude/")?ki:at(e,"Codex/")?xi:at(e,"ChatGPT/")?Pi:at(e,"FBIOS")?"Facebook Mobile":at(e,"UCWEB")||at(e,"UCBrowser")?"UC Browser":at(e,"CriOS")?Xt:at(e,"CrMo")||at(e,Zt)?Zt:at(e,jt)&&at(e,Yt)?ci:at(e,"FxiOS")?ri:at(e.toLowerCase(),fi.toLowerCase())?fi:at(e,"Brave/")?Ei:((e,t)=>t&&at(t,"Apple")||function(e){return at(e,Yt)&&!at(e,Zt)&&!at(e,jt)}(e))(e,t)?at(e,qt)?ui:Yt:at(e,"PaleMoon/")?wi:at(e,"Waterfox/")?Ci:at(e,ni)?ni:at(e,"MSIE")||at(e,"Trident/")?ei:at(e,"Gecko")?ni:"")},Di={[ti]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[si]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[Zt]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[Xt]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[Yt]:[Ii],[ui]:[Ii],[ii]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[ni]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[ri]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[fi]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Qt]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),Ii],[ci]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[Jt]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[vi]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[mi]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[yi]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[bi]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Ei]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[ki]:[Fi],[xi]:[Fi],[Pi]:[Fi],[Si]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[wi]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[Ci]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[Ti]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[ei]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},Ni=function(e,t,i,s){const n=Li(e,t,i,s),r=Di[n];if(mt(r))return null;for(let t=0;r.length>t;t++){const i=e.match(r[t]);if(i)return parseFloat(i[i.length-2])}return null},Bi=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[li,e&&e[1]||""]],[new RegExp(oi,"i"),[oi,""]],[new RegExp(ai,"i"),[ai,""]],[Mi,[Qt,""]],[new RegExp(di,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[hi,""];if(new RegExp(qt).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"),[di,e]}return[di,""]}],[/((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=mt(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[jt,[e[2],e[3],e[4]||"0"].join(".")]:[jt,""]],[/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",""]]],Ui=function(e){for(let t=0;Bi.length>t;t++){const[i,s]=Bi[t],n=i.exec(e),r=n&&(gt(s)?s(n,e):s);if(r)return r}return["",""]},zi=function(e){return $i.test(e)?oi:Ai.test(e)?ai:Ri.test(e)?li:new RegExp(pi,"i").test(e)?pi:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?hi:/iPad/.test(e)?Gt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Kt:Mi.test(e)?Qt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(_i,"i").test(e)?_i:/(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(qt).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)?jt:Vt:new RegExp("(pda|Mobile)","i").test(e)?"Generic mobile":new RegExp(Wt,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?gi:""},Hi=function(e,t){var i;const s=zi(e);return s===Gt||s===Vt||"Kobo"===s||"Kindle Fire"===s||s===gi?Wt:s===oi||s===li||s===ai||s===pi?"Console":s===Kt?"Wearable":s?qt:"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!==(n=null==t?void 0:t.screenWidth)&&void 0!==n?n:0,null!==(r=null==t?void 0:t.screenHeight)&&void 0!==r?r:0)/(null!==(o=null==t?void 0:t.devicePixelRatio)&&void 0!==o?o:1)?qt:Wt:"Desktop";var n,r,o},qi=/\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",qi],[/\bFBAN\/EMA\b/i,"Facebook Lite",qi],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",qi],[/\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 Yi=3e5;var Qi=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,Yi);if(!t)return this._installedAt=i,void(this._until=i+s);this._until=Math.max(this._until,Math.min(i+s,this._installedAt+Yi))}remainingMs(){const e=Date.now();if(this._installedAt-5e3>e)return this.reset(),0;const t=Math.min(Yi,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 Ji=/^[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)&&Ji.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 ns.apply(this,arguments)}function ns(){return(ns=Dt(function*(e,t,i){let s;try{return yield Promise.race([e,new Promise((e,n)=>{s=is(()=>{try{null==i||i(),e()}catch(e){n(e)}},t)})])}finally{clearTimeout(s)}})).apply(this,arguments)}function rs(e){return rs="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},rs(e)}function os(e,t,i){return(t=function(e){var t=function(e){if("object"!=rs(e)||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var i=t.call(e,"string");if("object"!=rs(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==rs(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 n=i?Object.keys(i):[],r=s?Object.keys(s):[];if(hs&&ps(i,n,us)&&ps(s,r,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 n of t){const t=i[n];if(!t)continue;const r=null==cs?void 0:cs[n];if(r){hs[r]=t;continue}const o=e(n);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[n]=i;break}}}};return s&&o(r,s),i&&o(n,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),n=this.buildParsingContext(t),r=this.parseStacktrace(s,n);return{$exception_list:this.convertToExceptionList(r,i),$exception_level:"error"}}modifyFrames(e){var t=this;return Dt(function*(){for(const i of e)i.stacktrace&&i.stacktrace.frames&&pt(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,n;if(null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack)try{n=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch(e){}return ls(ls({},e),{},{cause:s,stack:n,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 Dt(function*(){let i=e;for(const e of t.modifiers)i=yield e(i);return i})()}convertToExceptionList(e,t){const i=[],s=(e,n,r)=>{var o;const a=i.length,l=void 0===n?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:r,synthetic:e.synthetic,exception_id:a,parent_id:n},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(Ft(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 pt(t)?t:void 0}i=Object.getPrototypeOf(i)}}}catch(e){}}buildCoercingContext(e,t,i=0){let s=0,n=0,r=!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;r||(r=!!_);try{if(p=this.applyCoercers(e,c),!p)throw l}catch(e){if(e===l)return void(0===i&&s--);if(!r)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 f=[];for(let e=0;50>s&&1e3>n&&g>e;e++){let i;n++;try{i=c.next(_[e])}catch(e){s++,i=this.coerceFallback(u(t+1))}i&&f.push(i)}return ls(ls({},p),{},{errors:f})},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 fs=/^([a-z][a-z0-9.+-]+):/i,vs=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function ms(e){if(!e||"<anonymous>"===e)return!1;const t=fs.exec(e);return!t||vs.includes(t[1].toLowerCase())}function ys(e,t,i,s,n){const r={platform:e,filename:t,function:"<anonymous>"===i?"?":i,in_app:ms(t)};return mt(s)||(r.lineno=s),mt(n)||(r.colno=n),r}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,Cs=/\((\S*)(?::(\d+))(?::(\d+))\)/,Es=(e,t)=>{const i=Ss.exec(e);if(i){const[,e,s,n]=i;return ys(t,e,"?",+s,+n)}const s=ws.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){const e=Cs.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,xs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ps=(e,t)=>{const i=ks.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){const e=xs.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)}},Ts=/\(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 Fs(e){for(let t=1;10>=t;t++){const i=e.length-2*t;if(0>i)break;let s=!0;for(let n=0;t>n;n++)if(!Is(e[i+n],e[i+t+n])){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=$s(e,t);s&&e.splice(i+s===e.length?i:t.start,s)}function As(e,t){let i=t.start;for(;i>0&&Is(e[i-1],e[i-1+t.length]);)i--;return t.start-i}function $s(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 Ms(e,t){const i=t[0];let s=e.length-(i?As(e,i):0);for(const i of t)s-=$s(e,i);return s}function Os(e,t,i){for(let s=0;e.length>s;s++){const n=e[(t+s)%e.length],r=e[(i+s)%e.length];if(n!==r)return r>n}return!1}var Ls=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const i=yt(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 It(e,"DOMException")}isDOMError(e){return It(e,"DOMError")}},Ds=class{match(e){return Ft(e)}coerce(e,t){var i;const s=this.getStack(e),n=void 0===s?null===(i=t.syntheticException)||void 0===i?void 0:i.stack:void 0,r=!!n;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:n,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}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!!It(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 yt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i;const s=e,n=null!==(t=s.lineno)&&void 0!==t?t:0,r=null!==(i=s.colno)&&void 0!==i?i:0;if(yt(s.filename)&&0!==s.filename.length&&0!==n)return`Error\n at ${s.filename}:${n}:${r}`}};const Bs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;var Us=class{match(e){return"string"==typeof e}coerce(e,t){var i;const[s,n]=this.getInfos(e);return{type:null!=s?s:"Error",value:null!=n?n: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 zs=["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]";let s="";for(const e of i){const i=s?`${s}, ${e}`:e;if(i.length>t)break;s=i}return s}var qs=class{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s;const n=this.getErrorPropertyFromObject(e);return n?t.apply(n):{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(Rt(e))return e.constructor.name;const t="name"in e?e.name:void 0;return yt(t)&&!bt(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 yt(e)&&!bt(e)&&zs.indexOf(e)>=0}getStack(e){try{return yt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:yt(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(Ft(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 Rt(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 Tt(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 It(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Rt(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 Tt(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",Ys=new Set([Gs,Ks]),Qs={enabled:!0,max_bytes:32768};function Js(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Qs.enabled,max_bytes:Xs(e.max_bytes,Qs.max_bytes)}:ls({},Qs)}var Zs=class{constructor(e){this._entries=[],this._totalBytes=0,this._config=Js(e)}setConfig(e){this._config=Js(e),this._trimToMaxBytes()}add(e){const t=function(e){let t;try{t=ut(e)}catch(e){return}try{const e=JSON.parse(t);if(!ft(e))return;const i=e,s=i[Gs],n=i[Ks];if(!yt(s)||0===s.trim().length)return;if(!yt(n)&&!Ct(n))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(!Ct(e)||1/0===e||-1/0===e)return t;const i=Math.floor(e);return 0>i?t:i}const en=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function tn(e){return"string"==typeof e||e}function sn(e){return"string"==typeof e?e:void 0}const nn=["$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","bfcid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],rn="NativeGzipValidationError",on=e=>e.length>=2&&31===e[0]&&139===e[1],an=(e,t)=>e===nt.GZipJS||t===nt.GZipJS||"gzip"===t,ln=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):"");let cn;const un=e=>{throw Xi(rn,`Native gzip produced invalid output: ${e}`)};let dn=0,hn=!1;const _n=function(){var e=Dt(function*(e,t){18>e.size&&un("too-short");const i=new Uint8Array(yield e.slice(0,10).arrayBuffer());on(i)&&8===i[2]||un("invalid-header");const s=new DataView(yield e.slice(e.size-8).arrayBuffer()),n=t.length>>>0;s.getUint32(4,!0)!==n&&un("invalid-size"),(hn||3>dn)&&(s.getUint32(0,!0)!==(e=>{const t=(()=>{if(cn)return cn;cn=[];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;cn[e]=t>>>0}return cn})();let i=4294967295;for(let s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&(hn=!0,un("invalid-crc")),dn++)});return function(t,i){return e.apply(this,arguments)}}();function pn(){return pn=Dt(function*(e,t=!0,i){try{const t=(new TextEncoder).encode(e),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),r=n.write(t).then(()=>n.close()).catch((s=Dt(function*(e){try{yield n.abort(e)}catch(e){}throw e}),function(e){return s.apply(this,arguments)})),o=new Response(i.readable).blob(),[a]=yield Promise.all([o,r]);return yield _n(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}),pn.apply(this,arguments)}function gn(e,t){if(null==e)return{};var i,s,n=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 r=Object.getOwnPropertySymbols(e);for(s=0;r.length>s;s++)t.includes(i=r[s])||{}.propertyIsEnumerable.call(e,i)&&(n[i]=e[i])}return n}const fn="[redacted]",vn=/^[A-Za-z0-9+/\n\r]+=*$/,mn=/^[A-Za-z0-9_-]+={0,2}$/,yn=/[-_]/,bn=/^data:[^,\s]*;base64,/i,Sn=/^[A-Za-z0-9+/_-]+={0,2}$/,wn=/\bph[a-z]_[A-Za-z0-9_-]{20,}\b/g,Cn=/^(authorization|cookie|set-cookie|x-api-key|api[-_]?key|api[-_]?token|access[-_]?token|refresh[-_]?token|token|password|secret|client[-_]?secret|private[-_]?key)$/i,En=/[a-z][a-z0-9+.-]{0,63}:[^\s<>"]+/gi,kn=/[\s<>"]/,xn=(()=>new RegExp(En.source,"i"))(),Pn=/[a-z][a-z0-9+.-]{0,63}:\/\//i,Tn=(()=>new RegExp(`^${Pn.source}`,"i"))(),In=(()=>new RegExp(Pn.source,"gi"))(),Fn=/(^|[-_./;])(auth|token|secret|password|passwd|pwd|credential|signature|sig|key|hmac|sas|bearer|jwt|session|sessionid)([-_./;]|$)/i,Rn=/^(code|AWSAccessKeyId|GoogleAccessId|Policy)$/i,An=/[\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]/g,$n=/[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g,Mn=/\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,On=/(^|[^\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,Ln=/\b\d{3}[ .-]\d{2}[ .-]\d{4}\b/g,Dn=/\d+/g,Nn=/(^|[^\w+])((?:\+?1[ ./-]?)?(?:\(\d{3}\)[ ./-]?|\d{3}[ ./-])\d{3}[ ./-]\d{4})(?![\w])/g,Bn=/(^|[^\w])(\+\d{1,3}(?:[ ./()-]{0,2}\d){7,13})(?![\w])/g;function Un(e){return function(e){return Cn.test(e)}(e)||Fn.test(e)||Rn.test(e)}function zn(e){return e.split("&",129).length>128}function Hn(e,t,i){return Un(e)||t.includes(";")&&function(e){return e.split(";").some(e=>Un(e.split("=",1)[0]))}(t)?fn:xn.test(t)?i?Kn(t,{allowNestedUrls:!1,stripPunctuation:!0}):fn:t}function qn(e,t){const i=new URLSearchParams;let s=!1,n=!1;for(const[r,o]of new URLSearchParams(e)){const e=Yn(r),a=Yn(o);s||(s=e!==r||a!==o);const l=Hn(e,a,t);s||(s=l!==a),n=Un(e)||l!==a,i.append(e,l)}return{changed:s,lastFieldSensitive:n,serialized:i.toString()}}function jn(e,t){if(!e.includes("="))return{value:Wn(e,t),lastFieldSensitive:!1};const i=qn(e,t);return{value:i.changed?i.serialized:e,lastFieldSensitive:i.lastFieldSensitive}}function Wn(e,t){return t?Kn(e,{allowNestedUrls:!1,stripPunctuation:!0}):xn.test(e)?fn:e}function Vn(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 Gn(e,t){var i;if(e.length>8192&&Tn.test(e))return fn;const{address:s,suffix:n}=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 r;try{r=new URL(s)}catch(e){return fn+n}const o=r.search.slice(1),a=""!==r.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)}}(r.hash);if(zn(o)||zn(l.head)||zn(null!==(i=l.tail)&&void 0!==i?i:""))return fn+n;let c=!1;(r.username||r.password)&&(r.username=fn,r.password="",c=!0);const u=qn(o,t.allowNestedUrls);u.changed&&(r.search=u.serialized,c=!0);const d=jn(l.head,t.allowNestedUrls),h=null===l.tail?null:(_=l.tail,d.lastFieldSensitive?{value:""===_?"":fn,lastFieldSensitive:!0}:jn(_,t.allowNestedUrls));var _;const p=null===h?d.value:`${d.value}?${h.value}`;p!==r.hash.slice(1)&&(r.hash=p,c=!0);const g=a?null!=h?h:d:u;return(c?Yn(r.toString()):s)+(g.lastFieldSensitive?"":n)}function Kn(e,t){return e.replace(En,i=>function(e,t){const i=function(e){if(!e.includes("://"))return[];const t=[...e.matchAll(In)].map(e=>e.index),i=[],s={query:!1,fragment:!1,fragmentQuery:!1};let n=0,r=!1,o="";for(let a=0;e.length>a&&t.length>n;a++){t[n]===a&&(a>0&&"="!==o&&i.push(a),n++);const l=e[a];Vn(l,s,o)?(o=l,r=!0):r&&"=&".includes(l)&&(o=l)}return i}(e);if(0===i.length)return Gn(e,t);let s="",n=0;for(const r of i)s+=Gn(e.slice(n,r),ls(ls({},t),{},{stripPunctuation:!1})),n=r;return s+Gn(e.slice(n),t)}(i,ls(ls({},t),{},{stripPunctuation:t.stripPunctuation&&i.length!==e.length})))}function Yn(e){return e.replace(wn,fn)}function Qn(e,t){return function(e){return e.length>=10240&&(vn.test(e)||function(e){const t=bn.exec(e);if(!t)return!1;let i;try{i=decodeURIComponent(e.slice(t[0].length))}catch(e){return!1}return Sn.test(i.replace(/[\r\n]/g,""))}(e)||yn.test(e)&&mn.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 n=t(e.slice(0,function(e,t){let i=t;for(;i>0&&!kn.test(e[i-1]);)i--;return i}(e,s)));if(n.length>=2*i.maxStringLength)return n+i.truncationSuffix}return t(e)}(e,e=>function(e){return Kn(e,{allowNestedUrls:!0,stripPunctuation:!0})}(function(e){let t=e.replace(An," ");return t=t.replace($n,fn),t=t.replace(Mn,fn),t=t.replace(On,`$1${fn}`),t=function(e){let t="",i=0;for(let s=tr(e,0);null!==s;s=tr(e,s[1]))t+=e.slice(i,s[0])+ir(e.slice(s[0],s[1])),i=s[1];return t+e.slice(i)}(t),t=t.replace(Ln,fn),t=t.replace(Nn,`$1${fn}`),t=t.replace(Bn,`$1${fn}`),t}(Yn(e))),t)}function Jn(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let n=e.charCodeAt(s)-48;if(0>n||n>9)return!1;i&&(n*=2,n>9&&(n-=9)),t+=n,i=!i}return t%10==0}function Zn(e,t){const i=e.charCodeAt(t);return i>=48&&57>=i}function Xn(e,t){const i=e.charCodeAt(t);return Zn(e,t)||95===i||i>=65&&90>=i||i>=97&&122>=i}function er(e,t){let i=t;for(;Zn(e,i);)i++;return i}function tr(e,t){for(let i=t;e.length>i;i++){if(!Zn(e,i)||Xn(e,i-1))continue;let t=0,s=-1,n=i;for(;;){const i=er(e,n);if(t+=i-n,13>t||Xn(e,i)||(s=i),n=i+1,!" ./-".includes(e.charAt(i))||!Zn(e,n))break}if(s>=0)return[i,s];i=n-1}return null}function ir(e){const t=[];for(let i=Dn.exec(e);null!==i;i=Dn.exec(e))t.push({digits:i[0],start:i.index,end:i.index+i[0].length});let i="",s=0,n=0;for(;t.length>n;){let r="",o=-1;for(let e=n;t.length>e&&(r+=t[e].digits,19>=r.length);e++)r.length>=13&&Jn(r)&&(o=e);0>o?n++:(i+=e.slice(s,t[n].start)+fn,s=t[o].end,n=o+1)}return i+e.slice(s)}const sr={}.propertyIsEnumerable;function nr(e,t){try{return ar(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch(e){return[]}}function rr(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:Wi};if(i.remainingNodes--,kt(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 n=e.toJSON;if("function"==typeof n)return rr(n.call(e),t,i,s+1)}catch(e){}return pt(e)?{arrayValue:{values:or(e,t,i,s+1)}}:{kvlistValue:{values:ar(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Gi(String(e))}}function or(e,t,i,s){const n=[],r=Math.min(e.length,1e3);let o=0;for(;r>o&&i.remainingNodes>0;o++)try{const r=o in e?e[o]:void 0;if(wt(r))continue;n.push(rr(r,t,i,s))}catch(e){n.push({stringValue:Vi})}return e.length>o&&n.push({stringValue:Wi}),n}function ar(e,t,i,s){const n=[];for(const r in e)if(sr.call(e,r)){if(!r){null==t||t.debug("Dropping an attribute with an empty key");continue}if(n.length>=1e3||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[r];if(St(o)||mt(o))continue;n.push({key:Gi(r),value:rr(o,t,i,s)})}catch(e){n.push({key:Gi(r),value:{stringValue:Vi}})}}return n}function lr(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 cr=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function ur(e,t){const i=Ki({},e),s={};for(const e of cr)({}).hasOwnProperty.call(i,e)&&(s[e]=i[e],delete i[e]);return[...nr(i,t),...nr(s,t)]}const dr={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 hr={text:"INFO",number:9},_r={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:hr,warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}};function pr(e){try{return Gi(String(e))}catch(e){return Vi}}function gr(e,t,i,s){const n=e.level||"info",{text:r,number:o}=_r[n]||hr,a=function(e=Date.now()){return String(e)+"000000"}(Ct(s)?s:void 0),l={};t.distinctId&&(l.posthogDistinctId=t.distinctId),t.sessionId&&(l.sessionId=t.sessionId),t.windowId&&(l["window.id"]=t.windowId),wt(t.sessionStartTimestamp)||(l.sessionStartTimestamp=String(t.sessionStartTimestamp)),wt(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:r,body:{stringValue:pr(e.body)},attributes:nr(c,i)};return e.trace_id&&(d.traceId=e.trace_id),e.span_id&&(d.spanId=e.span_id),mt(e.trace_flags)||(d.flags=e.trace_flags),d}function fr(e,t,i){return lr(e,t,i)}function vr(e,t,i,s){return{resourceLogs:[{resource:{attributes:ur(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}var mr=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 yr(){return.75+.5*Math.random()}function br(e,t,i,s){const n=Math.min(Math.max(0,t-1),6),r=e*Math.pow(2,n);return Math.round((void 0===s?r:Math.min(r,Math.max(s,e)))*i)}var Sr=class{constructor(e,t,i,s,n,r=()=>Promise.resolve(),o,a=()=>!1){var l;this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=n,this._waitForStoragePersist=r,this._scopeName=o,this._isConsentWithdrawn=a,this._flushTimer=new mr(()=>this._flushInBackground()),this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._backgroundFlushPromise=null,this._retryAfter=new Qi,this._consecutiveFlushFailures=0,this._flushJitter=1,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(l=t.maxQueueSize)&&void 0!==l?l: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(st.LogsQueue,[])}get throttled(){return this._retryAfter.isOpen()}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 n={record:gr(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(n))}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=pt(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 Dt(function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally(()=>{e._flushPromise=null})),e._flushPromise})()}_flushInner(){var e=this;return Dt(function*(){var t;if(e._flushTimer.clear(),e._discardQueueIfConsentWithdrawn())return;let i=null!==(t=e._instance.getPersistedProperty(st.LogsQueue))&&void 0!==t?t:[];if(0===i.length)return;const s=i.length;let n=0;for(;i.length>0&&s>n;){var r,o;if(e._discardQueueIfConsentWithdrawn())return;const t=e._queueGeneration;e._evictedSinceAdvance=0;const s=Math.min(i.length,e._maxBatchRecordsPerPost),a=i.slice(0,s),l=vr(a.map(e=>e.record),e._buildResourceAttributes(),null!==(r=e._scopeName)&&void 0!==r?r: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(st.LogsQueue))&&void 0!==o?o:[],n+=a.length,"fatal"===c.kind)throw c.error}}})()}_discardQueueIfConsentWithdrawn(){return!!this._isConsentWithdrawn()&&(this._hasQueuedRecords()&&this.clearQueue(),!0)}_persistQueueAdvance(e){var t=this;return Dt(function*(){var i;const s=Math.max(0,e-t._evictedSinceAdvance),n=null!==(i=t._instance.getPersistedProperty(st.LogsQueue))&&void 0!==i?i:[];t._instance.setPersistedProperty(st.LogsQueue,n.slice(s)),yield t._waitForStoragePersist()})()}_buildResourceAttributes(){return fr(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(this._instance.optedOut)return;const i=null!==(t=this._instance.getPersistedProperty(st.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(st.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(br(this._flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_hasQueuedRecords(){const e=this._instance.getPersistedProperty(st.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Dt(function*(){t._flushTimer.clear();const i=t.flush().catch(()=>{});void 0!==e?yield ss(i,e):yield i})()}flushWithTimeout(e){var t=this;return Dt(function*(){const i=t.flush();yield ss(i,e,()=>{i.catch(()=>{})})})()}flushInBackground(){if(this._backgroundFlushPromise)return this._backgroundFlushPromise;const e=this.flush().then(()=>{this._consecutiveFlushFailures=0,this._flushJitter=1},e=>{this._consecutiveFlushFailures++,this._flushJitter=yr(),this._logger.error("PostHog logs flush failed:",e)}).finally(()=>{this._backgroundFlushPromise===e&&(this._backgroundFlushPromise=null),!this._instance.isDisabled&&this._hasQueuedRecords()&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())});return this._backgroundFlushPromise=e,e}_flushInBackground(){this.flushInBackground()}};const wr=/^[0-9a-f]+$/;function Cr(e,t,i){return"string"==typeof e&&e.length===t&&e!==i&&wr.test(e)}const Er=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;const kr="00",xr=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Pr(e){return String(e)+"000000"}function Tr(e,t,i,s){let n="";return s&&(n=Object.keys(s).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(s[e])}`).join(",")),`${e}\0${t}\0${null!=i?i:""}\0${n}`}var Ir=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushTimer=new mr(()=>this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})),this._flushPromise=null,this._queuedFlush=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new Qi,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,bounds:pt(null==i?void 0:i.bounds)?i.bounds.slice():null==i?void 0:i.bounds})}flush(){var e=this;const t=this._flushPromise,i=function(){var i=Dt(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}flushCoalesced(){var e,t;return this._isBackingOff()?null!==(e=this._flushPromise)&&void 0!==e?e:Promise.resolve():(this._queuedFlush||(this._queuedFlush=(null!==(t=this._flushPromise)&&void 0!==t?t:Promise.resolve()).catch(()=>{}).then(()=>(this._queuedFlush=null,this._isBackingOff()?void 0:this.flush()))),this._queuedFlush)}_isBackingOff(){return this._consecutiveFlushFailures>0||this._retryAfter.remainingMs()>0}drainWindow(){if(0===this._series.size)return null;const e=this._series;return this._startWindow(),this._buildPayload(e)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._queuedFlush=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=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&&"gauge"!==t.type&&"histogram"!==t.type)return void this._logger.warn(`Dropping metric '${t.name}': unknown type '${String(t.type)}'`);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=Tr(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 n,r=this._series.get(s);if(!r&&!this._admitNewSeries())return;if("histogram"===t.type&&(n=this._histogramBounds(t.name,t.unit,t.bounds),!n))return;r||(r={name:t.name,type:t.type,unit:t.unit,attributes:i,windowStartMs:Date.now(),hist:n&&Rr(n)},this._series.set(s,r));const o=this._typeByName.get(t.name);void 0===o?this._typeByName.set(t.name,t.type):o===t.type||this._typeCollisionWarned.has(t.name)||(this._typeCollisionWarned.add(t.name),this._logger.warn(`Metric name '${t.name}' is already used as a ${o}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this._fold(r,t.value);const a=this._activeTraceContext();a&&(r.exemplar=ls(ls({},a),{},{value:t.value,timeMs:Date.now()})),this._armFlushTimer()}_activeTraceContext(){try{var e,t;const i=function(e){const t=function(e){if("string"!=typeof e)return;const t=Er.exec(e.trim());if(!t)return;const[,i,s,n,r,o]=t;return"ff"===i||"00"===i&&o||!function(e){return Cr(e,32,"00000000000000000000000000000000")}(s)||!function(e){return Cr(e,16,"0000000000000000")}(n)?void 0:{version:i,traceId:s,spanId:n,flags:r}}(e);return t&&{traceId:t.traceId,spanId:t.spanId,flags:(i=t.flags,1&parseInt(i,16)?"01":kr)};var i}(null===(e=(t=this._instance).getActiveSpan)||void 0===e||null===(e=e.call(t))||void 0===e?void 0:e.traceparent());if(i&&"01"===i.flags)return{traceId:i.traceId,spanId:i.spanId}}catch(e){}}_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)}_histogramBounds(e,t,i){if(void 0!==i&&!function(e){if(!pt(e)||0===e.length)return!1;for(let t=0;e.length>t;t++)if(!Number.isFinite(e[t])||t>0&&e[t-1]>=e[t])return!1;return!0}(i))return void this._logger.warn(`Dropping histogram '${e}': bounds must be a non-empty array of finite, strictly increasing numbers`);const s=Tr("histogram",e,t,void 0),n=this._boundsByHistogram.get(s);if(n)return this._warnOnBoundsConflict(e,s,n,i),n;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),i&&!Fr(i,xr))return;return xr}const r=i?i.slice():xr;return this._boundsByHistogram.set(s,r),r}_warnOnBoundsConflict(e,t,i,s){Fr(i,null!=s?s:xr)||this._boundsConflictWarned.has(t)||(this._boundsConflictWarned.add(t),this._logger.warn(`Histogram '${e}' already uses the bounds [${i.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_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":{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,i.bounds)]+=1;break}}}_runBeforeSend(e){const t=this._config.beforeSend;if(!t)return e;const i=pt(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(br(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}_doFlush(){var e=this;return Dt(function*(){if(e._flushTimer.clear(),0===e._series.size)return;const t=e._series;e._startWindow();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=yr()):(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 lr(e,t,i)}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),s=this._instance.getLibraryId(),n=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:ur(i)},scopeMetrics:[{scope:{name:s,version:n},metrics:t}]}]};var t,i,s,n}_buildMetrics(e){const t=Pr(Date.now()),i=new Map;for(const o of e.values()){var s;const e=Tr(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=nr(null!==(s=o.attributes)&&void 0!==s?s:{},this._logger),c=Pr(o.windowStartMs),u=Ar(o.exemplar);if("count"===o.type){var n;const e=ls({attributes:l,startTimeUnixNano:c,timeUnixNano:t,asDouble:null!==(n=o.total)&&void 0!==n?n:0},u);a.sum.dataPoints.push(e)}else if("gauge"===o.type){var r;const e=ls({attributes:l,timeUnixNano:t,asDouble:null!==(r=o.last)&&void 0!==r?r:0},u);a.gauge.dataPoints.push(e)}else{const e=o.hist,i=ls({attributes:l,startTimeUnixNano:c,timeUnixNano:t,count:e.count,sum:e.sum,min:e.min,max:e.max,bucketCounts:e.bucketCounts,explicitBounds:e.bounds},u);a.histogram.dataPoints.push(i)}}return Array.from(i.values())}_mergeWindowBack(e){for(const[n,r]of e){var t;const e=this._series.get(n);if(e)switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.exemplar=null!==(t=e.exemplar)&&void 0!==t?t:r.exemplar,e.type){case"count":var i,s;e.total=(null!==(i=e.total)&&void 0!==i?i:0)+(null!==(s=r.total)&&void 0!==s?s:0);break;case"gauge":break;case"histogram":{const t=e.hist,i=r.hist;t.count+=i.count,t.sum+=i.sum,t.min=Math.min(t.min,i.min),t.max=Math.max(t.max,i.max);for(let e=0;t.bucketCounts.length>e;e++)t.bucketCounts[e]+=i.bucketCounts[e];break}}else this._admitNewSeries()&&this._series.set(n,r)}}};function Fr(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;e.length>i;i++)if(e[i]!==t[i])return!1;return!0}function Rr(e){return{bounds:e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:new Array(e.length+1).fill(0)}}function Ar(e){return e?{exemplars:[{filteredAttributes:[],timeUnixNano:Pr(e.timeMs),asDouble:e.value,traceId:e.traceId,spanId:e.spanId}]}:{}}const $r=(e,{debugEnabled:i}={})=>{const s={_log(s,...n){let r;try{r=typeof window>"u"?void 0:window}catch(e){return}r&&(t.DEBUG||r.POSTHOG_DEBUG||i)&&!mt(r.console)&&r.console&&("__rrweb_original__"in r.console[s]?r.console[s].__rrweb_original__:r.console[s])(e,...n)},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)=>$r(`${e} ${t}`,i)};return s},Mr=$r("[PostHog.js]"),Or=(e,t)=>Mr.createLogger(e,t);function Lr(e,t){pt(e)&&e.forEach(t)}function Dr(e,t){if(!wt(e))if(pt(e))e.forEach(t);else if((e=>e instanceof FormData)(e))e.forEach((e,i)=>t(e,i));else for(const i in e)ht.call(e,i)&&t(e[i],i)}const Nr=function(e,...t){for(const i of t)for(const t in i)void 0!==i[t]&&(e[t]=i[t]);return e};function Br(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 Ur=function(e){return function(...t){try{return e.apply(this,t)}catch(e){Mr.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Mr.critical(e)}}},zr=function(e){const t={};return Dr(e,function(e,i){(yt(e)&&e.length>0||Ct(e))&&(t[i]=e)}),t};function Hr(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 qr=["herokuapp.com","vercel.app","netlify.app"];function jr(e){const t=null==e?void 0:e.hostname;if(!yt(t))return!1;const i=t.split(".").slice(-2).join(".");for(const e of qr)if(i===e)return!1;return!0}function Wr(e,t,i,s){const{capture:n=!1,passive:r=!0}=null!=s?s:{};null==e||e.addEventListener(t,i,{capture:n,passive:r})}function Vr(e){return"ph_toolbar_internal"===e.name}const Gr=e=>{if(o){try{const t=e+"=",i=o.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}};var Kr=class e{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,i,s,n){if(!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||!Number.isInteger(n)||0>t||0>i||0>s||0>n||t>0xffffffffffff||i>4095||s>1073741823||n>4294967295)throw new RangeError("invalid field value");const r=new Uint8Array(16);return r[0]=t/Math.pow(2,40),r[1]=t/Math.pow(2,32),r[2]=t/Math.pow(2,24),r[3]=t/Math.pow(2,16),r[4]=t/256,r[5]=t,r[6]=112|i>>>8,r[7]=i,r[8]=128|s>>>24,r[9]=s>>>16,r[10]=s>>>8,r[11]=s,r[12]=n>>>24,r[13]=n>>>16,r[14]=n>>>8,r[15]=n,new e(r)}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}},Yr=class{generate(){const e=this.generateOrAbort();if(!mt(e))return e;{this._timestamp=0;const e=this.generateOrAbort();if(mt(e))throw new Error("Could not generate UUID after timestamp reset");return e}}generateOrAbort(){const e=(()=>{const e=Date.now();return Ct(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 Kr.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 Zr}};const Qr=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};let Jr;var Zr=class{nextUint32(){var e;return this._buffer.length>this._cursor||((null!==(e=Jr)&&void 0!==e?e:Jr="u">typeof window&&!mt(window.crypto)&&crypto.getRandomValues?e=>{try{return crypto.getRandomValues(e)}catch(t){return Qr(e)}}:Qr)(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}};let Xr;const eo=()=>to().toString(),to=()=>(Xr||(Xr=new Yr)).generate();let io="";const so=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;let no=null;const ro={_is_supported(){if(!St(no))return no;if(no=!1,o)try{const e=`__ph_cookie_support_${eo()}`;ro._set(e,"xyz"),no='"xyz"'===Gr(e),ro._remove(e)}catch(e){no=!1}return no},_error(e){Mr.error("cookieStore error: "+e)},_get:Gr,_parse(e){let t;try{t=JSON.parse(ro._get(e))||{}}catch(e){}return t},_set(e,t,i,s,n){if(!o)return!1;try{let r="",a="";const l=function(e,t){if(t){let t=function(e,t=o){if(io)return io;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";const i=e.split(".");let s=Math.min(i.length,8);const n="dmn_chk_"+eo();for(;!io&&s--;){const e=i.slice(s).join("."),r=n+"=1;domain=."+e+";path=/";t.cookie=r+";max-age=3",t.cookie.includes(n)&&(t.cookie=r+";max-age=0",io=e)}return io}(e);if(!t){const i=(e=>{const t=e.match(so);return t?t[0]:""})(e);i!==t&&Mr.info("Warning: cookie subdomain discovery mismatch",i,t),t=i}return t?"; domain=."+t:""}return""}(o.location.hostname,s);if(i){const e=new Date;e.setTime(e.getTime()+864e5*i),r="; expires="+e.toUTCString()}n&&(a="; secure");const c=e+"="+encodeURIComponent(JSON.stringify(t))+r+"; SameSite=Lax; path=/"+l+a;return c.length>3686.4&&Mr.warn("cookieStore warning: large cookie, len="+c.length),o.cookie=c,!0}catch(e){return!1}},_remove(e,t){if((null==o?void 0:o.cookie)&&(!t||!St(Gr(e))))try{ro._set(e,"",-1,t)}catch(e){return}}};let oo=null;const ao={_is_supported(){if(!St(oo))return oo;let e=!0;if(mt(s))e=!1;else try{const t="__mplssupport__";ao._set(t,"xyz"),'"xyz"'!==ao._get(t)&&(e=!1),ao._remove(t)}catch(t){e=!1}return e||Mr.error("localStorage unsupported; falling back to cookie store"),oo=e,e},_error(e){Mr.error("localStorage error: "+e)},_get(e){try{return null==s?void 0:s.localStorage.getItem(e)}catch(e){ao._error(e)}return null},_parse(e){try{return JSON.parse(ao._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==s||s.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){ao._error(e)}return!1},_remove(e){try{null==s||s.localStorage.removeItem(e)}catch(e){ao._error(e)}}},lo=[k,v,C,m,T,S,b,y,x],co=[H,z,_e,pe,Me,$e,G,Te],uo=e=>e+"_cpm",ho=["__proto__","constructor","prototype"],_o=e=>{if(!ft(e))return{};const t={};return Object.keys(e).forEach(i=>{-1===ho.indexOf(i)&&(t[i]=e[i])}),t},po=(e,t=[])=>{const i={};return[...co,...t].forEach(t=>{const s=e[t];mt(s)||St(s)||""===s||(i[t]=s)}),i},go=e=>{let t=5381,i=2166136261;for(let s=0;e.length>s;s++){const n=e.charCodeAt(s);t=33*t^n,i=Math.imul(i^n,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},fo=(e,t)=>({p:t,f:go(JSON.stringify(e))}),vo=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const i=ro._parse(uo(e)),s=(null==i?void 0:i.f)===go(t)&&pt(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},mo=(e,t)=>t+"|"+(ro._get(uo(e))||""),yo={},bo={_is_supported:()=>!0,_error(e){Mr.error("memoryStorage error: "+e)},_get:e=>e in yo?yo[e]:null,_parse:e=>e in yo?yo[e]:null,_set:(e,t)=>(yo[e]=t,!0),_remove(e){delete yo[e]}};let So=null;const wo={_is_supported(){if(!St(So))return So;if(So=!0,mt(s))So=!1;else try{const e="__support__";wo._set(e,"xyz"),'"xyz"'!==wo._get(e)&&(So=!1),wo._remove(e)}catch(e){So=!1}return So},_error(e){Mr.error("sessionStorage error: ",e)},_get(e){try{return null==s?void 0:s.sessionStorage.getItem(e)}catch(e){wo._error(e)}return null},_parse(e){try{return JSON.parse(wo._get(e))||null}catch(e){}return null},_set(e,t){try{return null==s||s.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){wo._error(e)}return!1},_remove(e){try{null==s||s.sessionStorage.removeItem(e)}catch(e){wo._error(e)}}};var Co=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:at(Ot,e)?0:-1}get _storage(){const e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?ao:ro,i=t._is_supported()?t:bo;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;const t="localStorage"===e?ro:ao;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==r?void 0:r.doNotTrack,null==r?void 0:r.msDoNotTrack,p.doNotTrack,null==r?void 0:r.globalPrivacyControl].some(e=>Mt(e))}};function Eo(e,t){var i;const s=null==e||null===(i=e.config)||void 0===i?void 0:i.get_current_url;if(!gt(s))return t;try{const e=s(t);return yt(e)&&e?e:t}catch(e){return Mr.error("Error in get_current_url, falling back to window.location.href",e),t}}function ko(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 xo(e){return!!e&&1===e.nodeType}function Po(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function To(e){return!!e&&3===e.nodeType}function Io(e){return!!e&&11===e.nodeType&&xo(e.host)}function Fo(e){return e?lt(e).split(/\s+/):[]}function Ro(e,t){const i=function(e){var t;const i=typeof window>"u"?void 0:window,s=null==i||null===(t=i.location)||void 0===t?void 0:t.href;return mt(s)?void 0:Eo(e,s)}(t);return!!(i&&e&&e.some(e=>i.match(e)))}function Ao(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 Fo(t)}function $o(e){return wt(e)?null:lt(e).split(/(\s+)/).filter(e=>ua(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Mo(e){let t="";return ta(e)&&!ia(e)&&e.childNodes&&e.childNodes.length&&Dr(e.childNodes,function(e){var i;To(e)&&e.textContent&&(t+=null!==(i=$o(e.textContent))&&void 0!==i?i:"")}),lt(t)}function Oo(e){var t;return mt(e.target)?e.srcElement||null:(null===(t=e.target)||void 0===t?void 0:t.shadowRoot)?e.composedPath()[0]||null:e.target||null}const Lo=["a","button","form","input","select","textarea","label"];function Do(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 No(e,t){if(mt(t))return!0;for(const i of e)if(t.some(e=>Do(i,e)))return!0;return!1}function Bo(e){const t=e.parentNode;return!(!t||!xo(t))&&t}const Uo=[".ph-no-autocapture","[data-ph-no-autocapture]"],zo=["next","previous","prev",">","<","→","←","›","‹","»","«","▶","◀","❯","❮"],Ho=(()=>[...zo,"+","-","−","–"])(),qo=(()=>Ho.length+10)(),jo=["button","a","input","select","textarea","label"],Wo=["button","link","tab","menuitem","option"],Vo=(e,t)=>/[a-z0-9]/i.test(t)?at(Ho,t)?new RegExp(`\\b${t}\\b`).test(e):e.includes(t):e===t,Go=e=>at(jo,e.tagName.toLowerCase())||at(Wo,(e.getAttribute("role")||"").toLowerCase());function Ko(e){let t="",i="";const s=e=>{xo(e)&&ta(e)&&!ia(e)&&(t+=` ${Mo(e)}`,i=i||e.getAttribute("aria-label")||"",Dr(e.childNodes,s))};s(e),t=lt(t.replace(/\s+/g," "));const n=(ua(t)?t:"").toLowerCase(),r=e.getAttribute("aria-label")||(n?"":i);return{safeText:n,ariaLabel:lt(r).toLowerCase()}}const Yo=[".ph-no-rageclick",".ph-no-capture"],Qo=["","text","search","email","password","url","tel","number"];function Jo(e,t){if(!(typeof window>"u"?void 0:window)||Zo(e))return!1;let i,s,n;var r,o;if(kt(t)?(i=!!t&&Yo,s=void 0,n=!1):(i=null!==(r=null==t?void 0:t.css_selector_ignorelist)&&void 0!==r?r:Yo,s=null==t?void 0:t.content_ignorelist,n=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(n&&function(e){return!(!e||!xo(e))&&(!!Po(e,"textarea")||(Po(e,"input")?at(Qo,(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,isComplete:l}=Xo(e,!1);return!(!l||s&&function(e,{safeText:t,ariaLabel:i}){let s;if(!0===e)s=zo;else{if(!pt(e))return!1;if(e.length>qo)return Mr.error(`[PostHog] content_ignorelist array cannot exceed ${qo} items. Use css_selector_ignorelist for more complex matching.`),!1;s=e.map(e=>e.toLowerCase())}return s.some(e=>Vo(t,e)||Vo(i,e))}(s,function(e,t){for(const e of t)if(Go(e))return Ko(e);for(const e of t){try{var i;if("pointer"!==(null===(i=window)||void 0===i?void 0:i.getComputedStyle(e).getPropertyValue("cursor")))break}catch(e){break}const t=Ko(e);if(t.safeText||t.ariaLabel)return t}return Ko(e)}(e,a))||No(a,i))}const Zo=e=>!e||Po(e,"html")||!xo(e),Xo=(e,t)=>{const i=typeof window>"u"?void 0:window;if(!i||Zo(e))return{parentIsUsefulElement:!1,targetElementList:[],isComplete:!1};let s=!1;const n=[e];let r=e;const o=new Set([e]);for(;!Po(r,"body");){const e=r.assignedSlot||r.parentNode,a=Io(e)?e.host:e&&xo(e)?e:null;if(!a)break;if(o.has(a)||o.size>=1e3)return{parentIsUsefulElement:s,targetElementList:n,isComplete:!1};if(o.add(a),Io(e))n.push(a),r=a;else{if(t||Lo.indexOf(a.tagName.toLowerCase())>-1)s=!0;else try{const e=i.getComputedStyle(a);e&&"pointer"===e.getPropertyValue("cursor")&&(s=!0)}catch(e){}n.push(a),r=a}}return{parentIsUsefulElement:s,targetElementList:n,isComplete:!0}};function ea(e){const t=new Set;let i=0,s=e;for(;s;){if(i++>=1e3||t.has(s))return!0;t.add(s);const e=Ao(s);if(at(e,"ph-sensitive")||at(e,"ph-no-capture"))return!0;const n=s.assignedSlot||s.parentNode;s=Io(n)?n.host:n&&xo(n)?n:null}return!1}function ta(e){if(ea(e))return!1;if(at(Ao(e),"ph-include"))return!0;const t=e.type||"";if(yt(t))switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=e.name||e.id||"";return!yt(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function ia(e){return!!(Po(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Po(e,"select")||Po(e,"textarea")||"true"===e.getAttribute("contenteditable"))}const sa=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}))$"),na=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,ra=[16,15,14,13],oa=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),aa=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),la=/[0-9A-Za-z_]/;function ca(e){let t=0,i=!1;for(let s=e.length-1;s>=0;s--){let n=e.charCodeAt(s)-48;i&&(n*=2,n>9&&(n-=9)),t+=n,i=!i}return t%10==0}function ua(e,t=!0){if(wt(e))return!1;if(yt(e)){if(e=lt(e),t?sa.test((e||"").replace(/[- ]/g,"")):function(e){let t;for(na.lastIndex=0;t=na.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 ra){const s=e+t;if(i.length>=s){const t=i.slice(e,s);if(sa.test(t)&&ca(t))return!0}}}return!1}(e))return!1;if(t?oa.test(e):function(e){let t;for(aa.lastIndex=0;t=aa.exec(e);){const e=t[1],i=t[3];if(!(e&&i&&la.test(e)&&la.test(i)))return!0}return!1}(e))return!1}return!0}function da(e){let t=Mo(e);return t=`${t} ${ha(e)}`.trim(),ua(t)?t:""}function ha(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Dr(e.childNodes,function(e){var i;if(e&&"span"===(null===(i=e.tagName)||void 0===i?void 0:i.toLowerCase()))try{const i=Mo(e);t=`${t} ${i}`.trim(),e.childNodes&&e.childNodes.length&&(t=`${t} ${ha(e)}`.trim())}catch(e){Mr.error("[AutoCapture]",e)}}),t}function _a(e){return e.replace(/"|\\"/g,'\\"')}function pa(e){const t=e.attr__class;if(t)return pt(t)?t:Fo(t)}const ga=Or("[Dead Clicks]"),fa=()=>!0,va=e=>{var t;const i=!!(null===(t=e.instance.persistence)||void 0===t?void 0:t.get_property(ie)),s=e.instance.config.capture_dead_clicks;return kt(s)?s:!!ft(s)||i};var ma=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({[ie]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript(()=>{this._start()}):this.stop()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.initDeadClicksAutocapture)?e():null===(i=g(this.instance))||void 0===i||i(this.instance,"dead-clicks-autocapture",t=>{t?ga.error("failed to load script",t):e()})}_start(){var e;if(o){if(!this._lazyLoadedDeadClicksAutocapture&&(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.initDeadClicksAutocapture)){const e=ft(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=p.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,e),this._lazyLoadedDeadClicksAutocapture.start(o),ga.info("starting...")}}else ga.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,ga.info("stopping..."))}};const ya=Or("[SegmentIntegration]");function ba(e,t,i=!0){const s=e.config.segment;if(!s)return t();const{analytics:n,filterProperties:r}=(e=>gt(e.register))(o=s)?{analytics:o}:o;var o;!function(e,t,i,s){const n=t=>{const n=()=>t.anonymousId()||eo();e.config.get_device_id=n,s&&t.id()&&(e.register({distinct_id:t.id(),$device_id:n()}),e.persistence.set_property(Te,Qe)),i(s?void 0:t.anonymousId()||void 0)},r=t.user();"then"in r&&gt(r.then)?r.then(n):n(r)}(e,n,i=>{n.register(((e,t,{filterProperties:i}={})=>{"undefined"!=typeof Promise&&Promise.resolve||ya.warn("This browser does not have Promise support, and can not use the segment integration");const s=(s,n)=>{if(!n)return s;const r=!!t&&s.event.anonymousId===t&&!s.event.userId;r||s.event.userId||s.event.anonymousId===e.get_distinct_id()||(ya.info("No userId set, resetting PostHog"),e.reset()),r||(t=void 0),s.event.userId&&s.event.userId!==e.get_distinct_id()&&(ya.info("UserId set, identifying with PostHog"),e.identify(s.event.userId));let o=e.calculateEventProperties(n,s.event.properties);if(!wt(i)){const e=s.event.properties||{},t={};for(const i of Object.keys(o))ht.call(e,i)||(t[i]=o[i]);const n=((e,t)=>{const i=pt(e)?e:[e];let s=ls({},t);for(const e of i)try{if(s=e(s),wt(s))return null}catch(e){return ya.error("Error in Segment filterProperties:",e),null}return s})(i,t);if(wt(n))return s;o=n}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,Xe)},identify(e){return s(e,tt)},screen(e){return s(e,"$screen")}}})(e,i,{filterProperties:r})).then(()=>{t()},e=>{ya.error("Failed to register the Segment integration",e),t()})},i)}const Sa="posthog-js";function wa(e,{organization:t,projectId:i,prefix:s,severityAllowList:n=["error"],sendExceptionsToPostHog:r=!0}={}){return o=>{var a,l,c,u,d;if("*"!==n&&!n.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 f;return t&&i&&(g.$sentry_url=(s||"https://sentry.io/organizations/")+t+"/issues/?project="+i+"&query="+o.event_id),r&&(null===(f=e.exceptions)||void 0===f||f.sendExceptionEvent(g)),o}}var Ca=class{constructor(e,t,i,s,n,r){this.name=Sa,this.setupOnce=function(o){o(wa(e,{organization:t,projectId:i,prefix:s,severityAllowList:n,sendExceptionsToPostHog:null==r||r}))}}},Ea=class{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(Mr.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 n=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==s?void 0:s.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}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 n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:e,lastScrollY:t,maxScrollY:i,maxContentHeight:r,lastContentY:o,maxContentY:a}=n;if(!(mt(e)||mt(t)||mt(i)||mt(r)||mt(o)||mt(a))){e=Math.ceil(e),t=Math.ceil(t),i=Math.ceil(i),r=Math.ceil(r),o=Math.ceil(o),a=Math.ceil(a);const n=e>1?zt(t/e,0,1,Mr):1,l=e>1?zt(i/e,0,1,Mr):1,c=r>1?zt(o/r,0,1,Mr):1,u=r>1?zt(a/r,0,1,Mr):1;s=Nr(s,{$prev_pageview_last_scroll:t,$prev_pageview_last_scroll_percentage:n,$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 ka=["flags","surveys"],xa={[U]:{exposure:"hidden"},[j]:{exposure:"hidden"},[W]:{exposure:"hidden"},[Q]:{exposure:"hidden"},[G]:{exposure:"hidden"},[Y]:{exposure:"hidden"},[A]:{exposure:"event"},[J]:{exposure:"hidden"},[ne]:{exposure:"hidden"},[Z]:{exposure:"event"},[X]:{exposure:"hidden"},[ee]:{exposure:"event"},[te]:{exposure:"event"},[ie]:{exposure:"event"},[se]:{exposure:"hidden"},[re]:{exposure:"event"},[oe]:{exposure:"hidden"},[ae]:{exposure:"hidden"},[_e]:{exposure:"hidden"},[pe]:{exposure:"event"},[le]:{exposure:"event",shouldSkipFromEventProperties:e=>St(e)},[ge]:{exposure:"event"},[fe]:{exposure:"event"},[ve]:{exposure:"event"},[me]:{exposure:"event"},[ye]:{exposure:"hidden"},[C]:{exposure:"hidden",storageGroup:"flags"},[v]:{exposure:"hidden",storageGroup:"flags"},[f]:{exposure:"hidden"},[m]:{exposure:"hidden",storageGroup:"flags"},[T]:{exposure:"hidden",storageGroup:"flags"},[S]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[w]:{exposure:"hidden",storageGroup:"flags"},[I]:{exposure:"hidden"},[F]:{exposure:"hidden"},[k]:{exposure:"hidden"},[E]:{exposure:"hidden"},[M]:{exposure:"hidden",storageGroup:"surveys"},[O]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[D]:{exposure:"event"},[N]:{exposure:"hidden"},[B]:{exposure:"hidden"},[Se]:{exposure:"hidden"},[we]:{exposure:"hidden"},[Ce]:{exposure:"hidden"},[Ee]:{exposure:"event"},[ke]:{exposure:"event"},[xe]:{exposure:"event"},[Pe]:{exposure:"event"},[x]:{exposure:"hidden"},[P]:{exposure:"hidden"},[be]:{exposure:"event"},[y]:{exposure:"hidden"},[b]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Te]:{exposure:"hidden"},[Ie]:{exposure:"hidden"},[Fe]:{exposure:"hidden"},[Re]:{exposure:"hidden"},[Ae]:{exposure:"hidden"},[$e]:{exposure:"hidden"},[Me]:{exposure:"hidden"},[ce]:{exposure:"event"},[ue]:{exposure:"event"},[de]:{exposure:"event"},[he]:{exposure:"event"},[De]:{exposure:"event"},[Ne]:{exposure:"event"},[Be]:{exposure:"hidden"},[Ue]:{exposure:"hidden"},[ze]:{exposure:"hidden"},[He]:{exposure:"hidden"},[qe]:{exposure:"hidden"},[je]:{exposure:"hidden"},[We]:{exposure:"hidden"},[Ve]:{exposure:"hidden"},[Ge]:{exposure:"hidden"},[Ke]:{exposure:"event"}},Pa=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Ta=e=>{const t=xa[e];if(t)return t;for(const[t,i]of Pa)if(0===e.indexOf(t))return i};function Ia(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}const Fa=e=>{const t=typeof document>"u"?void 0:document,i=null==t?void 0:t.createElement("a");return mt(i)?null:(i.href=e,i)},Ra=()=>{try{return"u">typeof window&&!1!==window.navigator.onLine}catch(e){return!1}},Aa=(e,t)=>e>=t&&Ra(),$a=(e,t,i,s)=>{if(0===e){if(Ra()){const e=t+1;return e===i&&s(),e}return t}return 0},Ma=(e,t)=>{try{let i;return JSON.stringify(e,(e,t)=>{var s;return Ft(t)?(null!==(s=i)&&void 0!==s||(i=new WeakMap),i.has(t)||i.set(t,Hr(t)),i.get(t)):"bigint"==typeof t?t.toString():t},t)}catch(t){return ut(e)}},Oa=function(e,t){const i=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let s;for(let e=0;i.length>e;e++){const n=i[e].split(/=(.*)/);if(n[0]===t){s=n;break}}if(!pt(s)||2>s.length)return"";{let e=s[1].replace(/\+/g," ");try{e=decodeURIComponent(e)}catch(t){Mr.error("Skipping decoding for malformed query param: "+e)}return e}},La=function(e,t,i){if(!e||!t||!t.length)return e;const s=e.split(/#(.*)/),n=s[1],r=(s[0]||"").split(/\?(.*)/),o=r[1],a=r[0],l=(o||"").split("&"),c=[];for(let e=0;l.length>e;e++){const s=l[e].split("?");let n=0;for(;s.length>n&&!t.includes(s[n].split("=")[0]);)n++;c.push(s.length>n?s.slice(0,n).concat(s[n].split("=")[0]+"="+i).join("?"):l[e])}let u=a;return null!=o&&(u+="?"+c.join("&")),null!=n&&(u+="#"+n),u},Da=function(e,t){const i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},Na=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","oppref","bfcid","irclid","_kx"],Ba=(()=>["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Na])(),Ua="<masked>",za=["li_fat_id"];function Ha(e,t,i){if(!o)return{};const s=t?[...Na,...i||[]]:[],n=qa(La(o.URL,s,Ua),e),r=function(){const e={};return Dr(za,function(t){const i=Gr(t);e[t]=i||null}),e}();return Nr(r,n)}function qa(e,t){const i=Ba.concat(t||[]),s={};return Dr(i,function(t){const i=Oa(e,t);s[t]=i||null}),s}function ja(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(!St(t)){s.$search_engine=t;const e=o?Oa(o.referrer,i):"";e.length&&(s.ph_keyword=e)}return s}function Wa(){return navigator.language||navigator.userLanguage}function Va(){const e=Wa();return"string"==typeof e?e.split("-")[0]:void 0}const Ga="$direct";function Ka(){return(null==o?void 0:o.referrer)||Ga}function Ya(e,t,i=!1){const s=e?[...Na,...t||[]]:[],n=i?es(null==a?void 0:a.href):null==a?void 0:a.href,r=null==n?void 0:n.substring(0,1e3);return{r:Ka().substring(0,1e3),u:r?La(r,s,Ua):void 0}}function Qa(e,t=!1){var i;const{r:s,u:n}=e,r=t?es(n):n,o={$referrer:s,$referring_domain:null==s?void 0:s==Ga?Ga:null===(i=Fa(s))||void 0===i?void 0:i.host};if(r){o.$current_url=r;const e=Fa(r);o.$host=null==e?void 0:e.host,o.$pathname=null==e?void 0:e.pathname;const t=qa(r);Nr(o,t)}if(s){const e=ja(s);Nr(o,e)}return o}function Ja(){try{return(new Date).getTimezoneOffset()}catch(e){return}}const Za={flags:b,surveys:O},Xa=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],el=e=>`${e}_cookie_identity_change_pending`,tl=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},il="main",sl=[C,v,m,T,S,b,w,k],nl=e=>-1!==sl.indexOf(e),rl=[G,Y],ol=e=>-1!==rl.indexOf(e),al=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},ll=e=>{if(!e)return{};const t=JSON.parse(e);return ft(t)?t:{}},cl=(e,t)=>{Dr(e,(i,s)=>{const n=Ta(s);n&&"event"!==n.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]})};var ul=class{constructor(e,t,i=!0,n=!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(n),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&Mr.info("Persistence loaded",e.persistence,ls({},this.props)),this.update_config(e,e,t),this.save(),s){const e=()=>this.flush();Wr(s,"beforeunload",e,{capture:!1}),Wr(s,"pagehide",e,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==s?void 0:s.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){const t=ka.find(t=>e.key===this._groupEntryName(t));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,il)},Wr(s,"storage",this._onStorage)}}reconcileFeatureFlagsBeforeMerge(){return!(this._disabled||this._cookieSyncSuppressed||this._storageMigrationInProgress)&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite()}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([e,t])=>{const i=this._pendingCrossTabFeatureFlagChanges.get(e);if(!nl(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&&s&&(s.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i=!0){if(this._disabled)return!1;let s,n;try{if(n=ao._get(e),St(n)){const e=this._slotWriteState(t);return e.storageValue=null,t!==il?e.persisted=!1:this._mergeMetaIdentifierProperties({}),!1}s=ll(n)}catch(e){return!1}t===il&&this._mergeMetaIdentifierProperties(s);const r=t===il?s:ao._parse(this._name);if(r&&this._hasCrossTabFeatureFlagIdentityMismatch(r))return!1;const o=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===il&&this._splitStorage&&!al(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,n),o}_hasCrossTabFeatureFlagIdentityMismatch(e){const t=this.props[z],i=e[z];return!mt(t)&&!mt(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){const n=this._slotWriteState(t);n.storageValue=s,t!==il&&(n.persisted=i);try{n.fingerprint=this._entryFingerprint(e,t)}catch(e){n.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){let s=!1;return sl.forEach(i=>{var n;const r=null===(n=Ta(i))||void 0===n?void 0:n.storageGroup;if(t===il&&this._splitStorage&&r||t!==il&&r!==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&&al(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}),s&&i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()),s}_mergeMetaIdentifierProperties(e){const t=this._storesIdentityInCookie&&this._config.cookieWinsOnConflict?[...co,...this._config.cookie_persisted_properties||[]]:[];rl.forEach(i=>{this._metaIdentifierChangePending.has(i)||-1!==t.indexOf(i)||(i in e?al(e[i],this.props[i])||this._setProp(i,e[i],!1):i in this.props&&this._deleteProp(i,!1))})}_metaIdentifierCookieSyncEnabled(){return this._storesIdentityInCookie&&this._splitStorageEligible&&!this._config.cookieWinsOnConflict}_adoptMetaIdentifiersFromCookie(){if(!this._metaIdentifierCookieSyncEnabled())return;let e,t;try{e=ro._get(this._name)||void 0}catch(e){return}if(e&&e!==this._lastSeenMetaIdentifierCookieValue){this._lastSeenMetaIdentifierCookieValue=e;try{t=_o(JSON.parse(e))}catch(e){return}rl.forEach(e=>{!(e in t)||e in this.props||this._metaIdentifierChangePending.has(e)||this._setProp(e,t[e],!1)})}}_rememberMetaIdentifierCookieValue(e){if(this._metaIdentifierCookieSyncEnabled())try{const t=JSON.stringify(po(e,this._config.cookie_persisted_properties||[])),i=ro._get(this._name)||void 0;i===t&&(this._lastSeenMetaIdentifierCookieValue=i)}catch(e){}}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;const e=ao._get(this._name),t=this._slotWriteState(il);let i,s=!1,n=!1;if(e!==t.storageValue)if(St(e))yt(t.storageValue)&&this._mergeMetaIdentifierProperties({}),t.storageValue=null;else{if(i=ll(e),this._mergeMetaIdentifierProperties(i),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(i),this._crossTabFeatureFlagIdentityMismatch)return!1;n=this._mergeCrossTabFeatureFlagProperties(i,il,!1),!this._splitStorage||al(this._partitionProps().main,i)?this._rememberCrossTabStorageFingerprint(i,il,!0,e):t.storageValue=e,s=!0}return this._splitStorage&&ka.forEach(e=>{const t=ao._get(this._groupEntryName(e)),r=this._slotWriteState(e),o=i||{},a=s&&sl.some(t=>{var i;return(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e&&t in o});if(t===r.storageValue&&!a)return;if(St(t))return r.storageValue=null,r.persisted=!1,void(a&&(n=this._mergeCrossTabFeatureFlagProperties(o,e,!1)||n));const l=ll(t);n=this._mergeCrossTabFeatureFlagProperties(l,e,!1)||n,this._rememberCrossTabStorageFingerprint(l,e,!0,t)}),n}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);const i=Ta(e);(null==i?void 0:i.volatile)||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||il).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){sl.forEach(e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{const e=ao._get(this._name),t=ll(e);this._slotWriteState(il).storageValue=e,sl.forEach(e=>{var i;const s=this._splitStorage?null===(i=Ta(e))||void 0===i?void 0:i.storageGroup:void 0,n=s?ao._get(this._groupEntryName(s)):null;if(s){const e=this._slotWriteState(s);e.storageValue=n,e.persisted=!St(n)}const r=s&&!St(n)?ll(n):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,r[e],this.props[e]):e in r&&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(pt(t)?t:[]),n=new Set(pt(this.props[e])?this.props[e]:[]);return i.forEach(e=>n.has(e)?s.add(e):s.delete(e)),Array.from(s)}const s=ft(t)?ls({},t):{},n=ft(this.props[e])?this.props[e]:{};return i.forEach(e=>{e in n?s[e]=n[e]:delete s[e]}),s}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(!nl(e))return;const s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0===s)return;let n=t;if(this._splitStorageEligible)try{var r;const t=this._splitStorage?null===(r=Ta(e))||void 0===r?void 0:r.storageGroup:void 0,i=t?this._groupEntryName(t):this._name;n=ll(ao._get(i))[e]}catch(e){}const o=new Set(s||[]);if("$active_feature_flags"===e){if(!mt(t)&&!pt(t)||!mt(n)&&!pt(n)||!pt(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=new Set(t||[]),r=new Set(n||[]),a=new Set(i);new Set([...s,...a]).forEach(e=>{s.has(e)!==a.has(e)&&o.add(e)}),o.forEach(e=>{r.has(e)===a.has(e)&&o.delete(e)})}else{if(!ft(i))return void(al(n,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));{if(!mt(t)&&!ft(t)||mt(t)&&vt(i)&&mt(n))return void this._setCrossTabFeatureFlagChangesPending(e,!0);const s=ft(t)?t:{},r=ft(n)?n:{};new Set([...Object.keys(s),...Object.keys(i)]).forEach(e=>{e in s==e in i&&al(s[e],i[e])||o.add(e)}),o.forEach(e=>{e in r==e in i&&al(r[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 Ct(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{const t=po(e,this._config.cookie_persisted_properties||[]),i=fo(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),n=ro._get(this._name)||void 0;n&&mo(this._name,n)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=n)}catch(e){}else try{const e=ro._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=e?mo(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=ro._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;const s=mo(this._name,i);let n;try{n=_o(JSON.parse(i))}catch(e){return!1}if((ro._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=i;const r=vo(this._name,i),o=[...co,...r.properties],a={};if(Object.keys(n).forEach(e=>{const t=n[e];(mt(t)||St(t)||""===t||"$user_state"===e&&"anonymous"!==t&&"identified"!==t)&&(a[e]=!0,delete n[e])}),vt(n))return!1;const l="distinct_id"in n||"anonymous"===n.$user_state||"identified"===n.$user_state,c=this.props,u=c[z],d=c[Te],h=Nr({},c);[...co,...e.cookie_persisted_properties||[]].forEach(e=>{if(-1!==o.indexOf(e)&&!(e in n)&&!a[e]&&(l||"distinct_id"!==e&&"$user_state"!==e)){const t=h[e];(r.isValid||-1===co.indexOf(e)||!1!==t&&0!==t)&&delete h[e]}}),this.props=Nr(h,n),sl.forEach(e=>{const t=e in this.props;e in c===t&&al(c[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,c[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))}),!l||"$user_state"in n||"$user_state"in this.props||this._setProp(Te,Ye);const _=this.props[z],p=this.props[Te];return!l||_===u&&p===d||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,wo._set(el(this._name),!0),this._deleteProp(k),this._deleteProp(v),this._deleteProp(C),this._deleteProp(m),this._deleteProp(T),this._deleteProp(S),this._deleteProp(b),this._deleteProp(y),this._deleteProp(x),"anonymous"!==p||"identified"!==d&&"anonymous"!==n.$user_state&&(mt(u)||_===u)||(cl(this.props,n),this._deleteProp(E)),"identified"===p?this.props.$user_id=_:delete this.props.$user_id,this._deleteProp(j)),!0}consumeCookieIdentityChange(){const e=el(this._name),t=this._cookieIdentityChangePending||!!wo._get(e);return this._cookieIdentityChangePending=!1,t&&wo._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&&(mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[il],this._writeNow(!0))}_endCookieSyncSuppression(e=!0){if(this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():mt(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===Xa.indexOf(e.persistence.toLowerCase())&&(Mr.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((e=[],t=!1,i=()=>!1)=>{const n=[...co,...e];return ls(ls({},ao),{},{_parse(e){try{let r,o={};try{r=ro._get(e)||void 0,o=r?_o(JSON.parse(r)):{}}catch(e){}const a=JSON.parse(ao._get(e)||"{}");let l;if(t){const t=vo(e,r),i=[...co,...t.properties],c={};Object.keys(o).forEach(e=>{const t=o[e];St(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 s;const e=a[z],r=null!==(s=a.$user_state)&&void 0!==s?s:Ye;n.forEach(e=>{if(-1!==i.indexOf(e)&&!(e in o)&&(u||"distinct_id"!==e&&"$user_state"!==e)){const i=a[e];(t.isValid||-1===co.indexOf(e)||!1!==i&&0!==i)&&delete a[e]}}),!u||"$user_state"in o||"$user_state"in a||(a[Te]=Ye),!u||("distinct_id"in c?c[z]:a[z])===e&&("$user_state"in c?c[Te]:a[Te])===r||(lo.forEach(e=>delete a[e]),"identified"===c.$user_state&&"distinct_id"in c?a.$user_id=c[z]:delete a.$user_id,"identified"!==c.$user_state&&(delete a[be],delete a[E]),delete a.__alias)}l=Nr(a,c)}else l=Nr(o,a);return i()||ao._set(e,l),l}catch(e){}return null},_set(i,s,n,r,o,a){const l=ao._set(i,s,void 0,void 0,a);try{const c=po(s,e);if(Object.keys(c).length){if(t){const t=uo(i),u=fo(c,e);if(ro._set(t,u,n,r,o,a),ro._get(t)!==JSON.stringify(u)){ro._remove(t,r);const e=po(s);return ro._set(i,e,n,r,o,a),l}}ro._set(i,c,n,r,o,a)}}catch(e){ao._error(e)}return l},_remove(e,t){try{null==s||s.localStorage.removeItem(e),ro._remove(e,t),ro._remove(uo(e),t)}catch(e){ao._error(e)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict,()=>!!this._disabled);let i,n=!1,r=!1;const o=e.persistence.toLowerCase();return"localstorage"===o&&ao._is_supported()?(i=ao,r=!0):"localstorage+cookie"===o&&t._is_supported()?(i=t,r=!0,n=!0):"sessionstorage"===o&&wo._is_supported()?i=wo:"memory"===o?i=bo:"cookie"===o&&ro._is_supported()?(i=ro,n=!0):t._is_supported()?(i=t,r=!0,n=!0):ro._is_supported()?(i=ro,n=!0):i=bo,this._splitStorageEligible=r,this._storesIdentityInCookie=n,i}_groupEntryName(e){return`${this._name}__${e}`}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){const e={};return Dr(this.props,(t,i)=>{const s=Ta(i);if(!s||"event"===s.exposure){var n;if(null==s||null===(n=s.shouldSkipFromEventProperties)||void 0===n?void 0:n.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?ao._parse(this._name):null;let s={};if(t)try{s=_o(ro._parse(this._name)),Dr(s,(e,t)=>{(mt(e)||St(e)||""===e)&&delete s[t]})}catch(e){}const n=this._storage._parse(this._name);if(n&&(this.props=Nr({},n)),this._splitStorage&&this._loadGroupEntries(),t&&n){var r,o;const e=null==i?void 0:i[z],t=null!==(r=null==i?void 0:i.$user_state)&&void 0!==r?r:Ye,a=n[z],l=null!==(o=n.$user_state)&&void 0!==o?o:Ye;if(a!==e||l!==t){this._cookieIdentityChangePending=!0,this._disabled||wo._set(el(this._name),!0);const i=Nr({},this.props);lo.forEach(e=>delete i[e]),"anonymous"!==l||"identified"!==t&&"anonymous"!==s.$user_state&&(mt(e)||a===e)||(cl(i,s),delete i[E]),this.props=i;const n=new Set;lo.forEach(e=>{var t;const i=null===(t=Ta(e))||void 0===t?void 0:t.storageGroup;i&&n.add(i)}),n.forEach(e=>{if(this._disabled)return;const t={};Dr(this.props,(i,s)=>{var n;(null===(n=Ta(s))||void 0===n?void 0:n.storageGroup)===e&&(t[s]=i)}),vt(t)?(ao._remove(this._groupEntryName(e)),this._slotState[e]={}):ao._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})})}}wo._get(el(this._name))&&(this._cookieIdentityChangePending=!0)}_loadGroupEntries(){for(const e of ka){const t=ao._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)||Nr(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some(t=>{var i;return(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e})}_groupEntryIsStale(e,t){const i=Za[e];if(!i)return!1;const s=t[i],n=this.props[i];return Ct(s)&&Ct(n)&&n>s}refreshKey(e){this._refreshKeys([e])}_refreshKeys(e){if(this._disabled)return;let t,i=!1;const s=()=>(i||(t=this._storage._parse(this._name),i=!0),t);e.forEach(e=>{var t;if(this._metaIdentifierChangePending.has(e))return;const i=this._splitStorage?null===(t=Ta(e))||void 0===t?void 0:t.storageGroup:void 0,n=i?ao._parse(this._groupEntryName(i)):s();if(n&&e in n)this._setProp(e,n[e],!1);else{if(i){const t=s();if(t&&e in t)return void this._setProp(e,t[e],!1)}this._deleteProp(e,!1)}})}refreshMetaIdentifiers(){this._disabled||(this._usesMetaIdentifierSnapshotRefresh()?this._refreshMetaIdentifiersIfStorageChanged():this._refreshKeys(rl))}_refreshMetaIdentifiersIfStorageChanged(){const e=this._storageSnapshot();(mt(e)||e!==this._metaIdentifierStorageSnapshot)&&(this._refreshKeys(rl),this._rememberMetaIdentifierStorageSnapshot(e))}_rememberMetaIdentifierStorageSnapshot(e=this._storageSnapshot()){this._metaIdentifierStorageSnapshot=0===this._metaIdentifierChangePending.size?e:void 0}refreshMetaIdentifiersBeforeCapture(){this._disabled||this._cookieSyncSuppressed||(this._usesMetaIdentifierSnapshotRefresh()||this._adoptMetaIdentifiersFromCookie(),this._refreshMetaIdentifiersIfStorageChanged())}_usesMetaIdentifierSnapshotRefresh(){return this._storage===ro||this._storage===wo||this._storage===bo}_storageSnapshot(){const e=this._storage._get(this._name);return yt(e)?e:void 0}save(){if(this._disabled)return;const e=this._saveDebounceMs();e>0?mt(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout(()=>{this._pendingSaveTimer=void 0,this._writeNow()},e)):this._writeNow()}flush(){mt(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._usesMetaIdentifierSnapshotRefresh()&&this.refreshMetaIdentifiers());const t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);const i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)return void(this._config.debug&&Mr.warn("skipping persistence write because storage belongs to a different distinct ID"));if(e||this._adoptMetaIdentifiersFromCookie(),this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach(e=>e()));const s=this._writeEntry(this._storage,this._name,this.props,il);"written"===s&&(this._rememberCurrentCookieProperties(this.props),this._rememberMetaIdentifierCookieValue(this.props)),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear()),"written"===s&&this._rememberMetaIdentifierStorageSnapshot(),i&&this._crossTabFeatureFlagHandlers.forEach(e=>e())}_writeNowSplit(){const{main:e,groups:t}=this._partitionProps(),i=this._writeEntry(this._storage,this._name,e,il);"written"===i&&(this._rememberCurrentCookieProperties(e),this._rememberMetaIdentifierCookieValue(e)),"failed"!==i&&(this._localIdentityChangePending=!1,this._metaIdentifierChangePending.clear(),sl.forEach(e=>{var t;(null===(t=Ta(e))||void 0===t?void 0:t.storageGroup)||this._pendingCrossTabFeatureFlagChanges.delete(e)})),"written"===i&&this._rememberMetaIdentifierStorageSnapshot();for(const e of ka){var s;const i=t[e];if(vt(i)&&!(null===(s=this._slotState[e])||void 0===s?void 0:s.persisted)){sl.forEach(t=>{var i;(null===(i=Ta(t))||void 0===i?void 0:i.storageGroup)===e&&this._pendingCrossTabFeatureFlagChanges.delete(t)});continue}const n=this._writeEntry(ao,this._groupEntryName(e),i,e);"failed"!==n&&sl.forEach(t=>{const i=Ta(t);(null==i?void 0:i.storageGroup)!==e||"written"!==n&&i.volatile||this._pendingCrossTabFeatureFlagChanges.delete(t)})}}_partitionProps(){const e={},t={flags:{},surveys:{}};return Dr(this.props,(i,s)=>{var n;const r=null===(n=Ta(s))||void 0===n?void 0:n.storageGroup;r?t[r][s]=i:e[s]=i}),{main:e,groups:t}}_entryFingerprint(e,t){if(t===il)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;const i={};return Dr(e,(e,t)=>{var s;i[t]=(null===(s=Ta(t))||void 0===s?void 0:s.volatile)?"__volatile__":e}),JSON.stringify(i)}_writeEntry(e,t,i,s){const n=this._slotWriteState(s);if(s!==il&&!n.dirty&&!mt(n.fingerprint))return"skipped";let r;try{if(r=this._entryFingerprint(i,s),r===n.fingerprint)return n.dirty=!1,"skipped"}catch(e){r=void 0}return e._set(t,i,this._expire_days,this._cross_subdomain,this._secure,this._config.debug)?(n.dirty=!1,s!==il&&(n.persisted=!0),mt(r)||(n.fingerprint=r),this._splitStorageEligible&&(n.storageValue=ao._get(t)),"written"):(this._config.debug&&Mr.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this._markAllCrossTabFeatureFlagChangesPending(),mt(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 ka)ao._remove(this._groupEntryName(e));e?delete this._slotState[il]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(ft(e)){this.syncCookieProperties(),mt(t)&&(t="None"),this._expire_days=mt(i)?this._default_expiry:i;let s=!1;if(Dr(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(ft(e)){this.syncCookieProperties(),this._expire_days=mt(t)?this._default_expiry:t;let i=!1;if(Dr(e,(t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||ft(t)||pt(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==o?void 0:o.URL;if(e===this._campaign_params_url)return;const t=Ha(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!vt(zr(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}update_search_keyword(){this.register(function(){const e=null==o?void 0:o.referrer;return e?ja(e):{}}())}update_referrer_info(){var e;this.register_once({$referrer:Ka(),$referring_domain:(null==o?void 0:o.referrer)&&(null===(e=Fa(o.referrer))||void 0===e?void 0:e.host)||Ga},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=Ya(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[$e]:this._storesIdentityInCookie?{r:tl(e.r),u:e.u?tl(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Dr([Ae,Re],t=>{const i=this.props[t];i&&Dr(i,function(t,i){e["$initial_"+ct(i)]=t})});const t=this.props[$e];if(t){const i=function(e,t=!1){const i=Qa(e,t),s={};return Dr(i,function(e,t){s[`$initial_${ct(t)}`]=e}),s}(t,this._config.disable_capture_url_hashes);Nr(e,i)}return e}safe_merge(e){return Dr(this.props,function(t,i){i in e||(e[i]=t)}),e}update_config(e,t,i){const s=e.persistence!==t.persistence,n=!((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||[]),r=s||n,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!i,l=!!this._disabled&&!a;a||this._syncCookieProperties(t,l),this._config=e,!a&&(s||n||o)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._lastSeenMetaIdentifierCookieValue=void 0,this._syncCookieProperties(ls(ls({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),l));const c=r||o?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();const u=this._resolveSplitStorage(e),d=r||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[il],this._writeNow()))}finally{this._storageMigrationInProgress=!1,h&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){const e=this.props[$e];if(!this._storesIdentityInCookie||!ft(e)||"string"!=typeof e.r)return;const t=tl(e.r),i="string"==typeof e.u?tl(e.u):e.u;t===e.r&&i===e.u||this._setProp($e,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(Q,i),this.save()}remove_event_timer(e){const t=this.props.__timers||{},i=t[e];return mt(i)||(delete t[e],this._setProp(Q,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 n=this.props[e];this.props[e]=t,i&&("distinct_id"!==e&&"$user_state"!==e||n===t||(this._localIdentityChangePending=!0),ol(e)&&!al(n,t)&&this._metaIdentifierChangePending.add(e),this._markPendingCrossTabFeatureFlagChanges(e,n,t),(null===(s=Ta(e))||void 0===s?void 0:s.volatile)||this._markGroupDirty(e))}_deleteProp(e,t=!0){delete this.props[e],t&&(nl(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),ol(e)&&this._metaIdentifierChangePending.add(e),this._markGroupDirty(e))}_markGroupDirty(e){var t;const i=null===(t=Ta(e))||void 0===t?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}};const dl={GZipJS:"gzip-js",Base64:"base64"},hl={Activation:"events",Cancellation:"cancelEvents"},_l={Button:"button",Tab:"tab",Selector:"selector"},pl={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"},gl={Top:"top",Left:"left",Right:"right",Bottom:"bottom"},fl={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},vl={Open:"open",MultipleChoice:"multiple_choice",SingleChoice:"single_choice",Rating:"rating",Link:"link"},ml={NextQuestion:"next_question",End:"end",ResponseBased:"response_based",SpecificQuestion:"specific_question"},yl={Once:"once",Recurring:"recurring",Always:"always"},bl={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Sl={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"},wl={Popover:"popover",Inline:"inline"};function Cl(e){let t=!0;return{dispose(){if(t){t=!1;const i=e();i&&gt(i.then)&&i.then(void 0,()=>{})}}}}const El={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},kl={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"},xl={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=Or("[RateLimiter]");var Tl=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)}get isClientRateLimited(){return 1>this._refilledBucket().tokens}clientRateLimitContext(e=!1){var t;const i=this._refilledBucket(),s=1>i.tokens;if(s||e||(i.tokens=Math.max(0,i.tokens-1)),s&&!e){const e=(Ct(i.dropped)?i.dropped:0)+1;i.dropped=e,!this.lastEventRateLimited&&this._captureWarning(e)&&(i.dropped=0)}return this.lastEventRateLimited=s,null===(t=this.instance.persistence)||void 0===t||t.set_property("$capture_rate_limit",i),{isRateLimited:s,remainingTokens:i.tokens}}_refilledBucket(){var e;const{captureEventsBurstLimit:t,captureEventsPerSecond:i}=this,s=(new Date).getTime(),n=null===(e=this.instance.persistence)||void 0===e?void 0:e.get_property(Fe),r=n?ls({},n):{tokens:t,last:s};return r.tokens+=Math.max(0,s-r.last)/1e3*i,r.last=Math.max(r.last,s),r.tokens>t&&(r.tokens=t),r}_isPropertyAllowed(e){const t=this.instance.config.property_denylist;return!pt(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&(null==a?void 0:a.pathname))return`${null!==(e=a.origin)&&void 0!==e?e:""}${a.pathname}`}_captureWarning(e){var t,i;const{captureEventsBurstLimit:s,captureEventsPerSecond:n}=this,r=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`,r?`triggered on ${r}`: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 ${n} 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 Il=Or("[RemoteConfig]");var Fl=class{constructor(e){this._instance=e}get remoteConfig(){var e;return null===(e=p._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.config}_loadRemoteConfigJs(e){const t=g(this._instance);t?t(this._instance,"remote-config",()=>e(this.remoteConfig)):e()}_loadRemoteConfigJSON(e){const t=this._instance.__pending_remote_config_callbacks;if(t)return void t.push(e);const i=[e];this._instance.__pending_remote_config_callbacks=i;try{this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),batchKey:"remote_config",fireCallbackOnDrop:!0,callback:e=>{this._instance.__pending_remote_config_callbacks=void 0,i.forEach(t=>t(e))}})}catch(e){throw this._instance.__pending_remote_config_callbacks=void 0,e}}load(){try{if(this.remoteConfig)return Il.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void Il.warn("Remote config is disabled. Falling back to local config.");if(!this._instance.config.opt_in_site_apps)return void this._loadRemoteConfigJSON(e=>{this._onRemoteConfig(e.json,e)});this._loadRemoteConfigJs(e=>{if(!e)return Il.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){Il.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||Il.warn("Failed to fetch remote config from PostHog."):Il.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){Il.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){Il.error("Error loading feature flags",e)}}};const Rl=["fatal","error","warning","log","info","debug"];var Al=Uint8Array,$l=Uint16Array,Ml=Uint32Array,Ol=new Al([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]),Ll=new Al([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]),Dl=new Al([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Nl=function(e,t){for(var i=new $l(31),s=0;31>s;++s)i[s]=t+=1<<e[s-1];var n=new Ml(i[30]);for(s=1;30>s;++s)for(var r=i[s];i[s+1]>r;++r)n[r]=r-i[s]<<5|s;return[i,n]},Bl=Nl(Ol,2),Ul=Bl[1];Bl[0][28]=258,Ul[258]=28;for(var zl=Nl(Ll,0)[1],Hl=new $l(32768),ql=0;32768>ql;++ql){var jl=(43690&ql)>>>1|(21845&ql)<<1;Hl[ql]=((65280&(jl=(61680&(jl=(52428&jl)>>>2|(13107&jl)<<2))>>>4|(3855&jl)<<4))>>>8|(255&jl)<<8)>>>1}var Wl=function(e,t,i){for(var s=e.length,n=0,r=new $l(t);s>n;++n)++r[e[n]-1];var o,a=new $l(t);for(n=0;t>n;++n)a[n]=a[n-1]+r[n-1]<<1;if(i){o=new $l(1<<t);var l=15-t;for(n=0;s>n;++n)if(e[n])for(var c=n<<4|e[n],u=t-e[n],d=a[e[n]-1]++<<u,h=d|(1<<u)-1;h>=d;++d)o[Hl[d]>>>l]=c}else for(o=new $l(s),n=0;s>n;++n)o[n]=Hl[a[e[n]-1]++]>>>15-e[n];return o},Vl=new Al(288);for(ql=0;144>ql;++ql)Vl[ql]=8;for(ql=144;256>ql;++ql)Vl[ql]=9;for(ql=256;280>ql;++ql)Vl[ql]=7;for(ql=280;288>ql;++ql)Vl[ql]=8;var Gl=new Al(32);for(ql=0;32>ql;++ql)Gl[ql]=5;var Kl=Wl(Vl,9,0),Yl=Wl(Gl,5,0),Ql=function(e){return(e/8|0)+(7&e&&1)},Jl=function(e,t,i){(null==t||0>t)&&(t=0),(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof $l?$l:e instanceof Ml?Ml:Al)(i-t);return s.set(e.subarray(t,i)),s},Zl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},Xl=function(e,t,i){var s=t/8|0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},ec=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var n=i.length,r=i.slice();if(!n)return[new Al(0),0];if(1==n){var o=new Al(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!=n-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=r[0].s;for(s=1;n>s;++s)r[s].s>h&&(h=r[s].s);var _=new $l(h+1),p=tc(i[u-1],_,0);if(p>t){s=0;var g=0,f=p-t,v=1<<f;for(r.sort(function(e,t){return _[t.s]-_[e.s]||e.f-t.f});n>s;++s){var m=r[s].s;if(t>=_[m])break;g+=v-(1<<p-_[m]),_[m]=t}for(g>>>=f;g>0;){var y=r[s].s;t>_[y]?g-=1<<t-_[y]++-1:++s}for(;s>=0&&g;--s){var b=r[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new Al(_),p]},tc=function(e,t,i){return-1==e.s?Math.max(tc(e.l,t,i+1),tc(e.r,t,i+1)):t[e.s]=i},ic=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new $l(++t),s=0,n=e[0],r=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==n&&a!=t)++r;else{if(!n&&r>2){for(;r>138;r-=138)o(32754);r>2&&(o(r>10?r-11<<5|28690:r-3<<5|12305),r=0)}else if(r>3){for(o(n),--r;r>6;r-=6)o(8304);r>2&&(o(r-3<<5|8208),r=0)}for(;r--;)o(n);r=1,n=e[a]}return[i.subarray(0,s),t]},sc=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},nc=function(e,t,i){var s=i.length,n=Ql(t+2);e[n]=255&s,e[n+1]=s>>>8,e[n+2]=255^e[n],e[n+3]=255^e[n+1];for(var r=0;s>r;++r)e[n+r+4]=i[r];return 8*(n+4+s)},rc=function(e,t,i,s,n,r,o,a,l,c,u){Zl(t,u++,i),++n[256];for(var d=ec(n,15),h=d[0],_=d[1],p=ec(r,15),g=p[0],f=p[1],v=ic(h),m=v[0],y=v[1],b=ic(g),S=b[0],w=b[1],C=new $l(19),E=0;m.length>E;++E)C[31&m[E]]++;for(E=0;S.length>E;++E)C[31&S[E]]++;for(var k=ec(C,7),x=k[0],P=k[1],T=19;T>4&&!x[Dl[T-1]];--T);var I,F,R,A,M=c+5<<3,O=sc(n,Vl)+sc(r,Gl)+o,L=sc(n,h)+sc(r,g)+o+14+3*T+sc(C,x)+(2*C[16]+3*C[17]+7*C[18]);if(O>=M&&L>=M)return nc(t,u,e.subarray(l,l+c));if(Zl(t,u,1+(O>L)),u+=2,O>L){I=Wl(h,_,0),F=h,R=Wl(g,f,0),A=g;var D=Wl(x,P,0);for(Zl(t,u,y-257),Zl(t,u+5,w-1),Zl(t,u+10,T-4),u+=14,E=0;T>E;++E)Zl(t,u+3*E,x[Dl[E]]);u+=3*T;for(var N=[m,S],B=0;2>B;++B){var U=N[B];for(E=0;U.length>E;++E)Zl(t,u,D[z=31&U[E]]),u+=x[z],z>15&&(Zl(t,u,U[E]>>>5&127),u+=U[E]>>>12)}}else I=Kl,F=Vl,R=Yl,A=Gl;for(E=0;a>E;++E)if(s[E]>255){var z;Xl(t,u,I[257+(z=s[E]>>>18&31)]),u+=F[z+257],z>7&&(Zl(t,u,s[E]>>>23&31),u+=Ol[z]);var H=31&s[E];Xl(t,u,R[H]),u+=A[H],H>3&&(Xl(t,u,s[E]>>>5&8191),u+=Ll[H])}else Xl(t,u,I[s[E]]),u+=F[s[E]];return Xl(t,u,I[256]),u+F[256]},oc=new Ml([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ac=new Al(0),lc=function(){for(var e=new Ml(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),cc=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function uc(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=lc[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var n,r,o,a,l,c,u=(a=10+((n=t).filename&&n.filename.length+1||0),l=8,function(e,t,i,s,n,r){var o=e.length,a=new Al(s+o+5*(1+Math.floor(o/7e3))+n),l=a.subarray(s,a.length-n),c=0;if(!t||8>o)for(var u=0;o>=u;u+=65535){var d=u+65535;o>d?c=nc(l,c,e.subarray(u,d)):(l[u]=r,c=nc(l,c,e.subarray(u,o)))}else{for(var h=oc[t-1],_=h>>>13,p=8191&h,g=(1<<i)-1,f=new $l(32768),v=new $l(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 Ml(25e3),w=new $l(288),C=new $l(32),E=0,k=0,x=(u=0,0),P=0,T=0;o>u;++u){var I=b(u),F=32767&u,R=v[I];if(f[F]=R,v[I]=F,u>=P){var A=o-u;if((E>7e3||x>24576)&&A>423){c=rc(e,l,0,S,w,C,k,x,T,u-T,c),x=E=k=0,T=u;for(var M=0;286>M;++M)w[M]=0;for(M=0;30>M;++M)C[M]=0}var O=2,L=0,D=p,N=F-R&32767;if(A>2&&I==b(u-N))for(var B=Math.min(_,A)-1,U=Math.min(32767,u),z=Math.min(258,A);U>=N&&--D&&F!=R;){if(e[u+O]==e[u+O-N]){for(var H=0;z>H&&e[u+H]==e[u+H-N];++H);if(H>O){if(O=H,L=N,H>B)break;var q=Math.min(N,H-2),j=0;for(M=0;q>M;++M){var W=u-N+M+32768&32767,V=W-f[W]+32768&32767;V>j&&(j=V,R=W)}}}N+=(F=R)-(R=f[F])+32768&32767}if(L){S[x++]=268435456|Ul[O]<<18|zl[L];var G=31&Ul[O],K=31&zl[L];k+=Ol[G]+Ll[K],++w[257+G],++C[K],P=u+O,++E}else S[x++]=e[u],++w[e[u]]}}c=rc(e,l,r,S,w,C,k,x,T,u-T,c),r||(c=nc(l,c,ac))}return Jl(a,0,s+Ql(c)+n)}(r=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(r.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&&cc(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),cc(u,d-8,i.d()),cc(u,d-4,s),u}const dc=!!c||!!l,hc=new WeakMap,_c="text/plain";let pc=0,gc=!1;const fc=(e,t)=>{const[i,s]=e.split("#"),[n,r]=i.split("?");if(!r)return e;const o=r.split("&").filter(e=>e.split("=")[0]!==t).join("&");return`${n}${o?`?${o}`:""}${s?`#${s}`:""}`},vc=(e,t,i=!0)=>{var s;const[n,r]=e.split("?"),o=ls({},t),a=null!==(s=null==r?void 0:r.split("&").map(e=>{var t;const[s,n]=e.split("="),r=i&&null!==(t=o[s])&&void 0!==t?t:n;return delete o[s],`${s}=${r}`}))&&void 0!==s?s:[],l=function(e,t="&"){let i,s;const n=[];return Dr(e,function(e,t){mt(e)||mt(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),n[n.length]=s+"="+i)}),n.join(t)}(o);return l&&a.push(l),a.length>0?`${n}?${a.join("&")}`:n},mc=e=>{if(e._encodedBody)return e._encodedBody;const{data:t,compression:i}=e;if(!t)return;if(i===dl.GZipJS){const e=uc(function(e){var t=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var i=new Al(e.length+(e.length>>>1)),s=0,n=function(e){i[s++]=e},r=0;t>r;++r){if(s+5>i.length){var o=new Al(s+8+(t-r<<1));o.set(i),i=o}var a=e.charCodeAt(r);128>a?n(a):2048>a?(n(192|a>>>6),n(128|63&a)):a>55295&&57344>a?(n(240|(a=65536+(1047552&a)|1023&e.charCodeAt(++r))>>>18),n(128|a>>>12&63),n(128|a>>>6&63),n(128|63&a)):(n(224|a>>>12),n(128|a>>>6&63),n(128|63&a))}return Jl(i,0,s)}(Ma(t)),{mtime:0});return{contentType:_c,body:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),estimatedSize:e.byteLength}}if(i===dl.Base64){const i=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))):e}(Ma(t)),s="sendBeacon"===e.transport,n=s?i:(e=>"data="+encodeURIComponent("string"==typeof e?e:Ma(e)))(i);return{contentType:s?_c:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}const s=Ma(t);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}},yc=e=>{const t=()=>"sendBeacon"===e.transport?{url:vc(e.url,{compression:dl.Base64}),encodedBody:mc(ls(ls({},e),{},{compression:dl.Base64,_encodedBody:void 0}))}:{url:fc(e.url,"compression"),encodedBody:mc(ls(ls({},e),{},{compression:void 0,_encodedBody:void 0}))};let i;try{i=mc(e)}catch(i){if(an(e.compression,Oa(e.url,"compression")))return Mr.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return i&&an(e.compression,Oa(e.url,"compression"))&&!((s=i.body)instanceof ArrayBuffer?on(new Uint8Array(s)):ArrayBuffer.isView(s)&&on(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(gc=!0,t()):{url:e.url,encodedBody:i};var s},bc=e=>{try{return yc(e)}catch(i){var t;return Mr.error(i),void(null===(t=e.callback)||void 0===t||t.call(e,{statusCode:0,error:i}))}},Sc=function(){var e=Dt(function*(e){const t=yield function(e){return pn.apply(this,arguments)}(Ma(e.data),i.DEBUG,{rethrow:!0});if(!t)return e;const s=yield t.arrayBuffer();return ls(ls({},e),{},{_encodedBody:{contentType:_c,body:s,estimatedSize:s.byteLength}})});return function(t){return e.apply(this,arguments)}}(),wc=e=>Xi("AbortError","PostHog request timed out"+(e?` after ${e}ms`:"")),Cc=/Failed to fetch|NetworkError|Load failed/i,Ec=e=>"TypeError"===(null==e?void 0:e.name)&&Cc.test((null==e?void 0:e.message)||""),kc=e=>{try{const t=function(e,t=Date.now(),i=3e5){if("string"!=typeof e||!e)return;const s=e.trim(),n=/^\d+\s*,/.test(s)?s.slice(0,s.indexOf(",")).trim():s;if(/^\d+$/.test(n)){const e=1e3*Math.min(Number(n),i/1e3);return e>0?e:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(n))return;const r=/^\w{3} \w{3} /.test(n)?n+" GMT":n,o=Date.parse(r)-t;return Number.isFinite(o)&&o>0?Math.min(o,i):void 0}(e());return mt(t)?void 0:Math.min(t,3e4)}catch(e){return}},xc=e=>{var t;const i=bc(e);if(!i)return;const s=new c;hc.set(s,!0);const{url:n,encodedBody:r}=i;s.open(e.method||"GET",n,!0);const{contentType:o,body:a}=null!=r?r:{};Dr(e.headers,function(e,t){s.setRequestHeader(t,e)}),o&&s.setRequestHeader("Content-Type",o),e.timeout&&(s.timeout=e.timeout);let l=!1;s.ontimeout=()=>{l=!0},s.onloadend=()=>{var t;if(l){var i;const t=wc(e.timeout);return Mr.warn(t),void(null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))}const n={statusCode:s.status,text:s.responseText};if(200===s.status)try{n.json=JSON.parse(s.responseText)}catch(e){}null===(t=e.callback)||void 0===t||t.call(e,n,kc(()=>s.getResponseHeader("Retry-After")))},null===(t=e.onSend)||void 0===t||t.call(e,n),s.send(a)},Pc=e=>{const t=bc(e);if(!t)return;const{url:i,encodedBody:s}=t,{contentType:n,body:r,estimatedSize:o}=null!=s?s:{},a=new Headers;Dr(e.headers,function(e,t){a.append(t,e)}),n&&a.append("Content-Type",n);let c=null,d=!1;if(u){const t=new u;c={signal:t.signal,timeout:setTimeout(()=>{d=!0;try{t.abort(wc(e.timeout))}catch(e){_(e)}},e.timeout)}}let h=!1;const _=t=>{var i;h||(h=!0,d&&"AbortError"===(null==t?void 0:t.name)||Ec(t)?Mr.warn(t):Mr.error(t),null===(i=e.callback)||void 0===i||i.call(e,{statusCode:0,error:t}))};let p=0;const g=()=>{pc-=p,p=0,c&&clearTimeout(c.timeout)};try{var f;const t=ls({method:(null==e?void 0:e.method)||"GET",headers:a,referrerPolicy:"strict-origin",body:r,signal:null==c?void 0:c.signal},e.fetchOptions);null===(f=e.onSend)||void 0===f||f.call(e,i);const s=null!=o?o:mt(r)?0:void 0;t.keepalive="POST"===t.method&&!e._keepaliveDisabled&&!1!==t.keepalive&&t.body===r&&!mt(s)&&s>=0&&52428.8>pc+s,t.keepalive&&(p=s,pc+=p),l(i,t).then(t=>t.text().then(i=>{var s;if(h)return;const n={statusCode:t.status,text:i};if(200===t.status)try{n.json=JSON.parse(i)}catch(e){Mr.error(e)}h=!0,g(),null===(s=e.callback)||void 0===s||s.call(e,n,kc(()=>t.headers.get("Retry-After")))})).catch(e=>{g(),_(e)}).finally(g)}catch(e){g(),_(e)}},Tc=e=>{try{var t;const{url:i,encodedBody:s}=yc(e),{contentType:n,body:o,estimatedSize:a}=null!=s?s:{};if(!o)return;const c=o instanceof Blob?o:new Blob([o],{type:n});if(r.sendBeacon(i,c))return;const u=pt(e.data)?e.data:null===(t=e.data)||void 0===t?void 0:t.batch;if(pt(u)&&u.length>1&&(null!=a?a:0)>16384){const t=Math.ceil(u.length/2),i=t=>pt(e.data)?t:ls(ls({},e.data),{},{batch:t});return Tc(ls(ls({},e),{},{data:i(u.slice(0,t))})),void Tc(ls(ls({},e),{},{data:i(u.slice(t))}))}Mr.warn(`Beacon of ~${null!=a?a:0} bytes was rejected by the browser, falling back to ${l?"fetch":"XHR"}`),l?Pc(ls(ls({},e),{},{_keepaliveDisabled:!0})):xc(e)}catch(e){Mr.warn("Beacon send failed",e)}},Ic=(e,t,i,s)=>{const n="query"===s?"POST"===t?"sent_at":"_":void 0;return vc(i===dl.GZipJS?fc(e,"compression"):e,ls(ls({},n?{[n]:Date.now().toString()}:{}),i===dl.GZipJS?{}:{compression:i}))},Fc=(()=>{const e=[];return l&&e.push({transport:"fetch",method:Pc}),c&&e.push({transport:"XHR",method:xc}),(null==r?void 0:r.sendBeacon)&&e.push({transport:"sendBeacon",method:Tc}),e})();let Rc=!dc&&-1===(null==h?void 0:h.indexOf("MSIE"))&&-1===(null==h?void 0:h.indexOf("Mozilla"));function Ac(e,t,i){var s,n,r,o;i&&(t=ls(ls({},t),{},{callback:e=>i(e)})),e.__loaded?Rc?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,(mt(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,null===(n=t.onDispatch)||void 0===n||n.call(t),((e,t)=>{var i,s,n;const r=ls(ls({},e),{},{callback:null!=t?t:t=>{var i;return null===(i=e.callback)||void 0===i?void 0:i.call(e,t)}});r.timeout=r.timeout||6e4;const o=null!==(i=r.transport)&&void 0!==i?i:"fetch";"sendBeacon"===o&&mt(r.compression)&&r.data&&(r.compression=dl.Base64),"POST"===r.method&&r.data&&("capture-body"===r.timestampMode?r.data=(e=>{var t,i;const s=(pt(e)?e:[e]).map(e=>ls(ls({},e),e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{})),n=s[0];return{api_key:null!==(t=null==n||null===(i=n.properties)||void 0===i?void 0:i.token)&&void 0!==t?t:null==n?void 0:n.token,batch:s,sent_at:(new Date).toISOString()}})(r.data):"body"===r.timestampMode&&(r.data=((e,t=(new Date).toISOString())=>pt(e)?e.map(e=>ls(ls({},e),{},{sent_at:t})):ls(ls({},e),{},{sent_at:t}))(r.data))),r.url=Ic(r.url,r.method,r.compression,r.timestampMode);const a=Fc.filter(e=>!r.disableTransport||!e.transport||!r.disableTransport.includes(e.transport)),l=null!==(s=null===(n=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===n?void 0:n.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;Ec(e)?Mr.warn(e):Mr.error(e),null===(t=r.callback)||void 0===t||t.call(r,{statusCode:0,error:e})}};"sendBeacon"!==o&&!r.preferSyncCompression&&r.data&&r.compression===dl.GZipJS&&d&&"undefined"!=typeof Promise&&!gc?Sc(r).then(e=>{c(e)}).catch(t=>{if(ln(t))return gc=!0,void c(ls(ls({},r),{},{compression:void 0,url:Ic(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 ln(e)||t===rn})(t)&&(gc=!0),c(r)}):c(r)})(t,(s,n)=>{var r,o,a;e.rateLimiter.checkForLimiting(s),400>s.statusCode||null===(r=(o=e.config).on_request_error)||void 0===r||r.call(o,s),i?i(s,n):null===(a=t.callback)||void 0===a||a.call(t,s)})):t.fireCallbackOnDrop&&(null===(o=t.callback)||void 0===o||o.call(t,{statusCode:0}))}var $c=class{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=zt((null==t?void 0:t.flush_interval_ms)||3e3,250,5e3,Mr.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){Mr.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){const e={},t={};Dr(this._queue,i=>{var s;const n=i,r=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");mt(e[r])&&(e[r]=ls(ls({},n),{},{data:[],callback:void 0,fireCallbackOnDrop:void 0}),t[r]=[]),null===(s=e[r].data)||void 0===s||s.push(n.data),n.callback&&t[r].push(n.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 Mc=["retriesPerformedSoFar"];var Oc=class{constructor(e){this._instance=e,this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._queue=[],this._areWeOnline=!0,this.resume()}resume(){if(!mt(s)&&"onLine"in s.navigator){if(this._areWeOnline=s.navigator.onLine,this._onlineListener)return;this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},Wr(s,"online",this._onlineListener),Wr(s,"offline",this._offlineListener)}}get length(){return this._queue.length}retriableRequest(e,t){let{retriesPerformedSoFar:i}=e,s=gn(e,Mc);Et(i)&&(s.url=vc(s.url,{retry_count:i})),Ac(this._instance,t?ls(ls({},s),{},{transport:t}):s,(e,t)=>{var n;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&&Mr.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===(n=s.callback)||void 0===n||n.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),n=(Math.random()-.5)*(s-i);return Math.ceil(s+n)}(i),null!=t?t:0),n=Date.now()+s;this._queue.push({retryAt:n,requestOptions:e});let r=`Enqueued failed request for retry in ${s}`;navigator.onLine||(r+=" (Browser is offline)"),Mr.warn(r),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,mt(s)||(this._onlineListener&&(s.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(s.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0));for(const{requestOptions:e}of this._queue)try{this._instance._send_request(ls(ls({},e),{},{callback:pt(e.data)?void 0:e.callback,transport:"sendBeacon"}))}catch(e){Mr.error(e)}this._queue=[]}},Lc=class{constructor(e){this._instance=e,this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});const n=this.scrollElement(),r=this.scrollY(),o=n?Math.max(0,n.scrollHeight-n.clientHeight):0,a=r+((null==n?void 0:n.clientHeight)||0),l=(null==n?void 0:n.scrollHeight)||0;this._context.lastScrollY=Math.ceil(r),this._context.maxScrollY=Math.max(r,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(){Wr(s,"scroll",this._updateScrollData,{capture:!0}),Wr(s,"scrollend",this._updateScrollData,{capture:!0}),Wr(s,"resize",this._updateScrollData)}scrollElement(){if(this._scrollRoot){const t=pt(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(const i of t){var e;const t=null==s||null===(e=s.document)||void 0===e?void 0:e.querySelector(i);if(t)return t}return}var t;return null==s||null===(t=s.document)||void 0===t?void 0:t.documentElement}_scrollPosition(e){var t,i;const n="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){const e=this.scrollElement();return e&&e[n]||0}return s?"y"===e?s.scrollY||s.pageYOffset||(null===(t=s.document)||void 0===t||null===(t=t.documentElement)||void 0===t?void 0:t.scrollTop)||0:s.scrollX||s.pageXOffset||(null===(i=s.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 Dc=e=>Ya(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 Nc=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({[Ie]:i})},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Dc,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[Ie]}getSetOnceProps(){var e;const t=null===(e=this._getStored())||void 0===e?void 0:e.props;return t?"r"in t?Qa(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 Dr(zr(this.getSetOnceProps()),(t,i)=>{"$current_url"===i&&(i="url"),e[`$session_entry_${ct(i)}`]=t}),e}},Bc=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 Uc=Or("[SessionId]"),zc=864e5;var Hc=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 Bc,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||eo,this._windowIdGenerator=i||eo;const n=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*zt(this._config.session_idle_timeout_seconds||1800,60,36e3,Uc.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+n+"_window_id",this._primary_window_exists_storage_key="ph_"+n+"_primary_window_exists",this._canUseSessionStorage()){const e=wo._parse(this._window_id_storage_key),t=wo._parse(this._primary_window_exists_storage_key);e&&!t?this._windowId=e:wo._remove(this._window_id_storage_key),wo._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 mt(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&&wo._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&wo._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?wo._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){const t=this._lastPersistedActivityTimestamp;return!St(t)&&!St(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){const s=t!==this._sessionActivityTimestamp,n=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,n&&!s||n&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[_e]:[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(_e):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(St(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({[_e]:[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[_e];return pt(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 Uc.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void Uc.error("Invalid sessionID in bootstrap",e)}})(e);return!mt(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&&s&&(s.removeEventListener(Ze,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&wo._remove(this._primary_window_exists_storage_key)},Wr(s,Ze,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(),n=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(St(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var r,o;null===(r=(o=this._persistence).syncCookieProperties)||void 0===r||r.call(o),this._lastCookieSyncTimestamp=s}let[,a,l]=this._getSessionId();const c=!mt(n)&&a!==n,u=this._freshestActivityTimestamp();let d=this._getWindowId();const h=this._pendingBootstrapSession,_=!!h&&(h.sessionStartTimestamp>s+6e4||s-h.sessionStartTimestamp>zc),p=h?_:Et(l)&&Math.abs(s-l)>zc;let g=!1,f=c,v=!a||!!h;const m=a;let y=!v&&!e&&this._sessionHasBeenIdleTooLong(s,u);if(y&&(y=this._isSessionIdleAfterCrossTabRefresh(s),y||Uc.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,l]=this._getSessionId(),y||(v=!a||!!h)),v||y||p){f=!1;const e=h&&!_;a=e?h.sessionId:this._sessionIdGenerator(),d=this._windowIdGenerator(),Uc.info("new session ID assigned",{sessionId:a,windowId:d,bootstrapped:!!e,changeReason:{noSessionId:v,activityTimeout:y,sessionPastMaximumLength:p}}),l=e?h.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,g=!0}else d||(d=this._windowIdGenerator(),g=!0),f=f||a!==m,f&&(Uc.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:v,activityTimeout:y,sessionPastMaximumLength:p,crossTabAdoption:f};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 qc=Object.freeze(["2026-08-30","2026-08-29","2026-06-25","2026-05-30","2026-01-30","2025-11-30","2025-05-24"]),jc=function(e,t){if(!e)return!1;const i=e.userAgent;if(i&&Ut(i,t))return!0;try{const i=null==e?void 0:e.userAgentData;if((null==i?void 0:i.brands)&&i.brands.some(e=>Ut(null==e?void 0:e.brand,t)))return!0}catch(e){}return!!e.webdriver};function Wc(){return(Wc=Dt(function*(){const e=null==r?void 0:r.userAgentData;if(null==e?void 0:e.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return yt(i)&&i.length>0?i:void 0}catch(e){return void Mr.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}})).apply(this,arguments)}function Vc(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 Gc(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 Kc=(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}},Yc=e=>e.toLowerCase(),Qc={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=>Kc(t,e))),not_regex:(e,t)=>t.every(t=>e.every(e=>!Kc(t,e))),icontains:(e,t)=>t.map(Yc).some(t=>e.map(Yc).some(e=>t.includes(e))),not_icontains:(e,t)=>t.map(Yc).every(t=>e.map(Yc).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 Jc(e,t){return!e||Object.entries(e).every(([e,i])=>{const s=null==t?void 0:t[e];if(null==s)return!1;const n=Qc[i.operator];return!!n&&n(i.values.map(String),[String(s)])})}function Zc(e,t,i){return Ma({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}const Xc="custom",eu="i.posthog.com",tu=/^\/static\//,iu=["/s/","/e/","/i/"];var su=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(`.${eu}`,".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":Xc),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(!tu.test(e))return;const t=this.instance.config.asset_host;return"string"==typeof t&&t.trim().replace(/\/$/,"")||void 0}_urlKey(e){const t=Fa(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;let s=i;const n=this.instance.config.rewriteRequestPath;if(n){var r;const e=(null===(r=Fa(i))||void 0===r?void 0:r.href)||i;s=n(new URL(e)).toString()}if(n&&"api"===e&&iu.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===n||(i={apiHost:t,rewriteRequestPath:n,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===Xc)return this._prepareEndpoint(e,t,this.apiHost+t);const i=eu+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 nu=Or("[Surveys]"),ru=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){nu.error("Failed to persist survey seen state",e)}},ou=[fl.Popover,fl.Widget,fl.API],au={ignoreConditions:!1,ignoreDelay:!1,displayType:wl.Popover},lu=Or("[PostHog ExternalIntegrations]"),cu={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};var uu=class{constructor(e){this._instance=e}_loadScript(e,t){var i;null===(i=g(this._instance))||void 0===i||i(this._instance,e,e=>{if(e)return lu.error("failed to load script",e);t()})}startIfEnabledOrStop(){var e;for(const[n,r]of Object.entries(null!==(e=this._instance.config.integrations)&&void 0!==e?e:{})){var t,i,s;r&&!(null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.integrations)||void 0===t?void 0:t[n])&&this._loadScript(cu[n],()=>{var e;null===(e=p.__PosthogExtensions__)||void 0===e||null===(e=e.integrations)||void 0===e||null===(e=e[n])||void 0===e||e.start(this._instance)}),!r&&(null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.integrations)||void 0===i?void 0:i[n])&&(null===(s=p.__PosthogExtensions__)||void 0===s||null===(s=s.integrations)||void 0===s||null===(s=s[n])||void 0===s||s.stop())}}},du=class{constructor(e){this.disabled=!1===e;const t=ft(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 hu=()=>typeof window>"u"?void 0:window,_u=()=>typeof document>"u"?void 0:document,pu="$copy_autocapture",gu=["password","hidden","file","checkbox","button","submit","reset","image"],fu=Or("[AutoCapture]");function vu(e,t){return t.length>e?t.slice(0,e)+"...":t}function mu(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do{t=t.previousSibling}while(t&&!xo(t));return t}function yu(e,{e:t,maskAllElementAttributes:i,maskAllText:s,elementAttributeIgnoreList:n,elementsChainAsString:r,disableCaptureUrlHashes:o}){var a,l;if(!xo(e))return{props:{}};const c=[e],u=new Set([e]);let d=e;for(;!Po(d,"body")&&1e3>c.length;){const e=d.assignedSlot||d.parentNode,t=Io(e)?e.host:e&&xo(e)?e:null;if(!t||u.has(t))break;u.add(t),c.push(t),d=t}const h="click"===t.type&&"http://www.w3.org/2000/svg"===e.namespaceURI?c.findIndex(e=>Po(e,"button")||Po(e,"a")):-1;h>0&&(s=s||c.slice(0,h+1).some(e=>!ta(e)||ia(e)));const _=[],p={};let g,f=!1,v=!1;if(Dr(c,e=>{const t=ta(e);if(t&&Po(e,"a")&&!i&&!(null==n?void 0:n.includes("href"))){const i=e.getAttribute("href");f=!!(t&&i&&ua(i))&&(o?es(i):i)}at(Ao(e),"ph-no-capture")&&(v=!0),_.push(function(e,t,i,s,n=!1){const r=e.tagName.toLowerCase(),o={tag_name:r};Lo.indexOf(r)>-1&&!i&&(o.$el_text="a"===r.toLowerCase()||"button"===r.toLowerCase()?vu(1024,da(e)):vu(1024,Mo(e)));const a=Ao(e);t||(null==s?void 0:s.includes("class"))||0>=a.length||(o.classes=a.filter(function(e){return""!==e})),Dr(ea(e)?[]:e.attributes,function(i){var r;if((!ia(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&!(null==s?void 0:s.includes(i.name))&&!t&&ua(i.value)&&(!yt(r=i.name)||"_ngcontent"!==r.substring(0,10)&&"_nghost"!==r.substring(0,7))){let e=i.value;"class"===i.name&&(e=Fo(e).join(" ")),o["attr__"+i.name]=vu(1024,"href"===i.name&&n?es(e):e)}});let l=1,c=1,u=e;for(;u=mu(u);)l++,u.tagName===e.tagName&&c++;return o.nth_child=l,o.nth_of_type=c,o}(e,i,s,n,o)),Dr(function(e){if(!ta(e))return{};const t={};return Dr(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&&ua(s)&&(t[i]=s)}}),t}(e),(e,t)=>{({}).hasOwnProperty.call(p,t)||(p[t]=e)})}),v)return{props:{},explicitNoCapture:v};if(h>0&&(e=c[h],_.splice(0,h)),s||(_[0].$el_text=Po(e,"a")||Po(e,"button")?da(e):Mo(e)),f){var m,y;_[0].attr__href=f;const e=null===(m=Fa(f))||void 0===m?void 0:m.host,t=null===(y=hu())||void 0===y||null===(y=y.location)||void 0===y?void 0:y.host;e&&t&&e!==t&&(g=f)}return{props:Nr((S=t.type,{$event_type:S,$ce_version:1}),r?{}:{$elements:_},{$elements_chain:(b=_,pt(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 n=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),r={};return Br(n).sort(([e],[t])=>function(e,t){return t>e?-1:e>t?1:0}(e,t)).forEach(([e,t])=>r[_a(e.toString())]=_a(t.toString())),s+=":",s+=Br(r).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:pa(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return Br(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}const bu="autocapture";var Su=class{_clearPointer(){this._pointerDown=void 0,clearTimeout(this._pointerExpiry),this._pointerExpiry=void 0}_isExcludedPointerTarget(e){var t;if(!ta(e))return!0;const i=null!==(t=this._refreshConfig().css_selector_ignorelist)&&void 0!==t?t:Uo,s=new Set;let n=e;for(;n;){if(s.size>=1e3||s.has(n))return!0;s.add(n);const e=n,t=Ao(e);if(at(t,"ph-no-capture")||at(t,"ph-sensitive")||ia(e)||i.some(t=>Do(e,t)))return!0;const r=n.assignedSlot||n.parentNode;n=Io(r)?r.host:r&&xo(r)?r:null}return!1}_trackPointer(e){if(!this.isEnabled||"pointercancel"===e.type)return void this._clearPointer();if("pointerdown"===e.type){var t;this._clearPointer();const i=Oo(e);return void(e.isPrimary&&0===e.button&&!e.ctrlKey&&i&&xo(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=Oo(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&&(Po(s,"html")||Po(s,"body"))){var n,r,o;if(i.excluded)return null;const e=null!==(n=this._refreshConfig().css_selector_ignorelist)&&void 0!==n?n:Uo;return[s,null===(r=_u())||void 0===r?void 0:r.documentElement,null===(o=_u())||void 0===o?void 0:o.body].some(t=>{if(!t)return!1;const i=Ao(t);return at(i,"ph-no-capture")||at(i,"ph-sensitive")||!ta(t)||ia(t)||e.some(e=>Do(t,e))})?null:i.target}}constructor(e){this._configSource=e,this.name=bu,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 du(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(){const e=hu(),t=_u();if(!this.isBrowserSupported())return void fu.info("Disabling Automatic Event Collection because this browser is not supported");if(!e||!t)return;this._listenerWindow=e,this._listenerDocument=t;const i=this._domEventHandler=t=>{t=t||(null==e?void 0:e.event);try{if("blur"===t.type)return void this._clearPointer();if(0===t.type.indexOf("pointer"))return void this._trackPointer(t);const e="click"===t.type?this._recoverClickTarget(t):void 0;if(St(e))return;this._captureEvent(t,"$autocapture",e)}catch(e){fu.error("Failed to capture event",e)}};if(Wr(e,"blur",i),Wr(t,"submit",i,{capture:!0}),Wr(t,"change",i,{capture:!0}),Wr(t,"click",i,{capture:!0}),Dr(["pointerdown","pointermove","pointerup","pointercancel"],e=>{Wr(t,e,i,{capture:!0})}),this._refreshConfig().capture_copied_text){const i=this._copiedTextHandler=t=>{t=t||(null==e?void 0:e.event);try{this._captureEvent(t,pu)}catch(e){fu.error("Failed to capture clipboard event",e)}};Wr(t,"copy",i,{capture:!0}),Wr(t,"cut",i,{capture:!0}),Wr(t,"paste",i,{capture:!0})}}_removeDomEventHandlers(){const e=this._listenerWindow,t=this._listenerDocument;this._clearPointer(),this._domEventHandler&&(null==e||e.removeEventListener("blur",this._domEventHandler),Dr(["pointerdown","pointermove","pointerup","pointercancel"],e=>{null==t||t.removeEventListener(e,this._domEventHandler,!0)}),null==t||t.removeEventListener("submit",this._domEventHandler,!0),null==t||t.removeEventListener("change",this._domEventHandler,!0),null==t||t.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==t||t.removeEventListener("copy",this._copiedTextHandler,!0),null==t||t.removeEventListener("cut",this._copiedTextHandler,!0),null==t||t.removeEventListener("paste",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._listenerWindow=void 0,this._listenerDocument=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;kt(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=>{var n;const r=null===(n=_u())||void 0===n?void 0:n.querySelectorAll(i);null==r||r.forEach(n=>{e!==n&&t!==n||at(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(A),s=this._isDisabledServerSide,n=this._refreshConfig();if(!n.remoteRequestsDisabled&&!this._hasReceivedConfigResponse)return!1;const r=n.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(St(s)&&!kt(i)&&!r)return!1;const o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!n.enabled&&!o}_captureEvent(e,t="$autocapture",i){if(!this.isEnabled)return void this._clearPointer();let s=i||Oo(e);To(s)&&(s=s.parentNode||null);const n=this._compileUrlPatterns();var r;"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&n.rageclick&&(null===(r=this.rageclicks)||void 0===r?void 0:r.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime()))&&Jo(s,n.rageclick)&&this._captureEvent(e,"$rageclick",i);const o=t===pu,a=o?ls(ls({},n),{},{dom_event_allowlist:void 0}):n;if(s&&function(e,t,i,s,n,r){var o;const a=typeof window>"u"?void 0:window;if(!a||Zo(e))return!1;if((null==i?void 0:i.url_allowlist)&&!Ro(i.url_allowlist,r))return!1;if((null==i?void 0:i.url_ignorelist)&&Ro(i.url_ignorelist,r))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:l,targetElementList:c,isComplete:u}=Xo(e,s);if(!u)return!1;if(!function(e,t){const i=null==t?void 0:t.element_allowlist;if(mt(i))return!0;for(const t of e)if(i.some(e=>t.tagName.toLowerCase()===e))return!0;return!1}(c,i))return!1;if(!No(c,null==i?void 0:i.css_selector_allowlist))return!1;if(No(c,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:Uo))return!1;try{const i=a.getComputedStyle(e);if(i&&"pointer"===i.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}const d=e.tagName.toLowerCase();switch(d){case"html":return!1;case"form":return(n||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(n||["change","click"]).indexOf(t.type)>=0;default:return l?(n||["click"]).indexOf(t.type)>=0:(n||["click"]).indexOf(t.type)>=0&&(Lo.indexOf(d)>-1||"true"===e.getAttribute("contenteditable"))}}(s,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:n.getCurrentUrl}})){var l;const{props:i,explicitNoCapture:r,target:o}=yu(s,{e:e,maskAllElementAttributes:n.maskAllElementAttributes,maskAllText:n.maskAllText,elementAttributeIgnoreList:n.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:n.disableCaptureUrlHashes});if(r)return!1;const a=this.getElementSelectors(s,o);if(a&&a.length>0&&(i.$element_selectors=a),t===pu){const t=e.type||"clipboard";if("paste"!==t){var c,u;const e=null===(c=hu())||void 0===c||null===(c=c.getSelection())||void 0===c?void 0:c.toString(),t=$o(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}if("$autocapture"===t&&"change"===e.type&&n.capture_value_css_selector_allowlist&&!n.maskAllText&&(Po(d=s,"input")?!at(gu,d.type):Po(d,"textarea")||Po(d,"select")&&!d.multiple)&&function(e,t){var i;if(!ta(e))return!1;const s=null!==(i=t.css_selector_ignorelist)&&void 0!==i?i:Uo,n=new Set;let r=e;for(Po(e,"select")&&(r=e.options[e.selectedIndex]||e);r;){const e=r,t=Ao(e);if(n.size>=1e3||n.has(r)||at(t,"ph-sensitive")||at(t,"ph-no-capture")||s.some(t=>Do(e,t)))return!1;n.add(r);const i=r.assignedSlot||r.parentNode;r=Io(i)?i.host:i&&xo(i)?i:null}return!0}(s,n)&&!s.querySelector(".ph-no-capture, .ph-sensitive")){const e=n.capture_value_css_selector_allowlist;let t=!1;try{t=gt(e)?!!e(s):pt(e)&&e.some(e=>Do(s,e))}catch(e){fu.error("capture_value_css_selector_allowlist threw",e)}t&&(i.$input_value=s.value)}return null===(l=this._client)||void 0===l||l.capture(t,i),!0}var d}isBrowserSupported(){var e;return gt(null===(e=_u())||void 0===e?void 0:e.querySelectorAll)}};const wu="featureFlags",Cu="logs",Eu=()=>{var e;return(null==s||null===(e=s.performance)||void 0===e?void 0:e.now)?s.performance.now():Date.now()},ku=[],xu=[50,75,100,150,200,300,400,500,750,1e3,1500,2e3,3e3,5e3,1e4],Pu=[5,10,25,...xu];var Tu=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);mt(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)}},Iu=class{constructor(e){this.instance=e,this._logger=Mr,this.kv=new Tu(e),this.onSession=e=>Cl(this.instance.onSessionId(t=>{try{e(t)}catch(e){this._logger.error("Browser extension session listener failed",e)}})),this.onEvent=e=>Cl(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),Cl(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(H);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,n;const r=null===(e=this.instance.sessionManager)||void 0===e?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:null!==(t=null==r?void 0:r.sessionId)&&void 0!==t?t:"",windowId:null!==(i=null==r?void 0:r.windowId)&&void 0!==i?i:"",sessionStartTimestamp:null!==(s=null==r?void 0:r.sessionStartTimestamp)&&void 0!==s?s:0,lastActivityTimestamp:null!==(n=null==r?void 0:r.lastActivityTimestamp)&&void 0!==n?n:0}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0,lastActivityTimestamp:0}}}get isOptedOut(){return this.instance.has_opted_out_capturing()}get canCapture(){return gt(this.instance.is_capturing)?this.instance.is_capturing():!this.isOptedOut}get isRateLimited(){var e;return!!(null===(e=this.instance.rateLimiter)||void 0===e?void 0:e.isClientRateLimited)}get projectToken(){return this.instance.config.token}getExtension(e){let t;switch(e){case wu:case"featureFlagsCommon":t=this.instance.featureFlags;break;case Cu:t=this.instance.logs;break;case"surveys":t=this.instance.surveys;break;case bu:t=this.instance.autocapture}return t}capture(e,t,i){if(!i)return this._notRateLimited(this.instance.capture(e,t));const s=ls({timestamp:i.timestamp,uuid:i.uuid,$set:i.set,$set_once:i.setOnce},"unload"===i.delivery?{transport:"sendBeacon",send_instantly:!0}:{});return this._notRateLimited(this.instance.capture(e,t,s))}_notRateLimited(e){var t;return!mt(e)||!(null===(t=this.instance.rateLimiter)||void 0===t?void 0:t.lastEventRateLimited)}registerDynamicEventProperties(e){return Cl(this.instance._registerExtensionEventProperties(e))}sendRequest(e){var t=this;return Dt(function*(e,i={}){var n;const r=null!==(n=i.target)&&void 0!==n?n:"api",o=i.query?vc(e,i.query):e,a=t.instance.requestRouter.endpointFor(r,o),l={method:i.method,url:a,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?nt.Base64:void 0,timestampMode:i.sentAt};return"api"===r&&"/i/v1/logs"===e&&(l.batchKey="logs"),"sendBeacon"===i.transport?(t.instance._send_request(l),{statusCode:202}):new Promise(e=>{var i;if(l.callback=e,"flags"===r&&(null===(i=t.instance.config.metrics)||void 0===i?void 0:i.flags)){let i,n;l.onDispatch=()=>{i=Eu()},l.onSend=e=>{n=(e=>{try{return(e=>{var t;const i=null==s?void 0:s.PerformanceObserver,n=null===(t=Fa(e))||void 0===t?void 0:t.href;if(!i||!n)return;const r=Eu(),o={name:n,before:1/0,inFlight:!0};let a,l,c,u=1/0,d=!1;const h=()=>{d||(d=!0,clearTimeout(c),g.disconnect(),ku.splice(ku.indexOf(o),1))};let _=!1;const p=e=>{for(const t of e){const e=t.startTime;t.name!==n||(_?r>=e:r>e)||e>=o.before||a&&e>=a.startTime||(a=t)}if(a&&l&&u>=a.startTime){const e=l;h(),e(a)}},g=new i(e=>p(e.getEntriesByName(n,"resource")));g.observe({entryTypes:["resource"]});for(const e of ku)e.name===n&&(e.before=Math.min(e.before,r),_=_||e.inFlight);return ku.push(o),{take(e,t){d||(u=e,o.inFlight=!1,l=t,c=setTimeout(h,5e3),gt(g.takeRecords)&&p(g.takeRecords()))},stop:h}})(e)}catch(e){return}})(e)},l.callback=s=>{if(e(s),mt(i))return;const r=i,o=Eu();try{const e=((e,t)=>{var i,s;const n=t.statusCode||void 0,r={"server.address":(null!==(i=null===(s=Fa(e))||void 0===s?void 0:s.hostname)&&void 0!==i?i:e).replace(/^\[(.*)\]$/,"$1")};n&&(r["http.response.status_code"]=n);const o=((e,t)=>e?400>e?void 0:String(e):"AbortError"===(null==t?void 0:t.name)?"timeout":"_OTHER")(n,t.error);o&&(r["error.type"]=o);const a=Ia();return a&&(r["client.timezone"]=a),r})(a,s);if(t._recordFlagsHistogram("posthog.flags.request.duration",o-r,xu,e),s.statusCode&&n)return void n.take(o,i=>t._recordFlagsSplit(i,r,o,e))}catch(e){Mr.error("Failed to record the /flags request timing",e)}null==n||n.stop()}}t.instance._send_request(l)})}).apply(this,arguments)}_recordFlagsSplit(e,t,i,s){if(e.responseEnd>=e.startTime)try{const n=Math.min(e.responseEnd,i);this._recordFlagsHistogram("posthog.flags.request.pre_send_duration",e.startTime-t,Pu,s),this._recordFlagsHistogram("posthog.flags.request.network_duration",n-e.startTime,xu,s),this._recordFlagsHistogram("posthog.flags.request.main_thread_duration",i-n,Pu,s)}catch(e){Mr.error("Failed to record the /flags request timing split",e)}}_recordFlagsHistogram(e,t,i,s){var n;null===(n=this.instance.metrics)||void 0===n||n.histogram(e,t,{unit:"ms",attributes:ls({},s),bounds:i})}};const Fu={};let Ru=0;const Au=()=>{},$u='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Mu="Surveys module not available",Ou="sanitize_properties is deprecated. Use before_send instead",Lu="Invalid value for property_denylist config: ",Du=["$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"],Nu=["$feature_flag_called","$$heatmap","$snapshot"],Bu=e=>"$"===e.charAt(0)&&!at(Nu,e),Uu=/^[A-Za-z0-9_-]{1,400}$/,zu=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,Hu=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,qu=["token","distinct_id",Le],ju="posthog",Wu=[...qc].sort()[qc.length-1],Vu=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},Gu=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:jr(null==o?void 0:o.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Au,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:!0,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:a&&yt(null==a?void 0:a.search)&&-1!==a.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==s||null===(t=s.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){Mr.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:Je,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:Au},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:Ho,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:Vu(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))},Ku=[["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"]],Yu=e=>{const t={};for(const[i,s]of Ku)mt(e[i])||(t[s]=e[i]);const i=Nr({},t,e),s=e.__preview_external_dependency_versioned_paths;return mt(s)||(mt(e.strict_script_versioning)&&(i.strict_script_versioning=!!s),yt(s)&&mt(e.asset_host)&&(i.asset_host=s)),pt(e.property_blacklist)&&(mt(e.property_denylist)?i.property_denylist=e.property_blacklist:pt(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:Mr.error(Lu+e.property_denylist)),i};var Qu=class{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){Mr.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},Ju=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()}_warnIfHistoryAutocaptureMissing(){if(this._hasWarnedAboutMissingHistoryAutocapture)return;if(!this._originalUserConfig||!("capture_pageview"in this._originalUserConfig))return;if(ls(ls({},e.__defaultExtensionClasses),this.config.__extensionClasses).historyAutocapture)return;const t=this.config.capture_pageview;("history_change"===t||ft(t)&&(t.path||t.search||t.hash&&!this.config.disable_capture_url_hashes))&&(this._hasWarnedAboutMissingHistoryAutocapture=!0,Mr.warn("capture_pageview is set to capture history changes, but the history autocapture extension is not loaded, so only the first pageview of each page load is captured. With the slim bundle, pass __extensionClasses: { historyAutocapture: AnalyticsExtensions.historyAutocapture } from 'posthog-js/dist/extension-bundles', or set capture_pageview: true to capture page loads only."))}_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(eo());this.register({distinct_id:t,$device_id:t}),e.set_property(Te,Ye)}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._botFilterWarned=!1,this._isPageUnloading=!1,this._isShutdown=!1,this.webPerformance=new Qu,this._personProcessingSetOncePropertiesSent=!1,this.version=i.LIB_VERSION,this.__loadExternalDependency=void 0,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new Bc,this._extensions=[],this._extensionEventPropertyProducers=[],this._replayDebugPropertiesPaused=!1,this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._hasWarnedAboutMissingHistoryAutocapture=!1,this._isConsentTransition=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Gu(),this.SentryIntegration=Ca,this.sentryIntegration=e=>function(e,t){const i=wa(e,t);return{name:Sa,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 Lc(this),this.pageViewManager=new Ea(this),this.rateLimiter=new Tl(this),this.requestRouter=new su(this),this.consent=new Co(this),this.externalIntegrations=new uu(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=yt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{const s=yt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",e=>Mr.info(`send "${null==e?void 0:e.event}"`,e))}init(t,i,s){if(s&&s!==ju){var n;const r=null!==(n=Fu[s])&&void 0!==n?n:new e;return r._init(t,i,s),Fu[s]=r,Fu[ju][s]=r,r}return this._init(t,i,s)}_init(e,t={},n){var r,o,a;const l=yt(e)?e.trim():"";if(!l)return Mr.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var c;if(this.__loaded)return l!==(null===(c=this.config)||void 0===c?void 0:c.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('${l}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Gu(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 u=Gu(t.defaults),d=Yu(t),h=Nr({},u,d,{name:n,token:l});ft(u.rageclick)&&ft(d.rageclick)&&(h.rageclick=Nr({},u.rageclick,d.rageclick)),ft(u.session_recording)&&ft(d.session_recording)&&(h.session_recording=Nr({},u.session_recording,d.session_recording)),this.set_config(h),this.config.on_xhr_error&&Mr.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:dl.GZipJS;const _=this._is_persistence_disabled(),p=!this._inCookielessMode();if(this.persistence=new ul(this.config,_,!0,p),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new ul(ls(ls({},this.config),{},{persistence:"sessionStorage"}),_,!1,p),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!_&&wo._is_supported()){const e=wo._parse(this._sessionRegisteredPropertiesStorageKey);pt(e)&&e.forEach(e=>{yt(e)&&this._sessionRegisteredPropKeys.add(e)})}else wo._remove(this._sessionRegisteredPropertiesStorageKey);const g=ls({},this.persistence.props),f=ls({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new $c((e,t)=>this._send_retriable_request(e,t),this.config.request_queue_config),this._retryQueue=new Oc(this),this.__request_queue=[];const v=this._inCookielessMode();v||(this.sessionManager=new Hc(this),this.sessionPropsManager=new Nc(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?(Mr.info("Deferring extension initialization to improve startup performance"),this._extensionInitTimeout=setTimeout(()=>{this._extensionInitTimeout=void 0,this._initExtensions(v)},0)):(Mr.info("Initializing extensions synchronously"),this._initExtensions(v)),i.DEBUG=i.DEBUG||this.config.debug,i.DEBUG&&Mr.info("Starting in debug mode",{this:this,config:t,thisC:ls({},this.config),p:g,s:f}),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 m=null===(o=t.bootstrap)||void 0===o?void 0:o.distinctID;if(this._hasStableInitialDistinctId=!!m&&!bt(m),null===(a=t.bootstrap)||void 0===a?void 0:a.distinctID){const e=t.bootstrap.distinctID,i=this.get_distinct_id(),s=this.persistence.get_property(Te);if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"anonymous"===s)this.identify(e);else if(t.bootstrap.isIdentifiedID&&null!=i&&i!==e&&"identified"===s)Mr.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(eo()),s=t.bootstrap.isIdentifiedID?i:e;this.persistence.set_property(Te,t.bootstrap.isIdentifiedID?Qe:Ye),this.register({distinct_id:e,$device_id:s})}}if(v)this.register_once({distinct_id:Oe,$device_id:null},"");else if(!this.get_distinct_id()){const e=this.config.get_device_id(eo());this.register_once({distinct_id:e,$device_id:e},""),this.persistence.set_property(Te,Ye)}return Wr(s,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Wr(s,"pageshow",e=>{if(this._isPageUnloading=!1,!this._isShutdown){var t;if(e.persisted&&this.persistence){const e=this.persistence.get_property(z),t=this.persistence.get_property(Te);this.persistence.load(),this._processCookieIdentityChange()||e===this.persistence.get_property("distinct_id")&&t===this.persistence.get_property("$user_state")||this._processIdentityChange()}null===(t=this._retryQueue)||void 0===t||t.resume()}}),t.segment?ba(this,()=>this._loaded()):this._loaded(),gt(this.config._onCapture)&&this.config._onCapture!==Au&&(Mr.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",e=>this.config._onCapture(e.event,e))),this.config.ip&&Mr.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 Wc.apply(this,arguments)}().then(e=>{e&&this.register({[q]:e})}).catch(Au),this}_isSharedExtension(e){const t=e;return yt(t.name)&&gt(t.setup)}_enrollExtension(e,t){var i=this;this._isSharedExtension(e)?t.push(Dt(function*(){try{yield e.setup(i._getBrowserClientAdapter())}catch(i){Mr.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){Mr.error(`Failed to dispose extension "${e.name}"`,t)}}})):this._extensions.push(e)}_enrollFeatureFlags(){var t,i,s,n=this;const r=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(r)if(this.featureFlags&&this.featureFlags instanceof r||(null===(o=this._featureFlagsReloadingUnsubscribe)||void 0===o||o.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new r(this)),gt(this.featureFlags.onReloading)&&gt(this.featureFlags.setup)){if(!this._featureFlagsReloadingUnsubscribe){this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading(()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)});const e=this.featureFlags;Dt(function*(){try{yield e.setup(n._getBrowserClientAdapter())}catch(t){Mr.error("Failed to set up feature flags",t);const i=n._featureFlagsReloadingUnsubscribe;n._featureFlagsReloadingUnsubscribe=void 0;try{null==i||i()}catch(e){Mr.error("Failed to unsubscribe feature flag reloading",e)}try{yield e.dispose()}catch(e){Mr.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),n=[];var r,o,a,l,c,u,d,h;s.exceptions&&this._extensions.push(this.exceptions=null!==(r=this.exceptions)&&void 0!==r?r:new s.exceptions(this)),s.historyAutocapture&&this._extensions.push(this.historyAutocapture=new s.historyAutocapture(this)),this._warnIfHistoryAutocaptureMissing(),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)),s.autocapture&&this._enrollExtension(this.autocapture=new s.autocapture(this),n),s.surveys&&this._enrollExtension(this.surveys=null!==(o=this.surveys)&&void 0!==o?o:new s.surveys(this),n),s.logs&&this._enrollExtension(this.logs=null!==(a=this.logs)&&void 0!==a?a:new s.logs(this),n),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,va)),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));const _=this._extensions.length>0||n.length>0;this.config.disable_scroll_properties||n.unshift(()=>{this.scrollManager.startMeasuringScrollPosition()}),this._extensions.forEach(e=>{e.initialize&&n.push(()=>{var t;null===(t=e.initialize)||void 0===t||t.call(e)})}),n.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(n,i,_)}_processInitTaskQueue(e,t,i){for(var s,n;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,i)},0));const s=e.shift();if(s)try{s()}catch(e){Mr.error("Error initializing extension:",e)}}const r=Math.round(performance.now()-t);i&&r>0?this.register_for_session({[De]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ne]:r}):mt(null===(s=this.sessionPersistence)||void 0===s?void 0:s.props.$sdk_debug_extensions_init_method)&&mt(null===(n=this.sessionPersistence)||void 0===n?void 0:n.props.$sdk_debug_extensions_init_time_ms)||(this.unregister_for_session(De),this.unregister_for_session(Ne)),this.config.__preview_deferred_init_extensions&&Mr.info(`PostHog extensions initialized (${r}ms)`)}_onRemoteConfig(e){if(!o||!o.body)return Mr.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=at(i.supportedCompression,dl.GZipJS)?dl.GZipJS:at(i.supportedCompression,dl.Base64)?dl.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:Je}),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){Mr.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&(null==a?void 0:a.hostname)){const e=a.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()&&Lr(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,n,r;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(et),null===(s=this.logs)||void 0===s||s.flushLogs("sendBeacon"),null===(n=this._requestQueue)||void 0===n||n.unload(),null===(r=this._retryQueue)||void 0===r||r.unload()):this._shouldCapturePageleave()&&this.capture(et,null,{transport:"sendBeacon"})}_send_request(e){Ac(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){Ru++;try{let t;const i=[],s=[],n=[];Lr(e,e=>{if(e)if(t=e[0],pt(t))n.push(e);else if(gt(e))try{e.call(this)}catch(t){Mr.error("Error executing queued PostHog call",e,t)}else pt(e)&&"alias"===t?i.push(e):pt(e)&&-1!==t.indexOf("capture")&&gt(this[t])?n.push(e):s.push(e)});const r=function(e,t){Lr(e,function(e){try{if(pt(e[0])){let i=t;Dr(e,function(e){i=i[e[0]].apply(i,e.slice(1))})}else t[e[0]].apply(t,e.slice(1))}catch(t){Mr.error("Error executing queued PostHog call",e,t)}})};r(i,this),r(s,this),r(n,this)}finally{Ru--}}push(t){if(Ru>0&&pt(t)&&yt(t[0])){const i=e.prototype[t[0]];return void(gt(i)&&i.apply(this,t.slice(1)))}this._execute_array([t])}get _facebookClickIdChannel(){return{property:V,persistenceKey:G,cookieName:"_fbc",pattern:zu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[G]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(G)}}}get _facebookBrowserIdChannel(){return{property:K,persistenceKey:Y,cookieName:"_fbp",pattern:Hu,register:(e,t)=>{var i;return null===(i=this.persistence)||void 0===i?void 0:i.register({[Y]:{value:e,delivered:t}})},unregister:()=>{var e;return null===(e=this.persistence)||void 0===e?void 0:e.unregister(Y)}}}_getPersistedMetaIdentifier(e){var t;const i=null===(t=this.persistence)||void 0===t?void 0:t.get_property(e.persistenceKey);return yt(i)&&e.pattern.test(i)?{value:i,delivered:!1}:ft(i)&&yt(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=Gr(e.cookieName);return yt(t)&&e.pattern.test(t)?t:void 0}_updateFacebookClickId(e,t,i,s){if(!this.persistence)return;const n=this._facebookClickIdChannel,r=this._getPersistedMetaIdentifier(n);if(s)return void n.unregister();if(i)return yt(t)&&zu.test(t)?this._storeMetaIdentifier(n,t,r):void n.unregister();const o=yt(e)&&Uu.test(e)?e:void 0,a=this._readMetaCookie(n);return a&&((e,t,i)=>{const s=e.split(".");if(t)return s[3]===t;if(!i)return!0;const n=i.value.split(".");return s[3]===n[3]||Number(s[2])>Number(n[2])})(a,o,r)?this._storeMetaIdentifier(n,a,r):o?(null==r?void 0:r.value.split(".")[3])===o?{value:r.value,pending:!r.delivered}:this._storeMetaIdentifier(n,`fb.1.${Date.now()}.${o}`,r):r?{value:r.value,pending:!r.delivered}:void 0}_updateFacebookBrowserId(e,t,i){if(!this.persistence)return;const s=this._facebookBrowserIdChannel,n=this._getPersistedMetaIdentifier(s);if(i)return void s.unregister();if(t)return yt(e)&&Hu.test(e)?this._storeMetaIdentifier(s,e,n):void s.unregister();const r=this._readMetaCookie(s);return r?this._storeMetaIdentifier(s,r,n):n?{value:n.value,pending:!n.delivered}:void 0}_markMetaIdentifiersDelivered(e){if(!this.persistence)return;const t=({channel:e,value:t})=>{const i=this._getPersistedMetaIdentifier(e);return(null==i?void 0:i.value)===t&&!i.delivered},i=e.filter(t);i.length&&(this.persistence.refreshMetaIdentifiers(),i.filter(t).forEach(({channel:e,value:t})=>e.register(t,!0)))}capture(e,t,i){var s,n,r;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue))return void Mr.uninitializedWarning("posthog.capture");if(!this.is_capturing())return void Mr.info(`Event "${e}" was not captured because capturing is disabled (opted out or consent pending).`);if(mt(e)||!yt(e))return void Mr.error("No event name provided to posthog.capture");if(this._syncCookielessIdentity(),"$snapshot"===e&&this._inCookielessMode())return;const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return this._botFilterWarned||(this._botFilterWarned=!0,console.warn("[PostHog.js] Events are being dropped because the user agent looks like a bot. Set `opt_out_useragent_filter: true` to capture them, e.g. in end-to-end tests. Note that logs from `captureLog` are not subject to this filter.")),void Mr.info(`Event "${e}" was not captured because the user agent looks like a bot. Set \`opt_out_useragent_filter: true\` to capture it.`);const a=(null==i?void 0:i.skip_client_rate_limiting)?void 0:this.rateLimiter.clientRateLimitContext();if(null==a?void 0:a.isRateLimited)return void Mr.critical("This capture call is ignored due to client rate limiting.");let l;(null==t?void 0:t.$current_url)&&!yt(null==t?void 0:t.$current_url)&&(Mr.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)||Mr.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&&(l=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 c=new Date,u=(null==i?void 0:i.timestamp)||c,d=Zi(null==i?void 0:i.uuid,eo);let h={uuid:d,event:e,properties:this.calculateEventProperties(e,t||{},u,d)};"$pageview"===e&&this.config.__preview_capture_bot_pageviews&&o&&(h.event="$bot_pageview",h.properties.$browser_type="bot"),a&&(h.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const _="$feature_flag_called"===e&&!1===h.properties.$feature_flag_has_experiment&&!0===this.get_property("$minimal_flag_called_events");(null==i?void 0:i.$set)&&!_&&(h.$set=null==i?void 0:i.$set);const p=ft(null==t?void 0:t.$set)?t.$set:void 0,g=pt(null==t?void 0:t.$unset)?t.$unset:[],f=(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||!!p&&e in p,provided:s?null==i||null===(t=i.$set)||void 0===t?void 0:t[e]:null==p?void 0:p[e],unset:-1!==g.indexOf(e)||-1!==f.indexOf(e)}};this.persistence.refreshMetaIdentifiersBeforeCapture();const m=v(V),y=v(K),b=[{channel:this._facebookClickIdChannel,hasProvided:m.hasProvided,update:this._updateFacebookClickId(null==l?void 0:l.fbclid,m.provided,m.hasProvided,m.unset)},{channel:this._facebookBrowserIdChannel,hasProvided:y.hasProvided,update:this._updateFacebookBrowserId(y.provided,y.hasProvided,y.unset)}];for(const{channel:e,hasProvided:t,update:i}of b)i&&!0===h.properties.$process_person_profile&&i.pending&&!t&&!_&&(h.$set=ls({[e.property]:i.value},h.$set));const S=null==i?void 0:i.$unset;S&&(h.$unset=S);const w=_?void 0:this._calculate_set_once_properties(null==i?void 0:i.$set_once,e!==it,e===tt);if(w&&(h.$set_once=w),(null==i?void 0:i._noTruncate)||(C=this.config.properties_string_max_length,h=function(e,t){const i=new Set;return function e(s,n){if(s!==Object(s))return t?t(s):s;if(i.has(s))return;let r;if(i.add(s),pt(s))r=[],Lr(s,t=>{r.push(e(t))});else{const t={};Dr(Ft(s)?Hr(s):s,(s,n)=>{i.has(s)||(t[n]=e(s,n))}),r=t}return r}(e)}(h,e=>yt(e)?e.slice(0,C):e)),h.timestamp=u,mt(null==i?void 0:i.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=c),_&&(h.properties=((e,t=[])=>{const i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return nn.forEach(s),t.forEach(s),i})(h.properties,qu)),e===bl.DISMISSED||e===bl.SENT){const i=null==t?void 0:t[Sl.SURVEY_ID],s=null==t?void 0:t[Sl.SURVEY_ITERATION];ru({id:i,current_iteration:s}),h.$set=ls(ls({},h.$set),{},{[Vc({id:i,current_iteration:s},e===bl.SENT?"responded":"dismissed")]:!0})}else e===bl.SHOWN&&(h.$set=ls(ls({},h.$set),{},{[Sl.SURVEY_LAST_SEEN_DATE]:(new Date).toISOString()}));var C;if(e===kl.SHOWN){const e=null==t?void 0:t[xl.TOUR_TYPE];e&&(h.$set=ls(ls({},h.$set),{},{[`${xl.TOUR_LAST_SEEN_DATE}/${e}`]:(new Date).toISOString()}))}const E=ls(ls({},h.properties.$set),h.$set);if(vt(E)||this.setPersonPropertiesForFlags(E),!wt(this.config.before_send)){const e=this._runBeforeSend(h);if(!e)return;h=e,h.uuid=Zi(h.uuid,eo)}this.sessionRecording&&!this._replayDebugPropertiesPaused&&Bu(e)&&(this._replayDebugPropertiesPaused=!0,setTimeout(()=>this._replayDebugPropertiesPaused=!1,3e4));const k=[];b.forEach(({channel:e,update:t})=>{var i,s,n;const r=null!==(i=null===(s=h.$set)||void 0===s?void 0:s[e.property])&&void 0!==i?i:ft(null===(n=h.properties)||void 0===n?void 0:n.$set)?h.properties.$set[e.property]:void 0;(null==t?void 0:t.pending)&&r===t.value&&k.push({channel:e,value:t.value})}),this._internalEventEmitter.emit("eventCaptured",h);const x=null!==(s=null==i?void 0:i._url)&&void 0!==s?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),P="recordings"===(null==i?void 0:i._batchKey)||/\/s\/(?:\?|$)/.test(x),T=ls(ls(ls({method:"POST",url:x,data:h,compression:"best-available",preferSyncCompression:null==i?void 0:i.send_instantly,timestampMode:P?"body":"capture-body",batchKey:null==i?void 0:i._batchKey},P&&(null===(n=h.properties)||void 0===n?void 0:n.$session_id)?{batchGroup:h.properties.$session_id+(h.properties.$window_id?`-${h.properties.$window_id}`:"")}:{}),(null==i?void 0:i.transport)?{transport:i.transport}:{}),k.length?{fireCallbackOnDrop:!0,callback:e=>{e.statusCode>=200&&300>e.statusCode&&this._markMetaIdentifiersDelivered(k)}}:{});if(!this.config.request_batching||i&&!(null==i?void 0:i._batchKey)||(null==i?void 0:i.send_instantly)){var I;let e;!T.transport&&!T.callback&&vt(null!==(I=this.config.request_headers)&&void 0!==I?I:{})&&this._isPageUnloading&&(e="sendBeacon"),this._send_retriable_request(T,e)}else this._requestQueue.enqueue(T);return null===(r=this.featureFlags)||void 0===r||r.sendFlagCallsPendingCapture(),h}_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 Iu(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;return!!(null===(t=this.persistence)||void 0===t?void 0:t.consumeCookieIdentityChange())&&(this._processIdentityChange(e),!0)}_processIdentityChange(e=!0){var t,i,s;this._cachedPersonProperties=null,"anonymous"===(null===(t=this.persistence)||void 0===t?void 0:t.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()}calculateEventProperties(e,i,n,r,l){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return i;this._syncCookielessIdentity(),this.persistence.syncCookieProperties(),this._processCookieIdentityChange();const c=l?void 0:this.persistence.remove_event_timer(e);let u=ls({},i);if(u.token=this.config.token,u.$config_defaults="latest"===this.config.defaults?Wu:this.config.defaults,this._inCookielessMode()&&(u[Le]=!0),"$snapshot"===e){const e=ls(ls({},this.persistence.properties()),this.sessionPersistence.properties());return u.distinct_id=e.distinct_id,(!yt(u.distinct_id)&&!Ct(u.distinct_id)||bt(u.distinct_id))&&Mr.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),u}const d=function(e,i,n,r=!1){var o,l,c,u;if(!h)return{};const d=e?[...Na,...i||[]]:[],[_,p]=Ui(h),[g,f]=function(e){for(let t=0;ji.length>t;t++){const[i,s,n]=ji[t],r=e.match(i);if(r){const t=n&&e.match(n)||r;return[s,(null==t?void 0:t[1])||""]}}return["",""]}(h),v=function(){const e="u">typeof navigator?navigator:void 0;return(null==e?void 0:e.brave)?{brave:!0}:{}}(),m={};mt(n)||(m.detectGoogleSearchApp=n);const y={},b=null===(o=navigator)||void 0===o||null===(o=o.userAgentData)||void 0===o?void 0:o.platform,S=null===(l=navigator)||void 0===l?void 0:l.maxTouchPoints,w=null==s||null===(c=s.screen)||void 0===c?void 0:c.width,C=null==s||null===(u=s.screen)||void 0===u?void 0:u.height,E=null==s?void 0:s.devicePixelRatio;mt(b)||(y.userAgentDataPlatform=b),mt(S)||(y.maxTouchPoints=S),mt(w)||(y.screenWidth=w),mt(C)||(y.screenHeight=C),mt(E)||(y.devicePixelRatio=E);const k=Nr(zr({$os:_,$os_version:p,$browser:Li(h,navigator.vendor,v,m),$webview_app:g,$webview_app_version:f,$device:zi(h),$device_type:Hi(h,y),$timezone:Ia(),$timezone_offset:Ja()}),{$current_url:La(r?es(null==a?void 0:a.href):null==a?void 0:a.href,d,Ua),$host:null==a?void 0:a.host,$pathname:null==a?void 0:a.pathname,$raw_user_agent:h.length>1e3?h.substring(0,997)+"...":h,$browser_version:Ni(h,navigator.vendor,v,m),$browser_language:Wa(),$browser_language_prefix:Va(),$screen_height:null==s?void 0:s.screen.height,$screen_width:null==s?void 0:s.screen.width,$viewport_height:null==s?void 0:s.innerHeight,$viewport_width:null==s?void 0:s.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&&(k.$sdk_dist_channel=t.SDK_DIST_CHANNEL),k}(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(l,n.getTime(),!0);u.$session_id=e,u.$window_id=t}let _,p;this.sessionPropsManager&&Nr(u,this.sessionPropsManager.getSessionProps());try{var g;if(this.sessionRecording){const t=this.sessionRecording.sdkDebugProperties,i=!this._replayDebugPropertiesPaused&&Bu(e);for(const e in t)(i||at(Du,e))&&(u[e]=t[e])}_=null===(g=this._retryQueue)||void 0===g?void 0:g.length}catch(e){u.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===Xc&&(u.$lib_custom_api_host=this.config.api_host),p="$pageview"!==e||l?"$pageleave"!==e||l?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,r),u=Nr(u,p),"$pageview"===e&&o&&(u.title=o.title),!mt(c)){const e=n.getTime()-c;u.$duration=parseFloat((e/1e3).toFixed(3))}h&&this.config.opt_out_useragent_filter&&(u.$browser_type=this._is_bot()?"bot":"browser");const f=this.persistence.properties(),v=this.sessionPersistence.properties(),m=u.$groups,y=f.$groups;ft(m)&&!vt(m)&&(u.$groups=ls(ls({},ft(y)?y:{}),m)),Dr(["$referrer","$referring_domain"],e=>{e in f&&delete v[e]});const b={};if(this._extensionEventPropertyProducers.length>0)for(const e of this._extensionEventPropertyProducers.slice())try{Nr(b,e())}catch(e){Mr.error("Failed to produce browser extension event properties",e)}u=Nr({},d,f,v,ls(ls({},b),u)),_?u.$sdk_debug_retry_queue_size=_:delete u.$sdk_debug_retry_queue_size,u.$is_identified=this._isIdentified(),pt(this.config.property_denylist)?Dr(this.config.property_denylist,function(e){delete u[e]}):Mr.error(Lu+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const S=this.config.sanitize_properties;S&&(Mr.error(Ou),u=S(u,e));const w=this._hasPersonProcessing();return u.$process_person_profile=w,w&&!l&&this._requirePersonProcessing("_calculate_event_properties"),u}_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 n=this.persistence.get_initial_props(),r=null===(s=this.sessionPropsManager)||void 0===s?void 0:s.getSetOnceProps();let o=Nr({},n,r||{},e||{});const a=this.config.sanitize_properties;return a&&(Mr.error(Ou),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)||!wo._is_supported())return void wo._remove(this._sessionRegisteredPropertiesStorageKey);const t=[];this._sessionRegisteredPropKeys.forEach(e=>t.push(e)),t.length>0?wo._set(this._sessionRegisteredPropertiesStorageKey,t):wo._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:Mu}),()=>{})}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:Mu})}getActiveMatchingSurveys(e,t=!1){this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:Mu})}onActiveMatchingSurveysChanged(e){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(e):(e([],{isLoaded:!1,error:Mu}),()=>{})}renderSurvey(e,t){var i;null===(i=this.surveys)||void 0===i||i.renderSurvey(e,t)}displaySurvey(e,t=au){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:Mu}}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:Mu})}_validateIdentifyId(e){return!e||bt(e)?(Mr.critical("Unique user id has not been set in posthog.identify"),!1):"$posthog_cookieless"===e?(Mr.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())||(Mr.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 Mr.uninitializedWarning("posthog.identify");if(Ct(e)&&(e=e.toString(),Mr.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(),n=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,r=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(j),this.register({distinct_id:e}));const o=(this.persistence.get_property("$user_state")||"anonymous")===Ye,c=e!==s,u=!c&&o;if(c&&o){var l;const n=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:s};this.persistence.set_property(Te,Qe),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$identify",n,{$set:t||{},$set_once:i||{}})&&(this._cachedPersonProperties=Zc(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(Te,Qe);const s=t||{},n=i||{};this.setPersonPropertiesForFlags({$set:s,$set_once:n},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:s,$set_once:n})&&(this._cachedPersonProperties=Zc(e,t,i))}else(t||i)&&this.setPersonProperties(t,i);c||n||r?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(x)):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=Zc(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)):Mr.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(e){var t;const i=(pt(e)?e:[e]).filter(e=>yt(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 Mr.error("posthog.group requires a group type and group key");null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange();const n=this.getGroups(),r=n[e]!==t;if(r&&this.resetGroupPropertiesForFlags(e),this.register({$groups:ls(ls({},n),{},{[e]:t})}),(r||i)&&this._hasPersonProcessing()){const s={$group_type:e,$group_key:t};i&&(s.$group_set=i),this.capture(it,s)}i&&this.setGroupPropertiesForFlags({[e]:i}),r&&!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=kt(e)?e:null==e?void 0:e.resetDeviceID,i=kt(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t=!1,i){var s,n,r,o,a,l;if(Mr.info("reset"),!this.__loaded)return Mr.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===(n=this.featureFlags)||void 0===n||null===(r=n.updateConfig)||void 0===r||r.call(n,this.config,this._shouldDisableFlags());const u=this.get_property(H),d=this.get_property(q),h=this.get_property(oe);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 f=!1;try{var v,m,y,b,S,w,C,E,k,x,P,T,I;if(null===(v=this.persistence)||void 0===v||v.clear(),null===(m=this.sessionPersistence)||void 0===m||m.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),mt(h)||null===(x=this.persistence)||void 0===x||x.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===(S=this.conversations)||void 0===S||S.reset(),null===(w=this.logs)||void 0===w||w.reset(),null===(C=this.metrics)||void 0===C||C.reset(),null===(E=this.persistence)||void 0===E||E.set_property("$user_state","anonymous"),null===(k=this.sessionManager)||void 0===k||k.resetSessionId(),this._cachedPersonProperties=null,"always"===this.config.cookieless_mode)this.register_once({distinct_id:Oe,$device_id:null},"");else{const t=this.config.get_device_id(eo());this.register_once({distinct_id:t,$device_id:e?t:u},""),e||mt(d)||this.register({[q]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),i)if(i.distinctID&&!this._inCookielessMode()&&(null===(I=this.persistence)||void 0===I||I.set_property("$user_state",i.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:i.distinctID})),null===(P=this.featureFlags)||void 0===P||P.initialize(),!wt(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,f=!0}finally{var F,R;this._isConsentTransition=g,p&&(null===(F=this.persistence)||void 0===F||null===(R=F._endCookieSyncSuppression)||void 0===R||R.call(F,f))}var A;this._lastRemoteConfig&&(null===(A=this.conversations)||void 0===A||A.onRemoteConfig(this._lastRemoteConfig)),this.reloadFeatureFlags()}shutdown(e){var t=this;return Dt(function*(){if(!t.__loaded)return void Mr.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&&gt(e.then)&&e.then(void 0,e=>{Mr.error("Error during shutdown",e)})}catch(e){Mr.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 n;const t=null!==(n=e.timestampLookBack)&&void 0!==n?n: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")?(Mr.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(mt(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(j,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(Mr.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){const t=ls({},this.config);if(ft(e)){var s,n,r,o,a,l,c,u,d,h,_,p,g,f;Nr(this.config,Yu(e));const S=this._is_persistence_disabled();if(this.persistence){const e="sessionStorage"===this.config.persistence||"memory"===this.config.persistence;var v,m;if(e&&this.sessionPersistence!==this.persistence&&(null===(v=this.sessionPersistence)||void 0===v||v.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 ul(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;kt(w)&&(this.config.debug=w),kt(this.config.debug)&&(this.config.debug?(i.DEBUG=!0,ao._is_supported()&&ao._set("ph_debug",!0),Mr.info("set_config",{config:e,oldConfig:t,newConfig:ls({},this.config)})):(i.DEBUG=!1,ao._is_supported()&&ao._remove("ph_debug"))),null===(s=this.featureFlags)||void 0===s||null===(n=s.updateConfig)||void 0===n||n.call(s,this.config,this._shouldDisableFlags()),null===(r=this.exceptionObserver)||void 0===r||r.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===(f=this.externalIntegrations)||void 0===f||f.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&ba(this,Au,!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,n,r,o,a;Object.values(i).some(Boolean)&&(null===(s=this.sessionManager)||void 0===s||s.checkAndGetSessionAndWindowId(),i.sampling&&(null===(n=this.sessionRecording)||void 0===n||n.overrideSampling()),i.linked_flag&&(null===(r=this.sessionRecording)||void 0===r||r.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:ju;return t!==ju&&(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?(Mr.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(Me,!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,n,r;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===(n=this.persistence)||void 0===n||n.set_disabled(i)),(null===(t=this.sessionPersistence)||void 0===t?void 0:t._disabled)!==i&&(null===(r=this.sessionPersistence)||void 0===r||r.set_disabled(i)),this._persistSessionRegisteredPropKeys(),i}opt_in_capturing(t){var i,s,n;if("always"===this.config.cookieless_mode)return void Mr.warn($u);if(this._inCookielessMode()){var r,o,a,l,c,u;null===(r=this.sessionRecording)||void 0===r||r.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null===(o=this.sessionManager)||void 0===o||o.destroy(),null===(a=this.pageViewManager)||void 0===a||a.destroy(),this.sessionManager=new Hc(this),this.pageViewManager=new Ea(this),this.persistence&&(this.sessionPropsManager=new Nc(this,this.sessionManager,this.persistence));const t=null!==(l=null===(c=this.config.__extensionClasses)||void 0===c?void 0:c.sessionRecording)&&void 0!==l?l:null===(u=e.__defaultExtensionClasses)||void 0===u?void 0:u.sessionRecording;var d,h;t&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new t(this)),this._lastRemoteConfig&&(null===(d=this.sessionRecording)||void 0===d||null===(h=d.onRemoteConfig)||void 0===h||h.call(d,this._lastRemoteConfig)))}const _=1===this.consent.consent;var p,g,f;_&&this._syncCookielessIdentity(),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===(p=this.surveys)||void 0===p||p.loadIfEnabled(),null===(g=this.conversations)||void 0===g||g.loadIfEnabled()),_||!mt(null==t?void 0:t.captureEventName)&&!(null==t?void 0:t.captureEventName)||this.capture(null!==(f=null==t?void 0:t.captureEventName)&&void 0!==f?f:"$opt_in",null==t?void 0:t.captureProperties,{send_instantly:!0}),null===(s=this.persistence)||void 0===s||s.syncCookieProperties(),this._processCookieIdentityChange(),null===(n=this.featureFlags)||void 0===n||n.sendFlagCallsPendingCapture(),this.config.capture_pageview&&this._captureInitialPageview()}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()):Mr.warn($u)}_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:Oe,$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 r?jc(r,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){o&&("visible"===o.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(Xe,{title:o.title},{send_instantly:!0}),this._visibilityStateListener&&(o.removeEventListener(R,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),Wr(o,R,this._visibilityStateListener)))}debug(e){!1===e?(null==s||s.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==s||s.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?(Mr.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,n){const r=t in e&&!wt(e[t]),o=i in e&&!wt(e[i]);return r?e[t]:!!o&&(n&&n.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,Mr)}_runBeforeSend(e){var t;if(wt(this.config.before_send))return e;const i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(Pt),s=pt(this.config.before_send)?this.config.before_send:[this.config.before_send];let n=e;for(const t of s)try{if(n=t(n),wt(n)){const t=`Event '${e.event}' was rejected in beforeSend function`;return xt(e.event)?Mr.warn(`${t}. This can cause unexpected behavior.`):Mr.info(t),null}n.properties&&!vt(n.properties)||Mr.warn(`Event '${e.event}' has no properties after beforeSend function, this is likely an error.`)}catch(t){return Mr.error(`Error in beforeSend function for event '${e.event}':`,t),null}for(const t of i)if(n.properties&&wt(n.properties[t]))return Mr.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 n}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=kt(e)&&!e,i=ao._is_supported()&&"true"===ao._get("ph_debug");return!t&&(!!i||e)}};Ju.__defaultExtensionClasses={},Ju._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]]=Ur(e.prototype[t[i]])}(Ju,["identify"]);const Zu=["[data-ph-capture-value]"];var Xu=class{constructor(e){this._instance=e}refresh(e){var t;const i=this._instance.config,s=ft(i.autocapture)?i.autocapture:void 0;e.enabled=!!i.autocapture,e.rageclick=i.rageclick,e.maskAllElementAttributes=i.mask_all_element_attributes,e.maskAllText=i.mask_all_text,e.disableCaptureUrlHashes=i.disable_capture_url_hashes,e.getCurrentUrl=i.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==s?void 0:s.url_allowlist,e.url_ignorelist=null==s?void 0:s.url_ignorelist,e.dom_event_allowlist=null==s?void 0:s.dom_event_allowlist,e.element_allowlist=null==s?void 0:s.element_allowlist,e.css_selector_allowlist=null==s?void 0:s.css_selector_allowlist,e.css_selector_ignorelist=null==s?void 0:s.css_selector_ignorelist,e.element_attribute_ignorelist=null==s?void 0:s.element_attribute_ignorelist,e.capture_copied_text=null==s?void 0:s.capture_copied_text,e.capture_value_css_selector_allowlist=null!==(t=null==s?void 0:s.capture_value_css_selector_allowlist)&&void 0!==t?t:Zu}};const ed=Or("[ExceptionAutocapture]"),td=()=>{},id=e=>{var t;if(gt(e))return null!==(t=e.__posthog_layer__)&&void 0!==t?t:e.__rrweb_layer__};function sd(e,t,i){try{if(!(t in e))return td;const s={next:e[t]},n=i(function(...e){return s.next.apply(this,e)});return gt(n)&&(n.prototype=n.prototype||{},Object.defineProperties(n,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=n,()=>{if(e[t]===n)return void(e[t]=s.next);let i=e[t],r=id(i);for(;r;){if(r.next===n)return void(r.next=s.next);i=r.next,r=id(i)}}}catch(e){return td}}const nd=Or("[TracingHeaders]"),rd=Or("[Web Vitals]"),od=9e5,ad=["CLS","FCP","INP","LCP"],ld=["INP","LCP"],cd=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],ud="disabled",dd="lazy_loading";function hd(e){return"ph_replay_pending_buffer_"+JSON.stringify([e.persistence_name||e.token,e.token])}const _d=Or("[SessionRecording]"),pd=[Be,Ue,ze,He,qe,je,We,Ve,Ge],gd=Or("[Heatmaps]");function fd(e){return ft(e)&&"clientX"in e&&"clientY"in e&&Ct(e.clientX)&&Ct(e.clientY)}const vd=Or("[Product Tours]"),md=e=>{var t;return!e.config.disable_product_tours&&!!(null===(t=e.persistence)||void 0===t?void 0:t.get_property(se))},yd=["$set_once","$set"],bd=Or("[SiteApps]"),Sd="Error while initializing PostHog app with config id ";function wd(e,t,i){if(wt(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 Cd=class{constructor(e){this._host=e,this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new Bc,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;mt(null===(e=this._host)||void 0===e?void 0:e.subscribeCapture)||(this._captureHookUnsubscribe=null===(t=this._host)||void 0===t?void 0:t.subscribeCapture((e,t)=>{this.on(e,t)}))}dispose(){var e,t,i;null===(e=this._captureHookUnsubscribe)||void 0===e||e.call(this),this._captureHookUnsubscribe=void 0,null===(t=this._host)||void 0===t||null===(i=t.setElementSelectors)||void 0===i||i.call(t,new Set,this),this._debugEventEmitter=new Bc}register(e){var t,i;if(!mt(null===(t=this._host)||void 0===t?void 0:t.subscribeCapture)&&(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._host)||void 0===i?void 0:i.setElementSelectors)){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._host.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;let r=null==e||null===(i=e.properties)||void 0===i?void 0:i.$current_url;if(!(null==e?void 0:e.properties)||!("$current_url"in e.properties))try{var s,n;r=null===(s=this._host)||void 0===s||null===(n=s.getActionUrl)||void 0===n?void 0:n.call(s)}catch(e){return!1}if(!r||"string"!=typeof r)return!1;if(!wd(r,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=>wd(e.href,t.href,t.href_matching||"exact"));const n=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!n&&wd(function(e){const t=e.match(/(?::|")href="(.*?)"/);return t?t[1]:""}(n),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=>wd(e.text,t.text,t.text_matching||"exact")||wd(e.$el_text,t.text,t.text_matching||"exact"));const n=(null==e||null===(i=e.properties)||void 0===i?void 0:i.$elements_chain)||"";return!!n&&(r=function(e){const t=[],i=/(?::|")text="(.*?)"/g;let s;for(;!wt(s=i.exec(e));)t.includes(s[1])||t.push(s[1]);return t}(n),o=t.text,a=t.text_matching||"exact",r.some(e=>wd(e,o,a)));var r,o,a}_checkStepSelector(e,t){var i,s;if(!(null==t?void 0:t.selector))return!0;const n=null==e||null===(i=e.properties)||void 0===i?void 0:i.$element_selectors;if(null==n?void 0:n.includes(t.selector))return!0;const r=(null==e||null===(s=e.properties)||void 0===s?void 0:s.$elements_chain)||"";if(t.selector_regex&&r)try{return new RegExp(t.selector_regex).test(r)}catch(e){}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||Jc(t.properties.reduce((e,t)=>{const i=pt(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)}},Ed=class{constructor(e,t){this._onActivationChanged=t,this._pendingActivatedItems=[],this._host=e,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map}_subscribeSession(){var e,t;this._sessionIdUnsubscribe=null===(e=(t=this._host).subscribeSession)||void 0===e?void 0:e.call(t,e=>this._onSessionIdChanged(e))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Jc(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===hl.Activation?this._eventToItems:this._cancelEventToItems).get(e);let n=[];return this._getItems(e=>{n=e.filter(e=>null==s?void 0:s.includes(e.id))}),n.filter(s=>{var n;const r=null===(n=s.conditions)||void 0===n||null===(n=n[i])||void 0===n||null===(n=n.values)||void 0===n?void 0:n.find(t=>t.name===e);return this._doesEventMatchFilter(r,t)})}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){mt(this._host.subscribeCapture)||(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 Cd(this._host),this._actionMatcher.init(),this._actionMatcher._addActionHook(e=>this.onAction(e)));const n=[];i.forEach(e=>{var t;null===(t=e.conditions)||void 0===t||null===(t=t.actions)||void 0===t||t.values.forEach(t=>{if(n.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(n):this._actionMatcher.register(n)}_mergeItemMaps(e,t){t.forEach((t,i)=>{var s;const n=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach(e=>{n.includes(e)||n.push(e)}),e.set(i,n)})}_setupEventBasedItems(e,t){var i,s,n;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}),o=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}),a=this._buildEventToItemMap(e,hl.Activation),l=this._buildEventToItemMap(e,hl.Cancellation);t?(this._eventToItems=a,this._cancelEventToItems=l):(this._mergeItemMaps(this._eventToItems,a),this._mergeItemMaps(this._cancelEventToItems,l)),(0!==r.length||0!==o.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=(n=this._host).subscribeCapture)||void 0===s?void 0:s.call(n,(e,t)=>{this.onEvent(e,t)})))}onEvent(e,t){var i,s;const n=this._getLogger(),r=(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(r&&this.getActivatedIds().includes(r)){const i=this._activationOutcome(e,r,t);if("consume"===i)return n.info("event consumed activated item, removing it",{event:e,itemId:r}),void this._deactivateItems([r]);if("persist"===i)return n.info("shown item promoted to persisted activation",{event:e,itemId:r}),this._persistActivation(r),void this._clearActivationTimestamps([r])}if(this._cancelEventToItems.has(e)){const i=this._getMatchingItems(e,t,hl.Cancellation);i.length>0&&(n.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;n.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});const o=this._getMatchingItems(e,t,hl.Activation);this._activateItems(o.map(e=>e.id))}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){if(0===e.length)return;const t=!!this._host.getSessionId(),i=[];for(const s of e)t&&this._shouldPersistArmedActivation(s)?this._persistActivation(s)&&this._recordActivationTimestamp(s):i.push(s);i.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...i])]),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(){const e=this._getActivationTimestampsKey();if(!e)return{};const t=this._host.getProperty(e);return t&&"object"==typeof t?t:{}}_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[n,r]of Object.entries(t))e.includes(n)?s=!0:i[n]=r;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 Ct(t)?t:void 0}_getRawPersistedActivatedIds(){const e=this._getActivatedKey();return this._host.getProperty(e)||[]}_getPersistedActivatedIds(){const e=this._getRawPersistedActivatedIds();if(0===e.length)return[];const t=this._host.getProperty(this._getActivatedSessionKey()),i=this._host.getSessionId();return i&&t===i?e:[]}_stampActivationSession(){const e=this._host.getSessionId();e&&this._setActivatedSession(e)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){const t=this._host.getProperty(this._getActivatedSessionKey());if(t&&t!==e){const e=this._getRawPersistedActivatedIds(),t=this._getRawActivationTimestamps();e.length>0&&(this._setActivatedItems([]),e.filter(e=>Ct(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}},kd=class extends Ed{constructor(e,t,i,s){var n;super({subscribeCapture(t){const i=e.onEvent(e=>t(e.event,e));return()=>i.dispose()},subscribeSession(t){const i=e.onSession(t);return()=>i.dispose()},getSessionId(){var t;return null===(t=e.session)||void 0===t?void 0:t.sessionId},getProperty:t=>e.kv.get(t),getActionUrl:null==i?void 0:i.getActionUrl,setElementSelectors:null!==(n=null==i?void 0:i.setElementSelectors)&&void 0!==n?n:(t,i)=>{var s;return null===(s=e.getExtension("autocapture"))||void 0===s?void 0:s.setElementSelectors(t,i)}},s),this._client=e,this._surveys=t,this._subscribeSession()}_getActivatedKey(){return D}_getActivatedSessionKey(){return N}_getActivationTimestampsKey(){return B}_writeActivationTimestamps(e){this._client.kv.set({[B]:e})}_clearActivationTimestampsStore(){this._client.kv.remove(B)}_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 Ct(s)&&s>0}_getShownEventName(){return bl.SHOWN}_getItems(e){this._surveys.getSurveys(e)}_cancelPendingItem(e){this._surveys.cancelPendingSurvey(e)}_getLogger(){return nu}_setActivatedItems(e){this._client.kv.set({[D]:e})}_setActivatedSession(e){this._client.kv.set({[N]:e})}_clearActivatedSession(){this._client.kv.remove(N)}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t,i){var s;if(e===bl.SENT&&!1===(null==i||null===(s=i.properties)||void 0===s?void 0:s.$survey_completed))return"ignore";let n;return this._getItems(e=>{n=e.find(e=>e.id===t)}),!n||function(e){var t;return Gc(e)&&!!(null===(t=e.conditions)||void 0===t||null===(t=t.events)||void 0===t?void 0:t.repeatedActivation)||"always"===e.schedule}(n)?e===bl.SHOWN?"consume":"ignore":e===bl.SHOWN?"persist":e===bl.DISMISSED||e===bl.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}};const xd=(e,t)=>(null==e?void 0:e.then)?e.then(t):t(e),Pd="SDK is not enabled or survey functionality is not yet loaded",Td="Disabled. Not loading surveys.";var Id=class{constructor(e){this._configSource=e,this.name="surveys",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."}),nu.warn("Remote config unavailable. Not loading surveys.");const t=e.config.surveys;if(wt(t))return nu.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=kt(t)?t:t.length>0,nu.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,xd(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,n;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===(n=this._activeMatchingSurveyConditionsUnsubscribe)||void 0===n||n.call(this),this._activeMatchingSurveyConditionsUnsubscribe=void 0,this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach(e=>clearTimeout(e)),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}getRenderContext(){if(!this._client)return;const e=this;return{client:this._client,get config(){return e._config},surveys:e}}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 nu.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void nu.info(Td);if(e.cookielessMode&&this._client.isOptedOut)return void nu.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(mt(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(L),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;if(this._disposed)return;this._surveyManager=e(t),this._surveyEventReceiver=this._createEventReceiver(this._client,this._notifyActiveMatchingSurveyCallbacks);const s=null===(i=this._client)||void 0===i?void 0:i.kv.get(M);s&&this._registerEventOrActionBasedSurveys(s),nu.info("Surveys loaded successfully"),this._startActiveMatchingSurveyConditions(),this._notifyActiveMatchingSurveyCallbacks(),this._notifySurveyCallbacks({isLoaded:!0})}_createEventReceiver(e,t){return new kd(e,this,void 0,t)}_handleSurveyLoadError(e,t){this._surveyInitializationFailed=!0,nu.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){if(this._disposed)return;const i=this._client;if(!i)return e([],{isLoaded:!1,error:Pd});if(this._config.disableSurveys)return nu.info(Td),e([]);const s=i.kv.get(M);if(s&&!t)return e(s,{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=>nu.error("Error in survey callback",e));const n=i.sendRequest("/api/surveys/",{method:"GET",query:{token:i.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then(e=>{try{return this._handleSurveyResponse(i,e)}catch(e){return nu.error("Error processing surveys response",e),this._handleSurveyResponse(i,{statusCode:0,error:e})}},e=>this._handleSurveyResponse(i,{statusCode:0,error:e}));this._getSurveysInFlightPromise=n;const r=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then(t=>{r(),this._disposed||(this._notifyActiveMatchingSurveyCallbacks(t.context),e(t.surveys,t.context))},r).catch(e=>nu.error("Error in survey callback",e))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:Pd}};const i=t.statusCode;if(200!==i||!t.json){const e=`Surveys API could not be loaded, status: ${i}`;return 0!==i?nu.error(e):t.error||nu.warn(e),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:e}}}this._lastSurveyRefreshFailedAt=null;const s=t.json.surveys||[];return e.kv.set({[M]:s,[O]:Date.now()}),this._registerEventOrActionBasedSurveys(s),{surveys:s,context:{isLoaded:!0}}}_registerEventOrActionBasedSurveys(e){const t=e.filter(e=>function(e){return!(!e.start_date||e.end_date)}(e)&&(Gc(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)));this._registerSurveyTriggers(t)}_registerSurveyTriggers(e){var t;null===(t=this._surveyEventReceiver)||void 0===t||t.replace(e)}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e;const t=null===(e=this._client)||void 0===e?void 0:e.kv.get(O);return Ct(t)&&Date.now()-t>3e5}_isSurveyRefreshBackingOff(){return Ct(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};ru(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}this._notifyActiveMatchingSurveyCallbacks()}_notifySurveyCallbacks(e){for(const t of this._surveyCallbacks){if(this._disposed)return;try{e.isLoaded?this.getSurveys(t):t([],e)}catch(e){nu.error("Error in survey callback",e)}}}getActiveMatchingSurveys(e,t=!1){if(!wt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);nu.warn("init was not called")}onActiveMatchingSurveysChanged(e){var t;if(this._disposed)return()=>{};const i={callback:e,active:!0,revision:0};this._activeMatchingSurveyCallbacks.push(i),this._startActiveMatchingSurveyConditions();const s=null===(t=this._client)||void 0===t?void 0:t.kv.get(M);return this._config.disableSurveys||!this._surveyManager&&this._surveyInitializationFailed&&!this._isInitializingSurveys||!s&&!wt(this._lastSurveyRefreshFailedAt)&&!this._getSurveysInFlightPromise?this._notifyActiveMatchingSurveyCallback(i,{isLoaded:!1}):this._surveyManager&&this._notifyActiveMatchingSurveyCallback(i),()=>{var e;i.active=!1,this._activeMatchingSurveyCallbacks=this._activeMatchingSurveyCallbacks.filter(e=>e!==i),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},n=JSON.stringify([s,i]);if(n===e.lastResult)return;e.lastResult=n,e.callback(s,i)}catch(e){nu.error("Error in active matching surveys callback",e)}};try{t&&!t.isLoaded?s([]):this.getActiveMatchingSurveys(s)}catch(e){nu.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(wt(this._surveyManager))return{eligible:!1,reason:Pd};const t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){var t;if(!(null===(t=this._client)||void 0===t?void 0:t.canCapture))return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(wt(this._surveyManager))return{eligible:!1,reason:Pd};const i="string"==typeof e?this._getSurveyById(e):e;return i?this._surveyManager.checkSurveyRenderability(i):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(wt(this._surveyManager))return nu.warn("init was not called"),{visible:!1,disabledReason:Pd};const t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return wt(this._surveyManager)?(nu.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Pd})):new Promise(i=>{this.getSurveys(t=>{var s;const n=null!==(s=t.find(t=>t.id===e))&&void 0!==s?s:null;if(n){const e=this._checkSurveyRenderability(n);i({visible:e.eligible,disabledReason:e.reason})}else i({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,i){var s,n,r;if(!(null===(s=this._client)||void 0===s?void 0:s.canCapture))return;if(wt(this._surveyManager))return void nu.warn("init was not called");const o="string"==typeof e?this._getSurveyById(e):e;if(!(null==o?void 0:o.id))return void nu.warn("Survey not found");if(!ou.includes(o.type))return void nu.warn(`Surveys of type ${o.type} cannot be rendered in the app`);const a=null===(n=typeof document>"u"?void 0:document)||void 0===n?void 0:n.querySelector(t);if(a){if(null===(r=o.appearance)||void 0===r?void 0:r.surveyPopupDelaySeconds){nu.info(`Rendering survey ${o.id} with delay of ${o.appearance.surveyPopupDelaySeconds} seconds`);const e=setTimeout(()=>{var t,s,n;this._renderTimeouts.delete(e),!this._disposed&&(null===(t=this._client)||void 0===t?void 0:t.canCapture)&&(nu.info(`Rendering survey ${o.id} with delay of ${null===(s=o.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds} seconds`),null===(n=this._surveyManager)||void 0===n||n.renderSurvey(o,a,i),nu.info(`Survey ${o.id} rendered`))},1e3*o.appearance.surveyPopupDelaySeconds);return void this._renderTimeouts.add(e)}this._surveyManager.renderSurvey(o,a,i)}else nu.warn("Survey element not found")}displaySurvey(e,t){var i,s;if(!(null===(i=this._client)||void 0===i?void 0:i.canCapture))return;if(wt(this._surveyManager))return void nu.warn("init was not called");const n=this._getSurveyById(e);if(!n)return void nu.warn("Survey not found");let r=n;if((null===(s=n.appearance)||void 0===s?void 0:s.surveyPopupDelaySeconds)&&t.ignoreDelay&&(r=ls(ls({},n),{},{appearance:ls(ls({},n.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==wl.Popover&&t.initialResponses&&nu.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){const e=this._checkSurveyEligibility(n);if(!e.eligible)return void nu.warn("Survey is not eligible to be displayed: ",e.reason)}t.displayType!==wl.Inline?this._surveyManager.handlePopoverSurvey(r,t):this.renderSurvey(r,t.selector,t.properties)}cancelPendingSurvey(e){wt(this._surveyManager)?nu.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)}},Fd=class{constructor(e){this._instance=e}get(){var e,t,i,s;const n=null===(e=this._instance)||void 0===e?void 0:e.config;return{disableSurveys:!!(null==n?void 0:n.disable_surveys),cookielessMode:!!(null==n?void 0:n.cookieless_mode),advancedEnableSurveys:!!(null==n?void 0:n.advanced_enable_surveys),requestTimeoutMs:null!==(t=null==n?void 0:n.surveys_request_timeout_ms)&&void 0!==t?t:1e4,prefillFromUrl:!!(null==n||null===(i=n.surveys)||void 0===i?void 0:i.prefillFromUrl),automaticDisplay:!(null==n?void 0:n.disable_surveys_automatic_display),featureFlagEvaluation:!(null==n?void 0:n.advanced_disable_feature_flags),overrideLanguage:null==n?void 0:n.override_display_language,prepareStylesheet:null==n?void 0:n.prepare_external_dependency_stylesheet,get_current_url:null==n?void 0:n.get_current_url,uiHost:null===(s=this._instance)||void 0===s||null===(s=s.requestRouter)||void 0===s?void 0:s.endpointFor("ui","")}}getExtensions(){const e=null==p?void 0:p.__PosthogExtensions__;if(!e||!this._instance)return;const t=this._instance,{generateSurveys:i}=e,s=g(t);return{generateSurveys:i?e=>i(t,e):void 0,loadExternalDependency:s?e=>s(t,"surveys",e):void 0}}onMatchingConditionsChanged(e){var t,i;const n=null===(t=this._instance)||void 0===t?void 0:t._addCaptureHook(t=>{"$pageview"!==t&&t!==bl.SHOWN&&t!==bl.DISMISSED&&t!==bl.SENT||e()}),r=()=>e();Wr(s,"PHSurveyShown",r);let o=!1;const a=null===(i=this._instance)||void 0===i?void 0:i.onFeatureFlags(()=>{o&&e()});return o=!0,()=>{o=!1,null==n||n(),null==a||a(),null==s||s.removeEventListener("PHSurveyShown",r)}}};const Rd=(()=>(null==s?void 0:s.location)?Da(s.location.hash,"__posthog")||Da(location.hash,"state"):null)(),Ad="_postHogToolbarParams",$d=Or("[Toolbar]"),Md=Or("[FeatureFlags]"),Od=Or("[FeatureFlags]",{debugEnabled:!0}),Ld="\" failed. Feature flags didn't load in time.",Dd=[502,504],Nd=["click","keydown","wheel","touchstart","pointerdown"],Bd="connection_error",Ud=(e,t)=>{const i=Object.keys(t||{}).filter(e=>{var i;return null==t||null===(i=t[e])||void 0===i?void 0:i.failed});if(!i.length)return e||{};const s=ls({},e);return i.forEach(e=>delete s[e]),s},zd=(e,t)=>{const i=ls({},e);return t.forEach(e=>{var t;(null===(t=i[e])||void 0===t?void 0:t.failed)&&delete i[e]}),i},Hd=(e,t)=>!!(null==t?void 0:t.partialResponse)||!!e.errorsWhileComputingFlags,qd=e=>{const t={};for(let i=0;e.length>i;i++)t[e[i]]=!0;return t},jd=e=>{const t={};for(const[i,s]of Br(e||{}))s&&(t[i]=s);return t},Wd=(e,t)=>e.distinctId===t.distinctId&&e.sessionId===t.sessionId&&((e,t)=>{const i=Object.keys(e);return i.length===Object.keys(t).length&&i.every(i=>e[i]===t[i])})(e.groups,t.groups);var Vd=class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=Md,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._firingFeatureFlagsCallbacks=!1,this._flagCallsPendingCapture=new Map,this._sendingFlagCallsPendingCapture=!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;mt(i)||mt(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]"),xd(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&&Wr(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&&!mt(t)&&t>0?t:void 0;this._config.idleRefreshBackoff||(this._dueRefreshIntervalMs=i),i!==this._refreshIntervalMs&&(this._stopAutomaticRefresh(),mt(i)||(this._refreshIntervalMs=i,this._dueRefreshIntervalMs=i,this._scheduleNextRefresh(),(null===(e=this._document)||void 0===e?void 0:e.addEventListener)&&(Wr(this._document,R,this._onVisibilityChange),Lr(Nd,e=>{Wr(this._document,e,this._onUserInteraction,{capture:!0})}))))}_scheduleNextRefresh(){mt(this._refreshIntervalMs)||(mt(this._refreshInterval)||clearInterval(this._refreshInterval),this._lastRefreshAt=Date.now(),this._refreshInterval=setInterval(this._refreshIfDue,this._refreshIntervalMs))}_stopAutomaticRefresh(){var e,t;mt(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),Lr(Nd,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!mt(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")||{},n=e.$enabled_feature_flags||{},r=t.flags||t.featureFlags,o=t.flags?Object.entries(t.flags).filter(([,e])=>!(null==e?void 0:e.failed)).map(([e])=>e):[],a=!!t.errorsWhileComputingFlags&&!!t.flags,l=a||i&&t.flags?o:i&&!pt(r)?Object.keys(r||{}):Array.from(new Set([...Object.keys(s),...Object.keys(n)])),c=this._prop("$feature_flag_payloads")||{},u=e.$feature_flag_payloads||{},d=a||i?l:Array.from(new Set([...Object.keys(c),...Object.keys(u)])),h=!a&&!i,_=!!h||l,p=!!h||d,g={[v]:_,[C]:_,[T]:p};e.$feature_flag_details&&(g[m]=_);for(const t of[S,b,w])mt(e[t])||(g[t]=!0);this._crossTabPersistence.markCrossTabFeatureFlagChanges(g)}_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={},t=this._prop(m);for(const t of[S,I]){const i=this._prop(t);mt(i)||(e[t]=i)}const i=this._prop(v);i&&(e[v]=i.filter(e=>{var i;return!(null==t||null===(i=t[e])||void 0===i?void 0:i.failed)}));const s=this._prop(T);s&&(e[T]=Ud(s,t)),this._baseEventProperties=e;const n=ls({},e),r=Ud(this._prop(C),t);if(r)for(const[e,t]of Object.entries(r))n[`$feature/${e}`]=t;this._eventPropertiesWithFlagValues=n}_isCacheStale(){const e=this._config.cacheTtlMs;if(!e||0>=e)return!1;const t=this._prop(b);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(!mt(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 n,r;const e=null!==(n=null===(r=i.bootstrap)||void 0===r?void 0:r.featureFlagPayloads)&&void 0!==n?n:{},t=Object.keys(s).filter(e=>!mt(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){const s=(null==i?void 0:i.merge)?Ud(this._prop(C),this._prop(m)):{},n=(null==i?void 0:i.merge)?Ud(this._prop(T),this._prop(m)):{},r=ls(ls({},s),e),o=ls(ls({},n),t),a={};for(const[e,t]of Object.entries(r))a[e]={key:e,enabled:tn(t),variant:sn(t),reason:void 0,metadata:mt(null==o?void 0:o[e])?void 0:{id:0,version:void 0,description:void 0,payload:o[e]}};this._receivedFeatureFlags({flags:a})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this._prop(m),t=this._prop(I),i=this._prop(F);if(!i&&!t)return e||{};const s=Nr({},e||{}),n=[...new Set([...Object.keys(i||{}),...Object.keys(t||{})])];for(const e of n){var r,o;const n=s[e],a=null==t?void 0:t[e],l=mt(a)?null!==(r=null==n?void 0:n.enabled)&&void 0!==r&&r:!!a,c=mt(a)?null==n?void 0:n.variant:"string"==typeof a?a:void 0,u=null==i?void 0:i[e],d=ls(ls({},n),{},{enabled:l,variant:l?null!=c?c:null==n?void 0:n.variant:void 0});l!==(null==n?void 0:n.enabled)&&(d.original_enabled=null==n?void 0:n.enabled),c!==(null==n?void 0:n.variant)&&(d.original_variant=null==n?void 0:n.variant),u&&(d.metadata=ls(ls({},null==n?void 0:n.metadata),{},{payload:u,original_payload:null==n||null===(o=n.metadata)||void 0===o?void 0:o.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:tn(s),variant:sn(s),payload:en(t[i])}})}getFlagVariants(){const e=Ud(this._prop(C),this._prop(m)),t=this._prop(I);if(!t)return e||{};const i=Nr({},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=Ud(this._prop(T),this._prop(m)),t=this._prop(F);if(!t)return e||{};const i=Nr({},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._firingFeatureFlagsCallbacks&&this._logger.warn("reloadFeatureFlags() was called inside an onFeatureFlags callback. This callback also runs when flags change in other tabs, so this can cause a request loop."),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(x),this._flagCallsPendingCapture=new Map}sendFlagCallsPendingCapture(){var e;if(0!==this._flagCallsPendingCapture.size&&!this._sendingFlagCallsPendingCapture&&(null===(e=this._client)||void 0===e?void 0:e.canCapture)&&!this._client.isRateLimited){this._sendingFlagCallsPendingCapture=!0;try{const e=this.getFlagVariants();for(const t of Array.from(this._flagCallsPendingCapture.keys())){const i=this._flagCallsPendingCapture.get(t);if(i){if(i.value!==String(e[t])||!Wd(i.context,this._flagCallContext())){this._flagCallsPendingCapture.delete(t);continue}if(this.getFeatureFlagResult(t),this._flagCallsPendingCapture.has(t))break}}}finally{this._sendingFlagCallsPendingCapture=!1}}}_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(E),timezone:Ia()};mt(i.deviceId)||(s.$device_id=i.deviceId),((null==e?void 0:e.disableFlags)||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);const n=this._getValidEvaluationEnvironments();n.length&&(s.evaluation_contexts=n);const r=this._getValidFlagKeys();mt(r)||(s.flag_keys=r);const o=this._config.onlyEvaluateSurveyFeatureFlags,a="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),l=this._requestGeneration,c=this._pendingReloads;this._pendingReloads=new Set,this._activeReloads=c,this._requestInFlight=!0;const u=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},d=e=>{var t,i;const n=null!==(t=e.json)&&void 0!==t?t:{},r=200!==e.statusCode;if(this._requestInFlight=!1,l!==this._requestGeneration)return void u();if(this._trackStatusZeroReachability(e.statusCode),r||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),s.disable_flags&&!this._additionalReloadRequested)return void this._settleReloads(c,"skipped");this._flagsLoadedFromRemote=!r;const a=[];e.error?a.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?Bd:"unknown_error"):200!==e.statusCode&&a.push(`api_error_${e.statusCode}`),n.errorsWhileComputingFlags&&a.push("errors_while_computing_flags");const d=!!(null===(i=n.quotaLimited)||void 0===i?void 0:i.includes("feature_flags"));d&&a.push("quota_limited"),this._set({[y]:a}),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(n,r,{partialResponse:o}),this._settleReloads(c,s.disable_flags?"skipped":a.length||!n.flags&&!n.featureFlags?"error":"loaded"),u()},h=e=>{this._requestInFlight=!1,l===this._requestGeneration?(this._set({[y]:[Bd]}),this._logger.error("Feature flag request failed",e),this._fallBackToPersistedFlags()&&this._fireFeatureFlagsCallbacks(!0),this._settleReloads(c,"error"),u()):u()};let _=null!==(t=this._config.requestMaxRetries)&&void 0!==t?t:1;const p=()=>_>0&&l===this._requestGeneration,g=()=>{if(l!==this._requestGeneration||!this._client||this._config.remoteRequestsDisabled)return this._requestInFlight=!1,this._settleReloads(c,"skipped"),void u();try{i.sendRequest(a,{target:"flags",method:"POST",body:s,compression:this._config.compression,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then(e=>{if((e=>Dd.includes(e.statusCode)||(e=>0===e.statusCode&&e.error instanceof Error&&"AbortError"===e.error.name)(e))(e)&&p())return _--,void setTimeout(g,500);d(e)}).catch(h)}catch(e){h(e)}};g()}_hasStatusZeroCircuitBreakerTripped(){return Aa(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=$a(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."))}_flagsNotLoaded(e){var t;return!this._hasLoadedFlags&&!this.getFlags().length&&!(null===(t=this.getFeatureFlagDetails(e))||void 0===t?void 0:t.failed)}getFeatureFlag(e,t={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(this._flagsNotLoaded(e))return void this._logger.warn('getFeatureFlag for key "'+e+Ld);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={}){var i;if(t.fresh&&!this._flagsLoadedFromRemote)return;if(this._flagsNotLoaded(e))return void this._logger.warn('getFeatureFlagResult for key "'+e+Ld);if(this._checkAndTriggerStaleRefresh())return;const s=null===(i=this._prop("$feature_flag_details"))||void 0===i||null===(i=i[e])||void 0===i?void 0:i.failed,n=s?void 0:this._prop(C),r=s?void 0:this._prop(T),o=this._prop(I),a=!!o&&{}.hasOwnProperty.call(o,e),l=a||!!n&&e in n,c=a?o[e]:null==n?void 0:n[e],u=this._prop(F),d=u&&{}.hasOwnProperty.call(u,e)?u[e]:null==r?void 0:r[e],h=String(c),_=this._prop("$feature_flag_request_id")||void 0,p=this._prop("$feature_flag_evaluated_at")||void 0;let g,f=this._prop("$flag_call_reported")||{};if(this._config.deduplicateCallsPerSession){var v;const e=null===(v=this._client)||void 0===v||null===(v=v.session)||void 0===v?void 0:v.sessionId,t=this._prop(P);e&&e!==t&&(f={},g=e)}if(!t.send_event&&"send_event"in t)g&&this._set({[x]:f,[P]:g});else{var m,y,b;const t=!(null===(m=this._client)||void 0===m?void 0:m.canCapture),i=!t&&!(null===(y=this._client)||void 0===y?void 0:y.isRateLimited);var S;if(i?this._flagCallsPendingCapture.delete(e):(t&&Object.keys(f).length>0&&(f={},this._set({[x]:f})),(null===(S=f[e])||void 0===S?void 0:S.includes(h))||this._holdFlagCall(e,h)),i&&!(null===(b=f[e])||void 0===b?void 0:b.includes(h))){var w,E,k,R,A,M,O,L,D,N,B,U,z;pt(f[e])?f[e].push(h):f[e]=[h],this._set(ls({[x]:f},g?{[P]:g}:{}));const t=this.getFeatureFlagDetails(e),i=[...null!==(w=this._prop("$feature_flag_errors"))&&void 0!==w?w:[]];mt(c)&&i.push((null==t?void 0:t.failed)?"evaluation_failed":"flag_missing");const s={$feature_flag:e,$feature_flag_response:c,$feature_flag_payload:null!=d?d:null,$feature_flag_request_id:_,$feature_flag_evaluated_at:p,$feature_flag_bootstrapped_response:null!==(E=null===(k=this._config.bootstrap)||void 0===k||null===(k=k.featureFlags)||void 0===k?void 0:k[e])&&void 0!==E?E:null,$feature_flag_bootstrapped_payload:null!==(R=null===(A=this._config.bootstrap)||void 0===A||null===(A=A.featureFlagPayloads)||void 0===A?void 0:A[e])&&void 0!==R?R:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};mt(null==t||null===(M=t.metadata)||void 0===M?void 0:M.has_experiment)||(s.$feature_flag_has_experiment=t.metadata.has_experiment),mt(null==t||null===(O=t.metadata)||void 0===O?void 0:O.version)||(s.$feature_flag_version=t.metadata.version);const n=null!==(L=null==t||null===(D=t.reason)||void 0===D?void 0:D.description)&&void 0!==L?L:null==t||null===(N=t.reason)||void 0===N?void 0:N.code;n&&(s.$feature_flag_reason=n),(null==t||null===(B=t.metadata)||void 0===B?void 0:B.id)&&(s.$feature_flag_id=t.metadata.id),mt(null==t?void 0:t.original_variant)&&mt(null==t?void 0:t.original_enabled)||(s.$feature_flag_original_response=mt(t.original_variant)?t.original_enabled:t.original_variant),(null==t||null===(U=t.metadata)||void 0===U?void 0:U.original_payload)&&(s.$feature_flag_original_payload=null==t||null===(z=t.metadata)||void 0===z?void 0:z.original_payload),i.length&&(s.$feature_flag_error=i.join(",")),this._captureFeatureFlagCalled(s)||(this._unmarkFlagCallReported(e,h),this._holdFlagCall(e,h))}else g&&this._set({[x]:f,[P]:g})}return l?{key:e,enabled:!!c,variant:"string"==typeof c?c:void 0,payload:en(d)}:void 0}_captureFeatureFlagCalled(e){try{var t;return!1!==(null===(t=this._client)||void 0===t?void 0:t.capture("$feature_flag_called",e))}catch(e){return this._logger.error("Failed to capture feature flag call",e),!0}}_holdFlagCall(e,t){this._flagCallsPendingCapture.set(e,{value:t,context:this._flagCallContext()})}_flagCallContext(){var e,t,i;return{distinctId:null===(e=this._client)||void 0===e?void 0:e.distinctId,groups:ls({},null===(t=this._client)||void 0===t?void 0:t.groups),sessionId:this._config.deduplicateCallsPerSession?null===(i=this._client)||void 0===i||null===(i=i.session)||void 0===i?void 0:i.sessionId:void 0}}_unmarkFlagCallReported(e,t){const i=this._prop("$flag_call_reported")||{},s=i[e];pt(s)&&s.includes(t)&&(i[e]=s.filter(e=>e!==t),this._set({[x]:i}))}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,t){var i=this;return Dt(function*(){const s=i._client;if(!s)return;const n={distinct_id:s.distinctId,token:s.projectToken,person_properties:{$lib:s.library.name,$lib_version:s.library.version}},r=i._getValidEvaluationEnvironments();r.length&&(n.evaluation_contexts=r);const o=i._getValidFlagKeys();let a;mt(o)||(n.flag_keys=o);try{var l;const t=null===(l=(yield s.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:n,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._flagsNotLoaded(e))return this._logger.warn('isFeatureEnabled for key "'+e+Ld),t.defaultValue;const i=this.getFeatureFlag(e,t);return mt(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;var s,n;this._hasLoadedFlags=!0,!1!==(null==i?void 0:i.persist)&&Hd(e,i)&&(null===(s=this._crossTabPersistence)||void 0===s||null===(n=s.reconcileFeatureFlagsBeforeMerge)||void 0===n?void 0:n.call(s))&&this._clearBootstrapState();const r=this.getFlagVariants(),o=!e.flags&&pt(e.featureFlags),a=((e,t={},i={},s={},n,r=Md)=>{const o=((e,t)=>{const i=e.flags;if(i){const t=Object.fromEntries(Object.keys(i).filter(e=>!i[e].failed).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].failed&&i[e].enabled).filter(e=>{var t;return!mt(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,r),a=o.flags,l=o.featureFlags,c=o.featureFlagPayloads;if(!l)return;const u=e.requestId,d=e.evaluatedAt;if(pt(l)){r.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const e={};if(l)for(let t=0;l.length>t;t++)e[l[t]]=!0;return{[v]:l,[C]:e,[m]:zd(s,l),[T]:Ud(i,s),[w]:!1}}let h=l,_=c,p=a;if(Hd(e,n)){const e=e=>({}.hasOwnProperty.call(t,e)&&!mt(t[e])),r=Object.keys(h),o=_||{};h=ls(ls({},t),h),_=ls(ls({},i),o),((null==n?void 0:n.partialResponse)||a)&&r.forEach(e=>{e in o||null==_||delete _[e]}),p=a?ls(ls({},s),Object.fromEntries(Object.entries(a).filter(([t,i])=>!i.failed||!e(t)))):zd(s,r)}return ls(ls({[v]:Object.keys(jd(h)),[C]:h||{},[T]:_||{},[m]:p||{},[w]:!0===e.minimalFlagCalledEvents},u?{[S]:u}:{}),d?{[b]:d}:{})})(e,r,o?this._prop("$feature_flag_payloads")||{}:this.getFlagPayloads(),o?this._prop("$feature_flag_details")||{}:this.getFlagsWithDetails(),i,this._logger);if(a)if(!1===(null==i?void 0:i.persist)){const e=!mt(this._client.kv.get(C));this._bootstrapState=a,e||this._set(a)}else this._clearBootstrapState(),this._markCrossTabFeatureFlagSnapshot(a,e,!!(null==i?void 0:i.partialResponse)),this._set(a);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([I,F]),this._fireFeatureFlagsCallbacks(),void Od.info("All overrides cleared");if(pt(e))return this._set({[I]:qd(e)}),this._fireFeatureFlagsCallbacks(),void Od.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={},n=i.flags,r=i.payloads;return n&&(s[I]=pt(n)?qd(n):n),r&&(s[F]=r),Object.keys(s).length&&this._set(s),!1===n&&!1===r?this._remove([I,F]):!1===n?this._remove(I):!1===r&&this._remove(F),this._fireFeatureFlagsCallbacks(),!1===n?Od.info("Flag overrides cleared"):n&&Od.info("Flag overrides set",{flags:n}),void(!1===r?Od.info("Payload overrides cleared"):r&&Od.info("Payload overrides set",{payloads:r}))}if(e&&"object"==typeof e)return this._set({[I]:e}),this._fireFeatureFlagsCallbacks(),void Od.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,n;const r=(this._prop("$early_access_features")||[]).find(t=>t.flagKey===e),o={[`$feature_enrollment/${e}`]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};r&&(a.$early_access_feature_name=r.name),i&&(a.$feature_enrollment_stage=i);const l=ls(ls({},this.getFlagVariants()),{},{[e]:t}),c=ls({},this._prop(m)),u=null===(s=c[e])||void 0===s?void 0:s.failed,d=ls({},this._prop(T));u&&(delete c[e],delete d[e]),null===(n=this._crossTabPersistence)||void 0===n||n.markCrossTabFeatureFlagChanges(ls(ls({$active_feature_flags:[e],$enabled_feature_flags:[e]},u?{$feature_flag_details:[e],$feature_flag_payloads:[e]}:{}),{},{$stored_person_properties:Object.keys(o)})),this._set(ls(ls({[v]:Object.keys(jd(l)),[C]:l},u?{[m]:c,[T]:d}:{}),{},{[k]:ls(ls({},this._prop("$stored_person_properties")||{}),o)})),this._fireFeatureFlagsCallbacks();try{var h;null===(h=this._client)||void 0===h||h.capture("$feature_enrollment_update",a)}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t=!1,i){const s=this._prop(f);!s||t?this._getEarlyAccessFeatures(e,i):e(s)}_getEarlyAccessFeatures(e,t){var i=this;return Dt(function*(){const s=i._client;if(!s)return;const n=t?`&${t.map(e=>`stage=${e}`).join("&")}`:"";let r;try{const e=yield s.sendRequest(`/api/early_access_features/?token=${s.projectToken}${n}`,{target:"api",method:"GET",sentAt:"query"});if(!e.json)return;r=e.json.earlyAccessFeatures,i._set({[f]:r})}catch(e){return void i._logger.error("Early access feature request failed",e)}try{e(r)}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(),s=this._firingFeatureFlagsCallbacks;this._firingFeatureFlagsCallbacks=!0,this.featureFlagEventHandlers.forEach(s=>{try{s(t,i,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}}),this._firingFeatureFlagsCallbacks=s}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),n=null==e?void 0:e.$set_once,r={};if(n)for(const e in n)({}).hasOwnProperty.call(n,e)&&(e in i||(r[e]=n[e]));this._set({[k]:ls(ls(ls({},i),r),s)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const i=ls({},this._prop("$stored_person_properties")||{});e.forEach(e=>{delete i[e]}),this._set({[k]:i}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this._remove(k),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({[E]:s}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this._prop("$stored_group_properties")||{};this._set({[E]:ls(ls({},t),{},{[e]:{}})})}else this._remove(E)}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,this._flagCallsPendingCapture=new Map}};const Gd=Or("[FeatureFlags]");var Kd=class{constructor(e,t=!1){this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,n,r,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!==(n=null===(r=e.bootstrap)||void 0===r?void 0:r.featureFlagPayloads)&&void 0!==n?n: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:mt(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:pt(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(Gd.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),mt(e.flag_keys)||pt(e.flag_keys)||Gd.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}};const Yd=e=>Ft(e)&&("RangeError"===e.name&&0===e.message.indexOf("Maximum call stack size exceeded")||"InternalError"===e.name&&"too much recursion"===e.message),Qd=Or("[Error tracking]"),Jd="webkit-masked-url:",Zd=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],Xd=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",Jd],eh=["__firefox__","__gCrWeb"];function th(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=Array(t);t>i;i++)s[i]=e[i];return s}function ih(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=i){var s,n,r,o,a=[],l=!0,c=!1;try{if(r=(i=i.call(e)).next,0===t);else for(;!(l=(s=r.call(i)).done)&&(a.push(s.value),a.length!==t);l=!0);}catch(e){c=!0,n=e}finally{try{if(!l&&null!=i.return&&(o=i.return(),Object(o)!==o))return}finally{if(c)throw n}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return th(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?th(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}const sh=Object.entries,nh=Object.setPrototypeOf,rh=Object.isFrozen,oh=Object.getPrototypeOf,ah=Object.getOwnPropertyDescriptor;let lh=Object.freeze,ch=Object.seal,uh=Object.create,dh="undefined"!=typeof Reflect&&Reflect,hh=dh.apply,_h=dh.construct;lh||(lh=function(e){return e}),ch||(ch=function(e){return e}),hh||(hh=function(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),n=2;i>n;n++)s[n-2]=arguments[n];return e.apply(t,s)}),_h||(_h=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];return new e(...i)});const ph=Oh([].forEach),gh=Oh([].lastIndexOf),fh=Oh([].pop),vh=Oh([].push),mh=Oh([].splice),yh=Array.isArray,bh=Oh("".toLowerCase),Sh=Oh("".toString),wh=Oh("".match),Ch=Oh("".replace),Eh=Oh("".indexOf),kh=Oh("".trim),xh=Oh((0).toString),Ph=Oh(Boolean.prototype.toString),Th="undefined"==typeof BigInt?null:Oh(BigInt.prototype.toString),Ih="undefined"==typeof Symbol?null:Oh(Symbol.prototype.toString),Fh=Oh({}.hasOwnProperty),Rh=Oh({}.toString),Ah=Oh(/t/.test),$h=(Mh=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];return _h(Mh,t)});var Mh;function Oh(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var i=arguments.length,s=new Array(i>1?i-1:0),n=1;i>n;n++)s[n-1]=arguments[n];return hh(e,t,s)}}function Lh(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:bh;if(nh&&nh(e,null),!yh(t))return e;let s=t.length;for(;s--;){let n=t[s];if("string"==typeof n){const e=i(n);e!==n&&(rh(t)||(t[s]=e),n=e)}e[n]=!0}return e}function Dh(e){for(let t=0;e.length>t;t++)Fh(e,t)||(e[t]=null);return e}function Nh(e){const t=uh(null);for(const s of sh(e)){var i=ih(s,2);const n=i[0],r=i[1];Fh(e,n)&&(t[n]=yh(r)?Dh(r):r&&"object"==typeof r&&r.constructor===Object?Nh(r):r)}return t}function Bh(e,t){for(;null!==e;){const i=ah(e,t);if(i){if(i.get)return Oh(i.get);if("function"==typeof i.value)return Oh(i.value)}e=oh(e)}return function(){return null}}const Uh=lh(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),zh=lh(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Hh=lh(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),qh=lh(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),jh=lh(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Wh=lh(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Vh=lh(["#text"]),Gh=lh(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Kh=lh(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-orientation","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Yh=lh(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Qh=lh(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Jh=ch(/{{[\w\W]*|^[\w\W]*}}/g),Zh=ch(/<%[\w\W]*|^[\w\W]*%>/g),Xh=ch(/\${[\w\W]*/g),e_=ch(/^data-[\-\w.\u00B7-\uFFFF]+$/),t_=ch(/^aria-[\-\w]+$/),i_=ch(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),s_=ch(/^(?:\w+script|data):/i),n_=ch(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),r_=ch(/^html$/i),o_=ch(/^[a-z][.\w]*(-[.\w]+)+$/i),a_=ch(/<[/\w!]/g),l_=ch(/<[/\w]/g),c_=ch(/<\/no(script|embed|frames)/i),u_=ch(/\/>/i),d_=function(){return"undefined"==typeof window?null:window},h_=function(e,t,i,s){return Fh(e,t)&&yh(e[t])?Lh(s.base?Nh(s.base):{},e[t],s.transform):i};var __=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d_();const i=t=>e(t);if(i.version="3.4.13",i.removed=[],!t||!t.document||9!==t.document.nodeType||!t.Element)return i.isSupported=!1,i;let s=t.document;const n=s,r=n.currentScript,o=t.HTMLTemplateElement,a=t.Node,l=t.NodeFilter,c=t.DOMParser,u=t.trustedTypes,d=t.Element.prototype,h=Bh(d,"cloneNode"),_=Bh(d,"remove"),p=Bh(d,"nextSibling"),g=Bh(d,"childNodes"),f=Bh(d,"parentNode"),v=Bh(d,"shadowRoot"),m=Bh(d,"attributes"),y=a&&a.prototype?Bh(a.prototype,"nodeType"):null,b=a&&a.prototype?Bh(a.prototype,"nodeName"):null,S=a&&a.prototype?Bh(a.prototype,"ownerDocument"):null;if("function"==typeof o){const e=s.createElement("template");e.content&&e.content.ownerDocument&&(s=e.content.ownerDocument)}let w,C,E="",k=!1,x=0;const P=function(){if(x>0)throw $h('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},T=function(e){P(),x++;try{return w.createHTML(e)}finally{x--}},I=s.implementation,F=s.createNodeIterator,R=s.createDocumentFragment,A=s.getElementsByTagName,M=n.importNode;let O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"==typeof sh&&"function"==typeof f&&I&&void 0!==I.createHTMLDocument;const L=Jh,D=Zh,N=Xh,B=e_,U=t_,z=s_,H=n_,q=o_;let j=i_,W=null;const V=Lh({},[...Uh,...zh,...Hh,...jh,...Vh]);let G=null;const K=Lh({},[...Gh,...Kh,...Yh,...Qh]);let Y=Object.seal(uh(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Q=null,J=null;const Z=Object.seal(uh(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let X=!0,ee=!0,te=!1,ie=!0,se=!1,ne=!0,re=!1,oe=!1,ae=null,le=null,ce=!1,ue=!1,de=!1,he=!1,_e=!0,pe=!1;const ge="user-content-";let fe=!0,ve=!1,me={},ye=null;const be=Lh({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Se=null;const we=Lh({},["audio","video","img","source","image","track"]);let Ce=null;const Ee=Lh({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ke="http://www.w3.org/1998/Math/MathML",xe="http://www.w3.org/2000/svg",Pe="http://www.w3.org/1999/xhtml";let Te=Pe,Ie=!1,Fe=null;const Re=Lh({},[ke,xe,Pe],Sh),Ae=lh(["mi","mo","mn","ms","mtext"]);let $e=Lh({},Ae);const Me=lh(["annotation-xml"]);let Oe=Lh({},Me);const Le=Lh({},["title","style","font","a","script"]);let De=null;const Ne=["application/xhtml+xml","text/html"];let Be=null,Ue=null;const ze=s.createElement("form"),He=function(e){return e instanceof RegExp||e instanceof Function},qe=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Ue&&Ue===e)return;e&&"object"==typeof e||(e={}),e=Nh(e),De=-1===Ne.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,Be="application/xhtml+xml"===De?Sh:bh,W=h_(e,"ALLOWED_TAGS",V,{transform:Be}),G=h_(e,"ALLOWED_ATTR",K,{transform:Be}),Fe=h_(e,"ALLOWED_NAMESPACES",Re,{transform:Sh}),Ce=h_(e,"ADD_URI_SAFE_ATTR",Ee,{transform:Be,base:Ee}),Se=h_(e,"ADD_DATA_URI_TAGS",we,{transform:Be,base:we}),ye=h_(e,"FORBID_CONTENTS",be,{transform:Be}),Q=h_(e,"FORBID_TAGS",Nh({}),{transform:Be}),J=h_(e,"FORBID_ATTR",Nh({}),{transform:Be}),me=!!Fh(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?Nh(e.USE_PROFILES):e.USE_PROFILES),X=!1!==e.ALLOW_ARIA_ATTR,ee=!1!==e.ALLOW_DATA_ATTR,te=e.ALLOW_UNKNOWN_PROTOCOLS||!1,ie=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,se=e.SAFE_FOR_TEMPLATES||!1,ne=!1!==e.SAFE_FOR_XML,re=e.WHOLE_DOCUMENT||!1,ue=e.RETURN_DOM||!1,de=e.RETURN_DOM_FRAGMENT||!1,he=e.RETURN_TRUSTED_TYPE||!1,ce=e.FORCE_BODY||!1,_e=!1!==e.SANITIZE_DOM,pe=e.SANITIZE_NAMED_PROPS||!1,fe=!1!==e.KEEP_CONTENT,ve=e.IN_PLACE||!1,j=function(e){try{return Ah(e,""),!0}catch(e){return!1}}(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:i_,Te="string"==typeof e.NAMESPACE?e.NAMESPACE:Pe,$e=Fh(e,"MATHML_TEXT_INTEGRATION_POINTS")&&e.MATHML_TEXT_INTEGRATION_POINTS&&"object"==typeof e.MATHML_TEXT_INTEGRATION_POINTS?Nh(e.MATHML_TEXT_INTEGRATION_POINTS):Lh({},Ae),Oe=Fh(e,"HTML_INTEGRATION_POINTS")&&e.HTML_INTEGRATION_POINTS&&"object"==typeof e.HTML_INTEGRATION_POINTS?Nh(e.HTML_INTEGRATION_POINTS):Lh({},Me);const t=Fh(e,"CUSTOM_ELEMENT_HANDLING")&&e.CUSTOM_ELEMENT_HANDLING&&"object"==typeof e.CUSTOM_ELEMENT_HANDLING?Nh(e.CUSTOM_ELEMENT_HANDLING):uh(null);if(Y=uh(null),Fh(t,"tagNameCheck")&&He(t.tagNameCheck)&&(Y.tagNameCheck=t.tagNameCheck),Fh(t,"attributeNameCheck")&&He(t.attributeNameCheck)&&(Y.attributeNameCheck=t.attributeNameCheck),Fh(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(Y.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),ch(Y),se&&(ee=!1),de&&(ue=!0),me&&(W=Lh({},Vh),G=uh(null),!0===me.html&&(Lh(W,Uh),Lh(G,Gh)),!0===me.svg&&(Lh(W,zh),Lh(G,Kh),Lh(G,Qh)),!0===me.svgFilters&&(Lh(W,Hh),Lh(G,Kh),Lh(G,Qh)),!0===me.mathMl&&(Lh(W,jh),Lh(G,Yh),Lh(G,Qh))),Z.tagCheck=null,Z.attributeCheck=null,Fh(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?Z.tagCheck=e.ADD_TAGS:yh(e.ADD_TAGS)&&(W===V&&(W=Nh(W)),Lh(W,e.ADD_TAGS,Be))),Fh(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?Z.attributeCheck=e.ADD_ATTR:yh(e.ADD_ATTR)&&(G===K&&(G=Nh(G)),Lh(G,e.ADD_ATTR,Be))),Fh(e,"ADD_URI_SAFE_ATTR")&&yh(e.ADD_URI_SAFE_ATTR)&&Lh(Ce,e.ADD_URI_SAFE_ATTR,Be),Fh(e,"FORBID_CONTENTS")&&yh(e.FORBID_CONTENTS)&&(ye===be&&(ye=Nh(ye)),Lh(ye,e.FORBID_CONTENTS,Be)),Fh(e,"ADD_FORBID_CONTENTS")&&yh(e.ADD_FORBID_CONTENTS)&&(ye===be&&(ye=Nh(ye)),Lh(ye,e.ADD_FORBID_CONTENTS,Be)),fe&&(W["#text"]=!0),re&&Lh(W,["html","head","body"]),W.table&&(Lh(W,["tbody"]),delete Q.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw $h('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw $h('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=w;w=e.TRUSTED_TYPES_POLICY;try{E=T("")}catch(e){throw w=t,e}}else null===e.TRUSTED_TYPES_POLICY?(w=void 0,E=""):(void 0===w&&(k||(C=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let i=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(i=t.getAttribute(s));const n="dompurify"+(i?"#"+i:"");try{return e.createPolicy(n,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+n+" could not be created."),null}}(u,r),k=!0),w=C),w&&"string"==typeof E&&(E=T("")));lh&&lh(e),Ue=e},je=Lh({},[...zh,...Hh,...qh]),We=Lh({},[...jh,...Wh]),Ve=function(e){vh(i.removed,{element:e});try{f(e).removeChild(e)}catch(t){if(_(e),!f(e))throw $h("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ge=function(e){Qe(e);const t=g(e);if(t){const e=[];ph(t,t=>{vh(e,t)}),ph(e,e=>{try{_(e)}catch(e){}})}const i=m(e);if(i)for(let t=i.length-1;t>=0;--t){const s=i[t],n=s&&s.name;if("string"==typeof n)try{e.removeAttribute(n)}catch(e){}}},Ke=function(e,t){try{vh(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){vh(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ue||de)try{Ve(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Ye=function(e){const t=m(e);if(t)for(let i=t.length-1;i>=0;--i){const s=t[i],n=s&&s.name;if("string"==typeof n&&!G[Be(n)])try{e.removeAttribute(n)}catch(e){}}},Qe=function(e){const t=[e];for(;t.length>0;){const e=t.pop();1===(y?y(e):e.nodeType)&&Ye(e);const i=g(e);if(i)for(let e=i.length-1;e>=0;--e)t.push(i[e])}},Je=function(e){let t=null,i=null;if(ce)e="<remove></remove>"+e;else{const t=wh(e,/^[\r\n\t ]+/);i=t&&t[0]}"application/xhtml+xml"===De&&Te===Pe&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const n=w?T(e):e;if(Te===Pe)try{t=(new c).parseFromString(n,De)}catch(e){}if(!t||!t.documentElement){t=I.createDocument(Te,"template",null);try{t.documentElement.innerHTML=Ie?E:n}catch(e){}}const r=t.body||t.documentElement;return e&&i&&r.insertBefore(s.createTextNode(i),r.childNodes[0]||null),Te===Pe?A.call(t,re?"html":"body")[0]:re?t.documentElement:r},Ze=function(e){const t=S?S(e):e.ownerDocument;return F.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Xe=function(e){return e=Ch(e,L," "),e=Ch(e,D," "),Ch(e,N," ")},et=function(e){var t;e.normalize();const i=S?S(e):e.ownerDocument,s=F.call(i||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null);let n=s.nextNode();for(;n;)n.data=Xe(n.data),n=s.nextNode();const r=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");r&&ph(r,e=>{it(e.content)&&et(e.content)})},tt=function(e){const t=b?b(e):null;return"string"==typeof t&&"form"===Be(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==m(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==y(e)||e.childNodes!==g(e))},it=function(e){if(!y||"object"!=typeof e||null===e)return!1;try{return 11===y(e)}catch(e){return!1}},st=function(e){if(!y||"object"!=typeof e||null===e)return!1;try{return"number"==typeof y(e)}catch(e){return!1}};function nt(e,t,s){0!==e.length&&ph(e,e=>{e.call(i,t,s,Ue)})}const rt=function(e,t,i,s){return 0===e.length?t:t===i||t===s?Nh(t):t},ot=function(e,t){if(nt(O.beforeSanitizeElements,e,null),e!==t&&null===f(e))return ve&&Qe(e),!0;if(tt(e))return Ve(e),!0;const s=Be(b?b(e):e.nodeName);if(W=rt(O.uponSanitizeElement,W,V,ae),nt(O.uponSanitizeElement,e,{tagName:s,allowedTags:W}),e!==t&&null===f(e))return ve&&Qe(e),!0;if(function(e,t){return!!(ne&&e.hasChildNodes()&&!st(e.firstElementChild)&&Ah(a_,e.textContent)&&Ah(a_,e.innerHTML))||!(!ne||e.namespaceURI!==Pe||"style"!==t||!st(e.firstElementChild))||7===e.nodeType||!(!ne||8!==e.nodeType||!Ah(l_,e.data))}(e,s))return Ve(e),!0;if(Q[s]||!(Z.tagCheck instanceof Function&&Z.tagCheck(s))&&!W[s]){const i=function(e,t,i){if(!Q[t]&&ct(t)){if(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,t))return!1;if(Y.tagNameCheck instanceof Function&&Y.tagNameCheck(t))return!1}if(fe&&!ye[t]){const t=f(e),s=g(e);if(s&&t)for(let n=s.length-1;n>=0;--n){const r=e===i?h(s[n],!0):s[n];t.insertBefore(r,p(e))}}return Ve(e),!0}(e,s,t);return!1===i&&nt(O.afterSanitizeElements,e,null),i}if(1===(y?y(e):e.nodeType)&&!function(e){let t=f(e);t&&t.tagName||(t={namespaceURI:Te,tagName:"template"});const i=bh(e.tagName),s=bh(t.tagName);return!!Fe[e.namespaceURI]&&(e.namespaceURI===xe?function(e,t,i){return t.namespaceURI===Pe?"svg"===e:t.namespaceURI===ke?"svg"===e&&("annotation-xml"===i||$e[i]):Boolean(je[e])}(i,t,s):e.namespaceURI===ke?function(e,t,i){return t.namespaceURI===Pe?"math"===e:t.namespaceURI===xe?"math"===e&&Oe[i]:Boolean(We[e])}(i,t,s):e.namespaceURI===Pe?function(e,t,i){return!(t.namespaceURI===xe&&!Oe[i])&&!(t.namespaceURI===ke&&!$e[i])&&!We[e]&&(Le[e]||!je[e])}(i,t,s):!("application/xhtml+xml"!==De||!Fe[e.namespaceURI]))}(e))return Ve(e),!0;if(("noscript"===s||"noembed"===s||"noframes"===s)&&Ah(c_,e.innerHTML))return Ve(e),!0;if(se&&3===e.nodeType){const t=Xe(e.textContent);e.textContent!==t&&(vh(i.removed,{element:e.cloneNode()}),e.textContent=t)}return nt(O.afterSanitizeElements,e,null),!1},at=function(e,t,i){if(J[t])return!1;if(ne&&"patchsrc"===t)return!1;if(ne&&"for"===t&&"label"!==e&&"output"!==e)return!1;if(_e&&("id"===t||"name"===t)&&(i in s||i in ze))return!1;const n=G[t]||Z.attributeCheck instanceof Function&&Z.attributeCheck(t,e);if(ee&&Ah(B,t));else if(X&&Ah(U,t));else if(n){if(Ce[t]);else if(Ah(j,Ch(i,H,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Eh(i,"data:")||!Se[e])if(te&&!Ah(z,Ch(i,H,"")));else if(i)return!1}else if(!(ct(e)&&(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,e)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(e))&&(Y.attributeNameCheck instanceof RegExp&&Ah(Y.attributeNameCheck,t)||Y.attributeNameCheck instanceof Function&&Y.attributeNameCheck(t,e))||"is"===t&&Y.allowCustomizedBuiltInElements&&(Y.tagNameCheck instanceof RegExp&&Ah(Y.tagNameCheck,i)||Y.tagNameCheck instanceof Function&&Y.tagNameCheck(i))))return!1;return!0},lt=Lh({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),ct=function(e){return!lt[bh(e)]&&Ah(q,e)},ut=function(e,t,i,s){if(w&&"object"==typeof u&&"function"==typeof u.getAttributeType&&!i)switch(u.getAttributeType(e,t)){case"TrustedHTML":return T(s);case"TrustedScriptURL":return function(e){P(),x++;try{return w.createScriptURL(e)}finally{x--}}(s)}return s},dt=function(e,t,s,n){try{s?e.setAttributeNS(s,t,n):e.setAttribute(t,n),tt(e)?Ve(e):fh(i.removed)}catch(i){Ke(t,e)}},ht=function(e){nt(O.beforeSanitizeAttributes,e,null);const t=e.attributes;if(!t||tt(e))return;G=rt(O.uponSanitizeAttribute,G,K,le);const i={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:G,forceKeepAttr:void 0};let s=t.length;const n=Be(e.nodeName);for(;s--;){const r=t[s],o=r.name,a=r.namespaceURI,l=r.value,c=Be(o),u=l;let d="value"===o?u:kh(u);i.attrName=c,i.attrValue=d,i.keepAttr=!0,i.forceKeepAttr=void 0,nt(O.uponSanitizeAttribute,e,i),d=i.attrValue,!pe||"id"!==c&&"name"!==c||0===Eh(d,ge)||(Ke(o,e),d=ge+d),ne&&Ah(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,d)||"attributename"===c&&wh(d,"href")?Ke(o,e):i.forceKeepAttr||(!i.keepAttr||!ie&&Ah(u_,d)?Ke(o,e):(se&&(d=Xe(d)),at(n,c,d)?(d=ut(n,c,a,d),d!==u&&dt(e,o,a,d)):Ke(o,e)))}nt(O.afterSanitizeAttributes,e,null)},_t=function(e){let t=null;const i=Ze(e);for(nt(O.beforeSanitizeShadowDOM,e,null);t=i.nextNode();)if(nt(O.uponSanitizeShadowNode,t,null),ot(t,e),ht(t),it(t.content)&&_t(t.content),1===(y?y(t):t.nodeType)){const e=v(t);it(e)&&(pt(e),_t(e))}nt(O.afterSanitizeShadowDOM,e,null)},pt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){_t(e.shadow);continue}const i=e.node,s=1===(y?y(i):i.nodeType),n=g(i);if(n)for(let e=n.length-1;e>=0;--e)t.push({node:n[e],shadow:null});if(s){const e=b?b(i):null;if("string"==typeof e&&"template"===Be(e)){const e=i.content;it(e)&&t.push({node:e,shadow:null})}}if(s){const e=v(i);it(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=null,r=null,o=null,a=null;if(Ie=!e,Ie&&(e="\x3c!--\x3e"),"string"!=typeof e&&!st(e)&&"string"!=typeof(e=function(e){switch(typeof e){case"string":return e;case"number":return xh(e);case"boolean":return Ph(e);case"bigint":return Th?Th(e):"0";case"symbol":return Ih?Ih(e):"Symbol()";case"undefined":default:return Rh(e);case"function":case"object":{if(null===e)return Rh(e);const t=e,i=Bh(t,"toString");if("function"==typeof i){const e=i(t);return"string"==typeof e?e:Rh(e)}return Rh(e)}}}(e)))throw $h("dirty is not a string, aborting");if(!i.isSupported)return e;oe?(W=ae,G=le):qe(t),(O.uponSanitizeElement.length>0||O.uponSanitizeAttribute.length>0)&&(W=Nh(W)),O.uponSanitizeAttribute.length>0&&(G=Nh(G)),i.removed=[];const l=ve&&"string"!=typeof e&&st(e);if(l){!function(e){if(!ne)return;const t=[e];for(;t.length>0;){const e=t.pop(),i=y?y(e):e.nodeType;if(7===i||8===i&&Ah(l_,e.data)){try{_(e)}catch(e){}continue}if(1===i){const t=e,i=Be(b?b(e):e.nodeName);try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&"label"!==i&&"output"!==i&&t.removeAttribute("for")}catch(e){}}const s=g(e);if(s)for(let e=s.length-1;e>=0;--e)t.push(s[e])}}(e);const t=b?b(e):e.nodeName;if("string"==typeof t){const i=Be(t);if(!W[i]||Q[i])throw Ge(e),$h("root node is forbidden and cannot be sanitized in-place")}if(tt(e))throw Ge(e),$h("root node is clobbered and cannot be sanitized in-place");try{pt(e)}catch(t){throw Ge(e),t}}else if(st(e))s=Je("\x3c!----\x3e"),r=s.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?s=r:s.appendChild(r),pt(r);else{if(!ue&&!se&&!re&&-1===e.indexOf("<"))return w&&he?T(e):e;if(s=Je(e),!s)return ue?null:he?E:""}s&&ce&&Ve(s.firstChild);const c=l?e:s;try{const e=Ze(c);for(;o=e.nextNode();)ot(o,c),ht(o),it(o.content)&&_t(o.content)}catch(t){throw l&&(Ge(e),ph(i.removed,e=>{e.element&&Qe(e.element)})),t}if(l)return ph(i.removed,e=>{e.element&&Qe(e.element)}),se&&et(e),e;if(ue){if(se&&et(s),de)for(a=R.call(s.ownerDocument);s.firstChild;)a.appendChild(s.firstChild);else a=s;return(G.shadowroot||G.shadowrootmode)&&(a=M.call(n,a,!0)),a}let u=re?s.outerHTML:s.innerHTML;return re&&W["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&Ah(r_,s.ownerDocument.doctype.name)&&(u="<!DOCTYPE "+s.ownerDocument.doctype.name+">\n"+u),se&&(u=Xe(u)),w&&he?T(u):u},i.setConfig=function(){qe(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),oe=!0,ae=W,le=G},i.clearConfig=function(){Ue=null,oe=!1,ae=null,le=null,w=C,E=""},i.isValidAttribute=function(e,t,i){Ue||qe({});const s=Be(e),n=Be(t);return at(s,n,i)},i.addHook=function(e,t){"function"==typeof t&&Fh(O,e)&&vh(O[e],t)},i.removeHook=function(e,t){if(Fh(O,e)){if(void 0!==t){const i=gh(O[e],t);return-1===i?void 0:mh(O[e],i,1)[0]}return fh(O[e])}},i.removeHooks=function(e){Fh(O,e)&&(O[e]=[])},i.removeAllHooks=function(){O={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}();const p_="Refusing to render web experiment since the viewer is a likely bot",g_={ADD_ATTR:(e,t)=>"target"===e&&"a"===t||"form"===e&&/^(button|fieldset|input|output|select|textarea)$/.test(t),ADD_URI_SAFE_ATTR:["form"]};let f_;const v_={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Kc(t,e),not_regex:(e,t)=>!Kc(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},m_=Or("[Conversations]"),y_="Conversations not available yet.";function b_(e,t){var i,s,n,r,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!==(n=null==e?void 0:e.maxLogsPerInterval)&&void 0!==n?n:1e3,h=mt(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,n=null==s||null===(i=s.navigator)||void 0===i?void 0:i.userAgent;n&&([e,t]=Ui(n))}catch(e){}return function(e,t){const i=function(e){if(e)return{}.hasOwnProperty.call(dr,e)?dr[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!==(r=null!==(o=null==_?void 0:_["service.name"])&&void 0!==o?o:null==e?void 0:e.serviceName)&&void 0!==r?r: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 S_=["debug","log","warn","error","info"],w_=e=>{for(;null==e?void 0:e.__rrweb_original__;)e=e.__rrweb_original__;return e},C_="console",E_="__posthogHandledLogsRequestError",k_=(e,t)=>{const i=e instanceof Error?e:new Error(t);return i[E_]=!0,i},x_=e=>!!e&&"object"==typeof e&&!0===e[E_];var P_=class{get _coreLogger(){return ls(ls({},this._logger),{},{error:(...e)=>{e.some(x_)||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=Or("[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&&(Wr(this._window,"online",this._onReconnect),this._listeningForReconnect=!0)}}_buildCore(e,t,i,s){this._listenForReconnect();const n=b_(this._configSource.get(),i);return[new Sr(this._createHost(e,t),n,this._coreLogger,()=>this._getSdkContext(),e=>e(),void 0,s),n]}_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},C_)),this._consoleCore}setup(e){if(!this._disposed&&!this._setupStarted)return this._setupStarted=!0,this._client=e,this._logger=e.logger.createLogger("[logs]"),xd(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,n,r,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===(n=this._consoleCore)||void 0===n||n.clearQueue(),null===(r=this._core)||void 0===r||r.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;wt(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=b_(this._configSource.get()).maxBufferSize;let i=!0;this._consoleRecorderUnpatchers.push(()=>{i=!1});for(const e of S_){let s;try{s=w_(this._window.console[e])}catch(e){continue}s&&this._consoleRecorderUnpatchers.push(sd(this._window.console,e,n=>{const r=(...s)=>{try{i&&this._recordConsoleEntry(e,s,t)}catch(e){}return n.apply(this._window.console,s)};return r.__rrweb_original__=s,r}))}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 Dt(function*(){var t,i;const s=null===(t=e._core)||void 0===t?void 0:t.flush().catch(t=>e._logFlushError(t)),n=null===(i=e._consoleCore)||void 0===i?void 0:i.flush().catch(t=>e._logFlushError(t));yield s,yield n})()}_logFlushError(e){x_(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===st.LogsQueue?e():void 0,setPersistedProperty(e,i){e===st.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(Aa(this._consecutiveStatusZeroFailures,3))return void t({kind:"fatal",error:k_(void 0,"logs endpoint is unreachable, dropping batch")});let i=!1;const s=e=>{i||(i=!0,clearTimeout(n),t(e))},n=setTimeout(()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:k_(void 0,"logs request timed out")})},9e4),r=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,r),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:k_(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=$a(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,C_,e=>{this._consoleQueue=e})}_drainQueueViaTransport(e,t,i,s,n){if(0===t.length)return;const r=t.map(e=>e.record);n([]);const o=vr(r,fr(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 T_=Or("[NetworkMetrics]"),I_={"http:":80,"https:":443},F_=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),R_=e=>yt(e)&&0===e.toLowerCase().indexOf("text/event-stream"),A_=e=>{try{return e()}catch(e){return}},$_=(e,t)=>{var i;const s=String(t);return{method:String(e).toUpperCase(),url:(null===(i=Fa(s))||void 0===i?void 0:i.href)||s}},M_=(e,t,i,s,n,r,o=!1)=>{try{var a,l;const c=n();if(!c)return;const u=i||void 0,d=Eu()-s,h=Fa(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=gt(c.name)?c.name(_):yt(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,r),f=ls(ls(ls(ls(ls({},(e=>{const t=F_.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)||I_[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:f})}catch(e){T_.error("Failed to record network metric",e)}},O_=()=>{},L_=(e,t)=>gt(null==s?void 0:s.fetch)?sd(s,"fetch",i=>function(...s){const n=Eu(),r=i.apply(this,s);if(!t())return r;try{var o,a,l;const[i,c]=s,u=$_(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 r.then(i=>(R_(A_(()=>{var e;return null==i||null===(e=i.headers)||void 0===e?void 0:e.get("content-type")}))||M_(e,u,null==i?void 0:i.status,n,t,void 0,!0),i),i=>{throw M_(e,u,void 0,n,t,i),i})}catch(e){return T_.error("Failed to observe fetch",e),r}}):O_,D_=(e,t)=>{var i;const n=null==s||null===(i=s.XMLHttpRequest)||void 0===i?void 0:i.prototype;if(!n)return O_;const r=new WeakMap,o=sd(n,"open",e=>function(...t){try{(()=>hc.has(this))()||r.set(this,$_(t[0],t[1]))}catch(e){T_.error("Failed to observe XHR open",e)}return e.apply(this,t)}),a=sd(n,"send",i=>function(...s){let n,o;try{const i=r.get(this);if(i&&t()){const s=Eu(),r=()=>R_(A_(()=>this.getResponseHeader("content-type")));let a=!1;o=()=>{2===this.readyState&&(a=r())},n=()=>{this.removeEventListener("loadend",n),this.removeEventListener("readystatechange",o),a||r()||M_(e,i,this.status,s,t)},Wr(this,"readystatechange",o),Wr(this,"loadend",n)}}catch(e){T_.error("Failed to observe XHR send",e)}try{return i.apply(this,s)}catch(e){throw n&&this.removeEventListener("loadend",n),o&&this.removeEventListener("readystatechange",o),e}});return()=>{o(),a()}},N_=new WeakMap,B_=new Set(["$comment","$defs","$id","$schema","additionalProperties","default","definitions","deprecated","description","examples","minProperties","properties","readOnly","required","title","type","writeOnly"]),U_={maxStringLength:2048,truncationSuffix:"..."},z_={maxStringLength:2048,truncationSuffix:"..."};function H_(e){if(e)return!0===e?{intent:!0,model:!0}:{intent:!1!==e.intent,model:!1!==e.model}}function q_(e,t){return{}.hasOwnProperty.call(e,t)}function j_(e,t){const i=Object.create(e);return t&&Object.defineProperty(i,"inputSchema",{configurable:!0,enumerable:!0,writable:!0,value:t}),i}function W_(e,t,i=!1){if(!yt(e))return;const s=e.trim();return s?(i?Qn(s,U_):s).slice(0,t):void 0}function V_(e){try{return ft(e)&&!0===e.isError}catch(e){return!1}}function G_(e){return Qn(e||"Unknown error",z_).slice(0,2048)}function K_(e,t){try{return G_(t?function(e){try{if(!ft(e)||!pt(e.content))return;return e.content.filter(e=>ft(e)&&"text"===e.type&&yt(e.text)).map(e=>e.text).join(" ").trim()||void 0}catch(e){return}}(e):ft(e)&&yt(e.message)?e.message:yt(e)?e:String(e))}catch(e){return"Unknown error"}}function Y_(e,t,i){return t.errorResult?[{type:"Error",value:i,mechanism:{type:"generic",handled:!0,synthetic:!0,exception_id:0}}]:e.buildProperties(t.error,{handled:!0}).$exception_list.map(e=>ls(ls({},e),{},{value:G_(e.value)}))}function Q_(e,t){if(t)return"Error";try{if(!ft(e))return"Error";let t=yt(e.name)?e.name.trim():"";const i=e.constructor;return t&&"Error"!==t||!gt(i)||"Error"===i.name||(t=i.name),(t||"Error").slice(0,256)}catch(e){return"Error"}}function J_(e,t){return{message:K_(e,t),type:Q_(e,t)}}Ju.__defaultExtensionClasses=ls({},{featureFlags:class extends Vd{constructor(e){const t=new Kd(e.config,e._shouldDisableFlags());super(t),this.name=wu,this._instance=e,this._mutableConfigSource=t}get _crossTabPersistence(){return this._instance.persistence}updateConfig(e,t){this._mutableConfigSource.update(e,t),this._onConfigUpdated()}},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=ud,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._selectMaskingFn=void 0,this._documentWasEverVisible=(()=>{var e,t;if(!(null==o?void 0:o.visibilityState)||"visible"===o.visibilityState)return!0;const i=null==s||null===(e=s.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==o?void 0:o.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 _d.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"');const t=this._instance.get_property(pe);var i;yt(t)&&"!"===t[0]&&(null===(i=this._persistence)||void 0===i||i.unregister("$session_is_sampled")),(null==o?void 0:o.addEventListener)&&Wr(o,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this._sessionRecordingDisposed=!0,null==o||null===(t=o.removeEventListener)||void 0===t||t.call(o,"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,n=this._config.disable_session_recording||this._instance.consent.isOptedOut();return s&&t&&i&&!n}startIfEnabledOrStop(e){if(this._sessionRecordingDisposed)return;var t;if(this._lazyLoadedSessionRecording)if(this._selectMaskingFn!==(null===(t=this._config.session_recording)||void 0===t?void 0:t.selectMaskingFn))wo._remove(hd(this._config)),this._lazyLoadedSessionRecording.discard({discardProducerEvents:!0}),this._selectMaskingFn=void 0;else if(this._lazyLoadedSessionRecording.isStarted&&this._isRecordingEnabled)return void(this._checkSelectMaskingSupport()||this._discardRecording(!0));const i=!mt(Object.assign)&&!mt(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),_d.info("starting")):(this._recordingStatus=ud,this.stopRecording())}_lazyLoadAndStart(e){var t,i;if(this._isRecordingEnabled)if("awaiting_config"!==this._recordingStatus&&"missing_config"!==this._recordingStatus&&(this._recordingStatus=dd),(null==p||null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t?void 0:t.record)&&(null===(i=p.__PosthogExtensions__)||void 0===i?void 0:i.initSessionRecording))this._onScriptLoaded(e);else{var s;const t=this._instance.sessionManager;null===(s=g(this._instance))||void 0===s||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}),_d.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,s;e&&(this._selectMaskingFn||(null===(t=this._config.session_recording)||void 0===t?void 0:t.selectMaskingFn))&&wo._remove(hd(this._config)),null===(i=this._persistFlagsOnSessionListener)||void 0===i||i.call(this),this._persistFlagsOnSessionListener=void 0,null===(s=this._lazyLoadedSessionRecording)||void 0===s||s.discard({discardProducerEvents:e}),this._selectMaskingFn=void 0}_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(wt(e))return null;const i=Ct(e)?e:parseFloat(e);return"number"!=typeof(s=i)||!Number.isFinite(s)||0>s||s>1?(_d.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,n=()=>{var t;const i=!1===e.sessionRecording?void 0:e.sessionRecording,n=this._validateSampleRate(null===(t=this._config.session_recording)||void 0===t?void 0:t.sampleRate,"session_recording.sampleRate"),r=this._validateSampleRate(null==i?void 0:i.sampleRate,"remote config sampleRate"),o=null!=n?n:r;wt(o)&&this._resetSampling();const a=null==i?void 0:i.minimumDurationMilliseconds;s.register({[oe]: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:mt(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})})};n(),null===(t=this._persistFlagsOnSessionListener)||void 0===t||t.call(this),this._persistFlagsOnSessionListener=null===(i=this._instance.sessionManager)||void 0===i?void 0:i.onSessionId(n)}}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({[Ue]:!0}),_d.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):_d.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(oe);return(null==i||null===(t=i.scriptConfig)||void 0===t?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){const e=this._instance.get_property(oe);if(!e)return!1;let t;try{t="object"==typeof e?e:JSON.parse(e)}catch(e){return _d.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!wt(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}_checkSelectMaskingSupport(){var e,t,i;return!(null===(e=this._config.session_recording)||void 0===e?void 0:e.selectMaskingFn)||!(!0!==(null===(t=p.__PosthogExtensions__)||void 0===t||null===(t=t.rrweb)||void 0===t||null===(t=t.record)||void 0===t?void 0:t.supportsSelectMasking)||!0!==(null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.initSessionRecording)||void 0===i?void 0:i.supportsSelectMasking)||this._lazyLoadedSessionRecording&&!0!==this._lazyLoadedSessionRecording.supportsSelectMasking)||(this._recordingStatus=ud,_d.error("Session recording has not started: the recorder does not support selectMaskingFn."),!1)}_onScriptLoaded(e){var t,i,s,n,r,o;if(this._sessionRecordingDisposed||!this._isRecordingEnabled||!this._instance.sessionManager)return void(this._recordingStatus=ud);if(!(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.initSessionRecording))return _d.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Be]:!0});if(!this._checkSelectMaskingSupport())return;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null===(o=p.__PosthogExtensions__)||void 0===o?void 0:o.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._checkSelectMaskingSupport())return void this._discardRecording(!0);if(!this._isRemoteConfigFresh()){if("missing_config"===this._recordingStatus||"awaiting_config"===this._recordingStatus)return;return this._recordingStatus="awaiting_config",_d.info("persisted remote config is stale, requesting fresh config before starting"),void new Fl(this._instance).load()}this._recordingStatus=dd,null===(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||void 0===i||i.call(s,this._documentWasEverVisible);const a=null===(n=this._config.session_recording)||void 0===n?void 0:n.selectMaskingFn;this._lazyLoadedSessionRecording.start(e),this._selectMaskingFn=a,this._lazyLoadedSessionRecording.isStarted&&a!==(null===(r=this._config.session_recording)||void 0===r?void 0:r.selectMaskingFn)&&this.startIfEnabledOrStop()}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 pd){var i;const s=null===(i=this._instance.sessionPersistence)||void 0===i?void 0:i.get_property(e);mt(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)}},autocapture:class extends Su{constructor(e){super(new Xu(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&&(Mr.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,Mr.info("History API monitoring stopped")}monitorHistoryChanges(){s&&s.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(!s||(null===(t=s.history[e])||void 0===t?void 0:t.__posthog_wrapped__))return;const i=this;sd(s.history,e,t=>function(n,r,o){var a;i._isUrlChanging(o)&&i._flushPendingPageview(),t.call(this,n,r,o),i._capturePageview(e,!i._isFlushingPageview&&"popstate"!==(null==s||null===(a=s.event)||void 0===a?void 0:a.type))})}_getCurrentLocation(){const e=null==s?void 0:s.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}:ft(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(Xe,{navigation_type:e});t?(this._pendingPageview=i,Promise.resolve().then(()=>this._flushPendingPageview())):i()}this._lastLocation=i}catch(t){Mr.error(`Error capturing ${e} pageview`,t)}}_isUrlChanging(e){var t,i;return!(wt(e)||!s)&&(null===(t=Fa(String(e)))||void 0===t?void 0:t.href)!==(null===(i=s.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){Mr.error("Error capturing deferred pageview",e)}finally{this._isFlushingPageview=!1}this._lastLocation=this._getCurrentLocation()}}_setupPopstateListener(){if(this._popstateListener)return;const e=()=>{this._capturePageview("popstate")};Wr(s,"popstate",e),this._popstateListener=()=>{s&&s.removeEventListener("popstate",e)}}_setupHashchangeListener(){if(this._hashchangeListener)return;const e=()=>{this._capturePageview("hashchange")};Wr(s,"hashchange",e),this._hashchangeListener=()=>{s&&s.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[J]),this.rageclicks=new du(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return ft(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return wt(this._config.capture_heatmaps)?wt(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;gd.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({[J]:i}),this._enabledServerSide=i,this.startIfEnabled()}getAndClearBuffer(){const e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){fd(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval="visible"===(null==o?void 0:o.visibilityState)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){s&&o&&(this._flushHandler=this._flush.bind(this),Wr(s,Ze,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==s?void 0:s.event)),Wr(o,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==s?void 0:s.event)),Wr(o,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new ma(this.instance,fa,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),Wr(o,R,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;s&&o&&(this._flushHandler&&s.removeEventListener(Ze,this._flushHandler),this._onClickHandler&&o.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&o.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&o.removeEventListener(R,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(),n=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),o=function(e,t,i){let n=e;for(;n&&xo(n)&&!Po(n,"body");){if(n===i)return!1;let e;try{var r,o,a;e=null===(r=null!==(o=null===(a=n.ownerDocument)||void 0===a?void 0:a.defaultView)&&void 0!==o?o:s)||void 0===r?void 0:r.getComputedStyle(n).position}catch(e){return!1}if(at(t,e))return!0;n=Bo(n)}return!1}(Oo(e),["fixed","sticky"],r);return{x:e.clientX+(o?0:n),y:e.clientY+(o?0:i),target_fixed:o,type:t}}_onClick(e,t="click"){var i;if(ko(e.target)||!fd(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()))&&Jo(Oo(e),this.instance.config.rageclick)&&this._capture(ls(ls({},s),{},{type:"rageclick"})),this._capture(s)}_onMouseMove(e){!ko(e.target)&&fd(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout(()=>{this._capture(this._getProperties(e,"mousemove"))},500))}_capture(e){if(!s)return;const t=this._config.disable_capture_url_hashes?es(s.location.href):s.location.href,i=this._config.custom_personal_data_properties,n=this._config.mask_personal_data_properties?[...Na,...i||[]]:[],r=La(t,n,Ua);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:ma,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=(e=!1)=>{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}),{})),e?{transport:"sendBeacon",send_instantly:!0}:void 0),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},wt(null==e?void 0:e.name)||wt(null==e?void 0:e.value))return void rd.error("Invalid metric received",e);const i="string"==typeof e.navigationURL?e.navigationURL:void 0,s=this._maskedURL(i);if(mt(s))return;const n=Ct(e.navigationId)||"string"==typeof e.navigationId?`navigation:${e.navigationId}`:`url:${s}`;if(this._maxAllowedValue&&e.value>=this._maxAllowedValue)return void rd.error("Ignoring metric with value >= "+this._maxAllowedValue,e);this._buffer.navigationKey!==n&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),mt(this._buffer.navigationKey)&&(this._buffer.navigationKey=n,this._buffer.url=s),this._buffer.firstMetricTimestamp=mt(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;const r=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,ft(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){const t={};for(const i of cd){const s="url"===i&&"string"==typeof e.attribution[i]?this._maskedURL(e.attribution[i]):e.attribution[i];mt(s)||(t[i]=s)}o.attribution=t}else delete o.attribution;mt(r)||(o.$session_id=r.sessionId,o.$window_id=r.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,n,r=!1;const o=p.__PosthogExtensions__,a=null==o?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(null==a?void 0:a[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&mt(a)?null==o?void 0:o.postHogWebVitalsCallbacks:void 0);if(!mt(l)){const s=l.withoutAttribution,o=this.attributionMetrics;r=!mt(s),e=o.indexOf("LCP")>-1?l.onLCP:(null==s?void 0:s.onLCP)||l.onLCP,t=o.indexOf("CLS")>-1?l.onCLS:(null==s?void 0:s.onCLS)||l.onCLS,i=o.indexOf("FCP")>-1?l.onFCP:(null==s?void 0:s.onFCP)||l.onFCP,n=o.indexOf("INP")>-1?l.onINP:(null==s?void 0:s.onINP)||l.onINP}if(!(e&&t&&i&&n))return void rd.error("web vitals callbacks not loaded - not starting");const c={reportSoftNavs:this.useSoftNavs},u=r&&this.attributionMetrics.indexOf("INP")>-1?ls(ls({},c),{},{includeProcessedEventEntries:!1}):c;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("FCP")>-1&&i(this._addToBuffer.bind(this),c),this.allowedMetrics.indexOf("INP")>-1&&n(this._addToBuffer.bind(this),u);const d=null==s?void 0:s.document;Wr(d,R,()=>{"hidden"===(null==d?void 0:d.visibilityState)&&this._flushToCapture(!0)}),Wr(s,"pagehide",()=>this._flushToCapture(!0)),this._initialized=!0},this._enabledServerSide=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[te]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const i=ft(this._perfConfig)?null===(e=this._perfConfig)||void 0===e?void 0:e.web_vitals_allowed_metrics:void 0;return wt(i)?(null===(t=this._instance.persistence)||void 0===t?void 0:t.props.$web_vitals_allowed_metrics)||ad:i}get flushToCaptureTimeoutMs(){return(ft(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=ft(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return kt(e)?e?ad:[]:pt(e)?e:ld}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=ft(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){const e=ft(this._perfConfig)&&Ct(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:od;return e>0&&6e4>=e?od:e}get isEnabled(){const e=null==a?void 0:a.protocol;if("http:"!==e&&"https:"!==e)return rd.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=ft(this._perfConfig)?this._perfConfig.web_vitals:kt(this._perfConfig)?this._perfConfig:void 0;return kt(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(rd.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const i=ft(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=ft(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[te]:i}),this._instance.persistence.register({[re]: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=p.__PosthogExtensions__,s=this._callbackFlavor,n=null==i?void 0:i.postHogWebVitalsCallbacksByFlavor;(null==n?void 0:n[s])||"web-vitals"===s&&mt(n)&&(null==i?void 0:i.postHogWebVitalsCallbacks)?e():null===(t=g(this._instance))||void 0===t||t(this._instance,s,t=>{t?rd.error("failed to load script",t):e()})}_maskedURL(e){const t=e||(null==s?void 0:s.location.href);if(!t)return void rd.error("Could not determine current URL");const i=this._instance.config.disable_capture_url_hashes?es(t):t,n=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...Na,...n||[]]:[];return La(i,r,Ua)}},exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(!s||!this.isEnabled||!(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.errorWrappingFunctions))return;const t=p.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=p.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=p.__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=n(this.captureException.bind(this)))}catch(e){ed.error("failed to start",e),this._stopCapturing()}},this._instance=e,this._remoteEnabled=!!(null===(t=this._instance.persistence)||void 0===t?void 0:t.props[Z]),this._rateLimiter=new Ht(ls(ls({},function(e={}){var t,i,s,n;return{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(n=e.exceptionRateLimiterBucketSize)&&void 0!==n?n:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking)),{},{refillInterval:1e4,_logger:ed})),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 ft(e)?t=ls(ls({},t),e):(mt(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?(ed.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.errorWrappingFunctions)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"exception-autocapture",t=>{if(t)return ed.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({[Z]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}onConfigChange(){this._config=this._requiredConfig()}captureException(e){try{var t,i,s;const n=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(n))return void ed.info("Skipping exception capture because of client rate limiting.",{exception:n});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 qs,new Us,new Ws],function(e,...t){return(i,s=0)=>{const n=[],r=i.split("\n"),o=Math.min(r.length,s+1e3),a=[];for(let i=s;o>i;i++){const s=r[i];if(s.length>1024)continue;const o=Ts.test(s)?s.replace(Ts,"$1"):s;if(!o.match(/\S*Error: /)){for(const i of t){const t=i(o,e);if(t){n.push(t);const e=Fs(n);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(Ms(n,a)>=50)break}}const l=[...a].sort((e,t)=>t.start-e.start),c=l[l.length-1];if(c){const e=As(n,c);n.splice(c.start-e,e);for(const t of l)t.start-=e}for(const e of l)Rs(n,e);return a.some(e=>0===e.start&&n.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))}(n),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})}(n)}}("web:javascript",Es,Ps)),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=Js(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new Zs(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=Js(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(!e.ok)return;const n=e.config;if(!("errorTracking"in n))return;const r=null!==(t=null===(i=n.errorTracking)||void 0===i?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null===(s=n.errorTracking)||void 0===s?void 0:s.captureExtensionExceptions;this._suppressionRules=r,this._instance.persistence&&this._instance.persistence.register({[X]:this._suppressionRules,[ee]:o})}get _captureExtensionExceptions(){var e;const t=!!this._instance.get_property(ee),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(!yt(e)||0===e.trim().length)return void Qd.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)=>Ys.has(s)?(t.push(s),i):(i[s]=e[s],i),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t));s.length>0&&Qd.warn("Ignoring reserved exception step fields",{droppedKeys:s}),this._exceptionStepsBuffer.add(ls({[Gs]:e,[Ks]:(new Date).toISOString()},i))}catch(e){Qd.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 Qd.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 Qd.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 Qd.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 Qd.info("Skipping exception capture because it was thrown by the PostHog SDK")}const i=this._exceptionStepsConfig.enabled&&wt(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 Yd(e)||Qd.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void(Yd(e)||Qd.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 Qd.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 ft(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})=>(yt(t)&&t.length>0&&e.$exception_types.push(t),yt(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=Qc[e.operator],s=t[e.key];if(!i||!s)return!1;const n=pt(e.value)?e.value:[e.value];return n.length>0&&i(n,s)});return"OR"===e.type?i.some(Boolean):i.every(Boolean)})}catch(e){return Qd.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&&Xd.some(t=>e.startsWith(t)));return 0!==i.length&&(!i.every(({filename:e})=>!!e&&e.startsWith(Jd))||e.some(({type:e,value:t})=>"NoResponse"===e||yt(t)&&Zd.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(Jd))))}_isInjectedBrowserScriptException(e){return e.some(({value:e})=>yt(e)&&eh.some(t=>e.includes(t)))}_isPostHogException(e){if(e.length>0){var t,i,s,n;const r=null!==(t=null===(i=e[0].stacktrace)||void 0===i?void 0:i.frames)&&void 0!==t?t:[],o=r[r.length-1];return null!==(s=null==o||null===(n=o.filename)||void 0===n?void 0:n.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!wt(e)&&pt(e)}},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({[se]:!!t.productTours}),!md(this._instance))return!this._productTourManager&&wt(null===(i=this._persistence)||void 0===i?void 0:i.props.ph_product_tours)||vd.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&&md(this._instance)&&this._loadScript(()=>this._startProductTours())}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.generateProductTours)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"product-tours",t=>{t?vd.error("Could not load product tours script",t):e()})}_startProductTours(){var e;!this._productTourManager&&(null===(e=p.__PosthogExtensions__)||void 0===e?void 0:e.generateProductTours)&&(this._productTourManager=p.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(pt(this._cachedTours)&&!t)return void e(this._cachedTours,{isLoaded:!0});const i=this._persistence;if(i){const s=i.props[Se];if(pt(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(!md(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||vd.warn(i):vd.error(i),void e([],{isLoaded:!1,error:i})}const n=pt(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=n,i&&i.register({[Se]:n}),e(n,{isLoaded:!0})}})}getActiveProductTours(e){wt(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)}},siteApps:class{constructor(e){this._instance=e,this._siteAppElementPatchCount=0,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps&&!this._instance.config.require_subresource_integrity}_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=p._POSTHOG_REMOTE_CONFIG)||void 0===e||null===(e=e[this._instance.config.token])||void 0===e?void 0:e.siteApps}initialize(){if(this._instance.config.opt_in_site_apps&&!this.isEnabled&&bd.critical("opt_in_site_apps is ignored: require_subresource_integrity disables site apps"),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,n,r,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({},gn(e,yd)),{},{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===(n=e.properties)||void 0===n?void 0:n.$set_once)&&void 0!==s?s:{}),d)}:{}),elements_chain:null!==(r=null===(o=e.properties)||void 0===o?void 0:o.$elements_chain)&&void 0!==r?r:"",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)||(bd.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)||(bd.error("prepare_external_dependency_script returned null"),null)}return e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,n,r,a,l;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=null==o?void 0:o.defaultView,u=null==c||null===(e=c.Node)||void 0===e?void 0:e.prototype;if(!c||!u)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();const d=[],h=this,_=new WeakSet,p=(e,t,i)=>{if(!(null==e?void 0:e[t]))return;const s=e[t];e[t]=i(s),d.push(()=>{e[t]=s})},g=e=>{if(_.has(e))return e;const t=h._prepareElementForSiteApp(e);return t&&_.add(t),t},f=e=>e.map(e=>"string"==typeof e?e:g(e)).filter(e=>!St(e));return p(u,"appendChild",e=>function(t){const i=g(t);return i?e.call(this,i):t}),p(u,"insertBefore",e=>function(t,i){const s=g(t);return s?e.call(this,s,i):t}),p(u,"replaceChild",e=>function(t,i){const s=g(t);return s?e.call(this,s,i):i}),[null===(t=c.Element)||void 0===t?void 0:t.prototype,null===(i=c.Document)||void 0===i?void 0:i.prototype,null===(s=c.DocumentFragment)||void 0===s?void 0:s.prototype].forEach(e=>{p(e,"append",e=>function(...t){return e.apply(this,f(t))}),p(e,"prepend",e=>function(...t){return e.apply(this,f(t))})}),[null===(n=c.Element)||void 0===n?void 0:n.prototype,null===(r=c.CharacterData)||void 0===r?void 0:r.prototype,null===(a=c.DocumentType)||void 0===a?void 0:a.prototype].forEach(e=>{p(e,"before",e=>function(...t){return e.apply(this,f(t))}),p(e,"after",e=>function(...t){return e.apply(this,f(t))}),p(e,"replaceWith",e=>function(...t){const i=f(t);return t.length&&!i.length?void 0:e.apply(this,i)})}),p(null===(l=c.Element)||void 0===l?void 0:l.prototype,"insertAdjacentElement",e=>function(t,i){const s=g(i);return s?e.call(this,t,s):null}),this._restoreSiteAppElementPatches=()=>{d.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&&(bd.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 n=n=>{t.errored=!n,t.loaded=!0,bd.info(`Site app with id ${e.id} ${n?"loaded":"errored"}`),s&&i()};try{const{processEvent:i}=this._runWithPreparedSiteAppElements(t=>e.init({posthog:this._instance,callback(e){t(),n(e)}}),!1);i&&(t.processEvent=i),s=!0}catch(t){bd.error(Sd+e.id,t),n(!1)}if(s&&t.loaded)try{i()}catch(i){bd.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){bd.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 bd.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 n=e.config;if(null===(s=n.siteApps)||void 0===s?void 0:s.length)if(this.isEnabled)for(const{id:e,url:t}of n.siteApps){var r,o;p[`__$$ph_site_app_${e}`]=this._instance,null===(r=p.__PosthogExtensions__)||void 0===r||null===(o=r.loadSiteApp)||void 0===o||o.call(r,this._instance,t,t=>{if(t)return bd.error(Sd+e,t)})}else bd.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},surveys:class extends Id{constructor(e){super(new Fd(e))}},tracingHeaders:class{constructor(e){this._instance=e,this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._patchedHostnames=void 0,this._traceparentTargetsForPatch=[],this._startCapturing=()=>{const{hostnames:e,traceparentTargets:t}=this._syncForPatch();var i,s;e||t?(e||pt(this._hostnamesForPatch)||(this._hostnamesForPatch=[]),this._patchedHostnames!==this._hostnamesForPatch&&(this._stopCapturing(),this._patchedHostnames=this._hostnamesForPatch),mt(this._restoreXHRPatch)&&(this._restoreXHRPatch=null===(i=p.__PosthogExtensions__)||void 0===i||null===(i=i.tracingHeadersPatchFns)||void 0===i?void 0:i._patchXHR(this._hostnamesForPatch,()=>this._instance.get_distinct_id(),this._instance.sessionManager,this._traceparentTargetsForPatch)),mt(this._restoreFetchPatch)&&(this._restoreFetchPatch=null===(s=p.__PosthogExtensions__)||void 0===s||null===(s=s.tracingHeadersPatchFns)||void 0===s?void 0:s._patchFetch(this._hostnamesForPatch,()=>this._instance.get_distinct_id(),this._instance.sessionManager,this._traceparentTargetsForPatch))):this._stopCapturing()}}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i;(null===(t=p.__PosthogExtensions__)||void 0===t?void 0:t.tracingHeadersPatchFns)?e():null===(i=g(this._instance))||void 0===i||i(this._instance,"tracing-headers",t=>{if(t)return nd.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 pt(e)?(pt(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):!pt(this._hostnamesForPatch)||(this._hostnamesForPatch.splice(0),e)?(this._hostnamesForPatch=e||void 0,this._hostnamesForPatch):void 0}_syncTraceparentTargetsForPatch(){const e=this._instance.config.trace_propagation_targets,t=pt(e)?e.filter(e=>yt(e)&&!!e):[];return this._traceparentTargetsForPatch.splice(0,this._traceparentTargetsForPatch.length,...t),t.length>0?this._traceparentTargetsForPatch:void 0}_syncForPatch(){return{hostnames:this._syncHostnamesForPatch(),traceparentTargets:this._syncTraceparentTargetsForPatch()}}_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(){const{hostnames:e,traceparentTargets:t}=this._syncForPatch();e||t?this._loadScript(this._startCapturing):this._stopCapturing()}},toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){p.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=p.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,i=void 0){var n,r;if(Vr(this.instance.config))return!1;if(!s||!o)return!1;e=null!==(n=e)&&void 0!==n?n:s.location,i=null!==(r=i)&&void 0!==r?r:s.history;try{if(!t){try{s.localStorage.setItem("test","test"),s.localStorage.removeItem("test")}catch(e){return!1}t=null==s?void 0:s.localStorage}const n=Rd||Da(e.hash,"__posthog")||Da(e.hash,"state");let r;const o=n?ts(()=>JSON.parse(atob(decodeURIComponent(n))))||ts(()=>JSON.parse(decodeURIComponent(n))):null;return o&&"ph_authorize"===o.action?(r=o,r.source="url",r&&Object.keys(r).length>0&&(o.desiredHash?e.hash=o.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):(r=JSON.parse(t.getItem(Ad)||"{}"),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=p.ph_load_toolbar||p.ph_load_editor;!wt(t)&&gt(t)?t(e,this.instance):$d.warn("No toolbar load function found")}loadToolbar(e){const t=!!(null==o?void 0:o.getElementById("__POSTHOG_TOOLBAR__"));if(!s||t)return!1;const i="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,n=ls(ls({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},i?{instrument:!1}:{});if(s.localStorage.setItem(Ad,JSON.stringify(ls(ls({},n),{},{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(n);else if(0===this._getToolbarState()){var r;this._setToolbarState(1),null===(r=g(this.instance))||void 0===r||r(this.instance,"toolbar",e=>{if(e)return $d.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(n)}),Wr(s,"turbolinks:load",()=>{this._setToolbarState(0),this.loadToolbar(n)})}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,i=void 0){return this.maybeLoadToolbar(e,t,i)}},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);yt(s)&&t.variants[s]&&this._applyVariantForFlag(t,s)}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(p_);else if(!this._config.disable_web_experiments){if(wt(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._applyVariantForFlag(s,t)}})}}previewWebExperiment(){const t=e.getWindowLocation();if(null==t?void 0:t.search){const i=Oa(null==t?void 0:t.search,"__experiment_id"),s=Oa(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 n=s.filter(e=>e.id===t);n&&n.length>0&&(e._logInfo(`Previewing web experiment [${n[0].name}] with variant [${i}]`),this._applyTransforms(n[0].name,i,n[0].variants[i].transforms))}_applyVariantForFlag(t,i){const s=t.variants[i];e._matchUrlConditions(s,this._instance)?this._applyTransforms(t.name,i,s.transforms):e._logInfo(`skipping variant ${i} of experiment ${t.name} because this page does not match its url conditions`)}static _matchesTestVariant(t,i){return!wt(t.conditions)&&e._matchUrlConditions(t,i)&&e._matchUTMConditions(t)}static _matchUrlConditions(t,i){var s;if(wt(t.conditions)||wt(null===(s=t.conditions)||void 0===s?void 0:s.url))return!0;const n=e.getWindowLocation();if(n){var r,o,a;const e=Eo(i,n.href);return!(null===(r=t.conditions)||void 0===r?void 0:r.url)||v_[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==s?void 0:s.location}static _matchUTMConditions(e){var t;if(wt(e.conditions)||wt(null===(t=e.conditions)||void 0===t?void 0:t.utm))return!0;const i=Ha();if(i.utm_source){var s,n,r,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===(n=e.conditions)||void 0===n||null===(n=n.utm)||void 0===n?void 0:n.utm_campaign)==i.utm_campaign,d=!(null===(r=e.conditions)||void 0===r||null===(r=r.utm)||void 0===r?void 0:r.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){Mr.info(`[WebExperiments] ${e}`,t)}static _logWarn(e,...t){Mr.warn(`[WebExperiments] ${e}`,t)}static _sanitizeLinkTargets(t){("http://www.w3.org/1999/xhtml"===t.namespaceURI&&"template"===t.localName?t.content:t).querySelectorAll("a[target], template").forEach(t=>{var i;if("template"===t.localName)return void("http://www.w3.org/1999/xhtml"===t.namespaceURI&&e._sanitizeLinkTargets(t));if("http://www.w3.org/1999/xhtml"!==t.namespaceURI||"_blank"!==(null===(i=t.getAttribute("target"))||void 0===i?void 0:i.toLowerCase()))return void t.removeAttribute("target");const s=(t.getAttribute("rel")||"").split(/\s+/).filter(e=>e&&!/^(opener|noopener)$/i.test(e));s.push("noopener"),t.setAttribute("rel",s.join(" "))})}_applyTransforms(t,i,s){this._is_bot()?e._logInfo(p_):"control"!==i?s.forEach(s=>{if(s.selector){var n;e._logInfo(`applying transform of variant ${i} for experiment ${t} `,s);const r=null===(n=document)||void 0===n?void 0:n.querySelectorAll(s.selector);if(!(null==r?void 0:r.length))return void e._logWarn(`no element on this page matches selector ${s.selector} of variant ${i} for experiment ${t}`);const o=new Map;null==r||r.forEach(t=>{if("script"===t.localName.toLowerCase())return;const i=t;if(s.html){var n;const a="http://www.w3.org/1998/Math/MathML"===t.namespaceURI&&"annotation-xml"===t.localName&&(null===(n=t.getAttribute("encoding"))||void 0===n?void 0:n.toLowerCase())||"",l=JSON.stringify([t.namespaceURI,t.localName,a]);let c=o.get(l);if(wt(c)){var r;const i=null!==(r=f_)&&void 0!==r?r:f_=__(),n=t.ownerDocument.implementation.createHTMLDocument(""),u=n.createElementNS(t.namespaceURI,t.localName);a&&u.setAttribute("encoding",a);const d=n.createRange();d.selectNodeContents(u);const h="http://www.w3.org/2000/svg"===t.namespaceURI&&/^(foreignObject|desc|title)$/.test(t.localName)||/^(text\/html|application\/xhtml\+xml)$/.test(a)?"http://www.w3.org/1999/xhtml":t.namespaceURI,_=d.createContextualFragment(s.html);"http://www.w3.org/1998/Math/MathML"===t.namespaceURI&&/^(mi|mo|mn|ms|mtext)$/.test(t.localName)?(u.appendChild(_),i.sanitize(u,ls(ls({},g_),{},{NAMESPACE:h||void 0,IN_PLACE:!0}))):("http://www.w3.org/1999/xhtml"===u.namespaceURI&&"template"===u.localName?u.content:u).appendChild(i.sanitize(_,ls(ls({},g_),{},{NAMESPACE:h||void 0,RETURN_DOM_FRAGMENT:!0}))),e._sanitizeLinkTargets(u),c=u.innerHTML,o.set(l,c)}i.innerHTML=c}s.css&&i.setAttribute("style",s.css)})}}):e._logInfo("Control variants leave the page unmodified.")}_is_bot(){return r&&this._instance?jc(r,this._config.custom_blocked_useragents):void 0}},conversations:class{constructor(e){this._instance=e,this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1,this._resetGeneration=0,this._pendingPanelAction=null,this._theme=null}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations)return void(this._pendingPanelAction=null);if(this._remoteConfigSuccessful=e.ok,!e.ok)return;const t=e.config.conversations;wt(t)?this._pendingPanelAction=null:(kt(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this._isConversationsEnabled||(this._pendingPanelAction=null),this.loadIfEnabled())}reset(){var e;null===(e=this._conversationsManager)||void 0===e||e.reset(),this._conversationsManager=null,this._resetGeneration++,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1,this._pendingPanelAction=null}loadIfEnabled(){if(this._conversationsManager)return;if(this._isInitializing)return;if(this._instance.config.disable_conversations)return;if(Vr(this._instance.config))return;if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=null==p?void 0:p.__PosthogExtensions__;if(e&&!mt(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=g(this._instance);if(!i)return void this._handleLoadError(L);const s=this._resetGeneration;i(this._instance,"conversations",t=>{if(s!==this._resetGeneration)return this._isInitializing=!1,void this.loadIfEnabled();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 m_.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,m_.info("Conversations loaded successfully")}catch(e){return void this._handleLoadError("Error completing conversations initialization",e)}this._theme&&this._conversationsManager.setTheme(this._theme),this._applyPendingPanelAction()}else m_.error("Cannot complete initialization: remote config is null")}_applyPendingPanelAction(){const e=this._pendingPanelAction;this._pendingPanelAction=null,this._conversationsManager&&e&&("open"===e?this._conversationsManager.open():this._conversationsManager.close())}_handleLoadError(e,t){m_.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():m_.warn("Conversations not loaded yet.")}hide(){"open"===this._pendingPanelAction&&(this._pendingPanelAction=null),this._conversationsManager&&this._conversationsManager.hide()}open(){this._conversationsManager?(this._pendingPanelAction=null,this._conversationsManager.open()):this._pendingPanelAction="open"}close(){this._conversationsManager?(this._pendingPanelAction=null,this._conversationsManager.close()):this._pendingPanelAction="close"}setTheme(e){var t,i;this._theme=ls(ls(ls({},this._theme),e),{},{dark:ls(ls({},null===(t=this._theme)||void 0===t?void 0:t.dark),null==e?void 0:e.dark)}),null===(i=this._conversationsManager)||void 0===i||i.setTheme(e)}isAvailable(){return!0===this._isConversationsEnabled&&!St(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Vr(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":!1===this._remoteConfigSuccessful?"remote_config_failed":mt(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?wt(this._remoteConfig)||!this._remoteConfig.token?"missing_token":(null==p?void 0:p.__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 Dt(function*(){return s._conversationsManager?s._conversationsManager.sendMessage(e,t,i):(m_.warn(y_),null)})()}getMessages(e,t){var i=this;return Dt(function*(){return i._conversationsManager?i._conversationsManager.getMessages(e,t):(m_.warn(y_),null)})()}markAsRead(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(m_.warn(y_),null)})()}getTickets(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(m_.warn(y_),null)})()}requestRestoreLink(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(m_.warn(y_),null)})()}restoreFromToken(e){var t=this;return Dt(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(m_.warn(y_),null)})()}restoreFromUrlToken(){var e=this;return Dt(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(m_.warn(y_),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()}},logs:class extends P_{constructor(e){super({get(){var t;return null==e||null===(t=e.config)||void 0===t?void 0:t.logs},captureHintKey:ne,get remoteConfigWillArrive(){var t,i;return!(null===(t=e._shouldDisableFlags)||void 0===t?void 0:t.call(e))||!!(null===(i=p._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:n,lastActivityTimestamp:r}=e.sessionManager.checkAndGetSessionAndWindowId(!0);i.sessionId=t,i.windowId=s,wt(n)||(i.sessionStartTimestamp=n),wt(r)||(i.lastActivityTimestamp=r)}if((null==p||null===(t=p.location)||void 0===t?void 0:t.href)&&(i.currentUrl=e.config.disable_capture_url_hashes?es(p.location.href):p.location.href),e.featureFlags){const t=e.featureFlags.getFlags();t&&t.length>0&&(i.activeFeatureFlags=t)}return i}(e)),this._instance=e,this.name=Cu,this._listenForReconnect()}get _isRequestReady(){return this._instance.__loaded}_getConsoleLoader(){const e=Or("[logs]"),t=null==p?void 0:p.__PosthogExtensions__;if(!t)return void e.error("PostHog Extensions not found.");const i=g(this._instance);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(L)}},metrics:class{constructor(e){this._instance=e,this._logger=Or("[metrics]"),this._disposed=!1,this._visibilityListening=!1,this._onVisibilityChange=()=>{"hidden"===(null==o?void 0:o.visibilityState)&&this.flush()}}initialize(){this.onConfigChange(),this._disposed||this._visibilityListening||!(null==o?void 0:o.addEventListener)||(Wr(o,"visibilitychange",this._onVisibilityChange),this._visibilityListening=!0)}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=L_(e,i),n=D_(e,i);return()=>{t=!1,s(),n()}})(this._instance):!t&&this._stopNetworkMetrics&&(this._stopNetworkMetrics(),this._stopNetworkMetrics=void 0)}_getCore(){var e;if(this._disposed)return;const t=null===(e=this._instance)||void 0===e||null===(e=e.config)||void 0===e?void 0:e.metrics;if(!this._core||this._resolvedFrom!==t){var i;null===(i=this._core)||void 0===i||i.reset(),this._resolvedFrom=t;const e=function(e){var t,i,s,n,r;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!==(n=null==e?void 0:e.flushIntervalMs)&&void 0!==n?n:1e4,maxSeriesPerFlush:null!==(r=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==r?r:1e3}}(t);mt(null==t?void 0:t.flushIntervalMs)&&(e.flushIntervalMs=6e4),this._core=new Ir(this._createHost(),e,this._logger)}return this._core}count(e,t=1,i){var s;null===(s=this._getCore())||void 0===s||s.count(e,t,i)}gauge(e,t,i){var s;null===(s=this._getCore())||void 0===s||s.gauge(e,t,i)}histogram(e,t,i){var s;null===(s=this._getCore())||void 0===s||s.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,i;this._disposed=!0,null==o||null===(e=o.removeEventListener)||void 0===e||e.call(o,"visibilitychange",this._onVisibilityChange),this._visibilityListening=!1,null===(t=this._stopNetworkMetrics)||void 0===t||t.call(this),this._stopNetworkMetrics=void 0,null===(i=this._core)||void 0===i||i.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 n=e=>{s||(s=!0,clearTimeout(r),i(e))},r=setTimeout(()=>n({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(ls(ls(ls({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),"hidden"===(null==o?void 0:o.visibilityState)&&{preferSyncCompression:!0}),{},{fireCallbackOnDrop:!0,callback(e){const t=e.statusCode;if(t>=200&&300>t)n({kind:"ok"});else if(413===t)n({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)n({kind:"fatal",error:new Error(`metrics request failed with status ${t}`)});else{var i;n({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)}},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==o?void 0:o.modelContext;if(!e||!gt(e.registerTool))return;const t=N_.get(e);if(t)return t.instances.add(this._instance),void(this._isPatched=!0);const i={instances:new Set([this._instance])},s=e.registerTool,n=this;sd(e,"registerTool",e=>{const t=e;return function(e,...s){let r=e;try{r=n._wrapTool(e,i)}catch(i){return t.call(this,e,...s)}return t.call(this,r,...s)}}),e.registerTool!==s&&(N_.set(e,i),this._isPatched=!0)}_wrapTool(e,t){if(!e||!gt(e.execute))return e;const i=e.execute,s=this,{tool:n,injected:r}=function(e,t){const i={intent:!1,model:!1},s=e.inputSchema;if(!function(e){return!!mt(e)||ft(e)&&Object.keys(e).every(e=>B_.has(e)||e.startsWith("x-"))&&!0!==e.additionalProperties&&!ft(e.additionalProperties)&&(!e.type||"object"===e.type)&&(!e.properties||ft(e.properties))&&(!e.required||pt(e.required))}(s))return{tool:j_(e),injected:i};const n=(null==s?void 0:s.properties)||{},r=e=>q_(n,e)||pt(null==s?void 0:s.required)&&s.required.includes(e);if(i.intent=t.intent&&!r("context"),i.model=t.model&&!r("llm_model"),!i.intent&&!i.model)return{tool:j_(e),injected:i};const o=ls({},n),a=pt(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 model identifier you are running as, for example "claude-opus-4-8" or "gpt-5.2". Pass "unknown" if you are not certain. Recorded for the site developer\'s analytics.'},a.includes("llm_model")||a.push("llm_model")),{tool:j_(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=H_(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(n,"execute",{configurable:!0,enumerable:!0,writable:!0,value(...o){const a=new Date,l=function(e,t){if(!ft(e))return{};try{const i=t.intent?W_(e.context,2048,!0):void 0,s=t.model?W_(e.llm_model,256):void 0;return ls(ls({},i&&"{}"!==i?{intent:i}:{}),s&&"unknown"!==s.toLowerCase()?{model:s}:{})}catch(e){return{}}}(o[0],r),c=function(e,t){const i=e[0];if(!ft(i))return e;try{const s=t.intent&&q_(i,"context"),n=t.model&&q_(i,"llm_model");if(!s&&!n)return e;const r=ls({},i);return s&&delete r.context,n&&delete r.llm_model,[r,...e.slice(1)]}catch(t){return e}}(o,r);let u;try{u=i.apply(this===n?e:this,c)}catch(e){throw s._captureToolCall(t,n,a,{error:e,errorResult:!1},l),e}if((d=u)&&"function"==typeof d.then)return Promise.resolve(u).then(e=>{const i=V_(e)?{error:e,errorResult:!0}:void 0;return s._captureToolCall(t,n,a,i,l),e},e=>{throw s._captureToolCall(t,n,a,{error:e,errorResult:!1},l),e});var d;const h=V_(u)?{error:u,errorResult:!0}:void 0;return s._captureToolCall(t,n,a,h,l),u}}),n}_captureToolCall(e,t,i,s,n){const r=Date.now()-i.getTime();let o;for(const c of e.instances){var l;const e=H_(c.config.capture_webmcp);if(e){s&&!o&&(o=J_(s.error,s.errorResult));try{c.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==a?void 0:a.hostname,$mcp_duration_ms:r,$mcp_is_error:!!s},o?{$mcp_error_type:o.type,$mcp_error_message:o.message}:{}),e.intent&&n.intent?{$mcp_intent:n.intent,$mcp_intent_source:"context_parameter"}:{}),e.model&&n.model?{$mcp_llm_model:n.model,$mcp_llm_model_source:"self_reported"}:{}),{timestamp:i})}catch(e){continue}if(s&&o&&c.exceptions&&(null===(l=c.exceptionObserver)||void 0===l?void 0:l.isEnabled))try{const e={$exception_list:Y_(c.exceptions,s,o.message),$exception_level:"error",$exception_source:"mcp.tool_call",$mcp_interface:"webmcp",$mcp_tool_name:t.name,$mcp_resource_name:t.name,$mcp_tool_description:t.description,$mcp_server_name:null==a?void 0:a.hostname};c.exceptionObserver.captureException(e)}catch(e){}}}}}});const Z_=function(){i.SDK_DIST_CHANNEL="npm";const e=Fu[ju]=new Ju;return function(){function e(){e.done||(e.done=!0,Rc=!1,Dr(Fu,function(e){e._dom_loaded()}))}(null==o?void 0:o.addEventListener)?"complete"===o.readyState?e():Wr(o,"DOMContentLoaded",e,{capture:!1}):s&&Mr.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),e}();export{dl as Compression,El as DEFAULT_PRODUCT_TOUR_APPEARANCE,wl as DisplaySurveyType,Ju as PostHog,kl as ProductTourEventName,xl as ProductTourEventProperties,bl as SurveyEventName,Sl as SurveyEventProperties,hl as SurveyEventType,pl as SurveyPosition,ml as SurveyQuestionBranchingType,vl as SurveyQuestionType,yl as SurveySchedule,gl as SurveyTabPosition,fl as SurveyType,_l as SurveyWidgetType,Z_ as default,Z_ as posthog,Rl as severityLevels};
2
2
  //# sourceMappingURL=module.no-external.js.map