diff --git a/NOTICES.md b/NOTICES.md
index 56b53f6..a00b792 100644
--- a/NOTICES.md
+++ b/NOTICES.md
@@ -31,6 +31,18 @@ be distributed under **AGPL-3.0**, with the following scope:
A copy of the exchange is retained by the project author.
+## Third-party code bundled in this repository
+
+Vendored under `map/static/map/vendor/` and shipped as-is, each under its own
+license:
+
+- **Leaflet** (`vendor/leaflet.js`, `vendor/leaflet.css`) -- BSD-2-Clause,
+ (c) Volodymyr Agafonkin / CloudMade.
+- **posthog-js** 1.427.2 (`vendor/posthog.js`, the upstream
+ `dist/array.no-external.js` build) -- MIT and Apache-2.0, (c) PostHog Inc.
+ . Loaded only by the hosted site;
+ see `analytics.js` for the gate and for what is sent.
+
## Not licensed by this repository
- The **Satisfactory Save Map** name, logo, and the `satisfactorymap.net`
diff --git a/README.md b/README.md
index a1aaa9d..74dc6cb 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,11 @@ up to **15 seconds at a time** — WebGL rendering instead of DOM markers
over HTTP). The file downloads directly into your browser — never through
this site's servers — so its host must allow cross-origin (CORS) requests.
- **Private by construction** — fully client-side; the save never leaves
- your machine. Works offline once loaded.
+ your machine. Works offline once loaded. satisfactorymap.net counts
+ anonymous, cookieless usage (page views, and how long a parse took) via
+ PostHog's EU region; nothing about the save itself is sent, and the desktop
+ app and any local build send nothing at all. See `map/static/map/analytics.js`
+ — it is short, and it is the whole of it.

diff --git a/map/static/map/analytics.js b/map/static/map/analytics.js
new file mode 100644
index 0000000..51ba008
--- /dev/null
+++ b/map/static/map/analytics.js
@@ -0,0 +1,211 @@
+/* Product analytics for the hosted site (PostHog).
+ *
+ * Deliberately small: is the site used, do saves parse, and which features do
+ * people actually open. Nothing about the save itself is sent -- no session
+ * name, no file name, no coordinates, no item names -- only shape and timing
+ * numbers, because the whole promise of this app is that your save never
+ * leaves your machine and analytics must not quietly walk that back.
+ */
+var Analytics = (function() {
+ "use strict";
+
+ // Public (write-only) project key. It is meant to be readable in client
+ // code -- it can send events and nothing else. Empty disables analytics
+ // entirely, which is the state a fork or a self-hosted copy inherits.
+ var PROJECT_KEY = "phc_yiJoNLSnBrq7BApC5VfDmzeB7H6oXui49QsQUEHgBM8W";
+ var API_HOST = "https://eu.i.posthog.com";
+
+ // Build-version query of this script's own URL, so the vendored library is
+ // cache-busted by a rebuild exactly like every tag build_site.py stamps.
+ // (Same idiom as save_client.js; the injected tag is not in index.html, so
+ // stampAssetVersion never sees it.) Empty when serving unstamped sources.
+ var ASSET_QUERY = (function() {
+ try {
+ var src = document.currentScript && document.currentScript.src;
+ return src ? new URL(src).search : "";
+ } catch (e) {
+ return "";
+ }
+ })();
+
+ var loaded = false;
+ // Events fired before the library finishes loading. Bounded because a
+ // failed load must not grow this without limit for the whole session.
+ var pending = [];
+ var PENDING_MAX = 32;
+
+ // The desktop app bundles this very dist/ (tauri.conf.json frontendDist),
+ // so "hosted site only" is a runtime question, not a build one: there is no
+ // separate web build to put the snippet in. The desktop CSP would block the
+ // request anyway -- gating here is what keeps the app genuinely
+ // phone-home-free rather than merely failing to phone home.
+ function enabled() {
+ if (!PROJECT_KEY) {
+ return false;
+ }
+ if (window.__TAURI__) {
+ return false;
+ }
+ // Local dev and file:// runs would otherwise land in the same project as
+ // real traffic and skew every number in it.
+ var host = location.hostname;
+ return !!host && host !== "localhost" && host !== "127.0.0.1" && host !== "[::1]";
+ }
+
+ var ENABLED = enabled();
+
+ function flush() {
+ for (var i = 0; i < pending.length; i++) {
+ try {
+ window.posthog.capture(pending[i][0], pending[i][1]);
+ } catch (e) { /* analytics must never break the app */ }
+ }
+ pending = [];
+ }
+
+ function start() {
+ if (!ENABLED) {
+ return;
+ }
+ var script = document.createElement("script");
+ // Vendored (see vendor/posthog.js): the site ships COEP require-corp for
+ // wasm, under which a plain cross-origin
+
diff --git a/map/static/map/panels.js b/map/static/map/panels.js
index 17405bc..74fffab 100644
--- a/map/static/map/panels.js
+++ b/map/static/map/panels.js
@@ -162,6 +162,7 @@
el.style.display = "";
currentTool = el;
body.classList.add("tool-open");
+ Analytics.toolOpened(el.id);
};
Panels.closeTool = function(el) {
diff --git a/map/static/map/vendor/posthog.js b/map/static/map/vendor/posthog.js
new file mode 100644
index 0000000..ed0d572
--- /dev/null
+++ b/map/static/map/vendor/posthog.js
@@ -0,0 +1 @@
+!function(){"use strict";function e(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function t(t){return function(){var i=this,s=arguments;return new Promise((function(r,n){var o=t.apply(i,s);function a(t){e(o,r,n,a,l,"next",t)}function l(t){e(o,r,n,a,l,"throw",t)}a(void 0)}))}}function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var i=arguments[t];for(var s in i)({}).hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},i.apply(null,arguments)}function s(e,t){if(null==e)return{};var i={};for(var s in e)if({}.hasOwnProperty.call(e,s)){if(-1!==t.indexOf(s))continue;i[s]=e[s]}return i}var r={DEBUG:!1,LIB_VERSION:"0.7.2",LIB_NAME:"browser-common"};r.DEBUG=!1,r.LIB_VERSION="1.427.2",r.LIB_NAME="web";var n="$people_distinct_id",o="distinct_id",a="$device_id",l="$device_model",u="__alias",c="$fbc",d="$fbc_persistence",h="__timers",_="$autocapture_disabled_server_side",p="$heatmaps_enabled_server_side",g="$exception_capture_enabled_server_side",v="$error_tracking_suppression_rules",f="$error_tracking_capture_extension_exceptions",m="$web_vitals_enabled_server_side",y="$dead_clicks_enabled_server_side",b="$product_tours_enabled_server_side",S="$logs_capture_enabled_server_side",w="$web_vitals_allowed_metrics",C="$session_recording_remote_config",k="$replay_sample_rate",E="$replay_override_sampling",x="$replay_override_linked_flag",P="$replay_override_url_trigger",F="$replay_override_event_trigger",I="$sesid",T="$session_is_sampled",R="$enabled_feature_flags",A="$active_feature_flags",L="$early_access_features",M="$feature_flag_details",O="$feature_flag_payloads",D="$feature_flag_request_id",B="$minimal_flag_called_events",q="$override_feature_flags",H="$override_feature_flag_payloads",N="$stored_person_properties",z="$stored_group_properties",j="$groups",V="$surveys",U="$surveys_loaded_at",W="$surveys_activated",G="$surveys_activated_session",K="$surveys_activated_timestamps",Q="ph_product_tours",J="$flag_call_reported",Y="$flag_call_reported_session_id",Z="$feature_flag_errors",X="$feature_flag_evaluated_at",ee="$user_state",te="$client_session_props",ie="$capture_rate_limit",se="$initial_campaign_params",re="$initial_referrer_info",ne="$initial_person_info",oe="$epp",ae="$posthog_cookieless",le="$cookieless_mode",ue="$sdk_debug_extensions_init_method",ce="$sdk_debug_extensions_init_time_ms",de="$sdk_debug_recording_script_not_loaded",he="PostHog loadExternalDependency extension not found.",_e="on_reject",pe="always",ge="anonymous",ve="identified",fe="identified_only",me="visibilitychange",ye="beforeunload",be="$pageview",Se="$pageleave",we="$identify",Ce="$groupidentify",ke="u">typeof window?window:void 0,Ee="u">typeof globalThis?globalThis:ke,xe=null==Ee?void 0:Ee.navigator,Pe=null==Ee?void 0:Ee.document,Fe=null==Ee?void 0:Ee.location,Ie=null==Ee?void 0:Ee.fetch,Te=null!=Ee&&Ee.XMLHttpRequest&&"withCredentials"in new Ee.XMLHttpRequest?Ee.XMLHttpRequest:void 0,Re=null==Ee?void 0:Ee.AbortController,Ae=null==Ee?void 0:Ee.CompressionStream,Le=null==xe?void 0:xe.userAgent;function Me(){return!(!ke||!1===ke.navigator.onLine)}var $e="undefined"!=typeof globalThis?globalThis:ke;$e&&"undefined"==typeof self&&($e.self=$e),$e&&"undefined"==typeof File&&($e.File=function(){});var Oe=null!=ke?ke:{},De=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Be=function(e,t){if(void 0===t&&(t=[]),!e)return!1;var i=e.toLowerCase();return De.concat(t).some((e=>{var t=e.toLowerCase();return-1!==i.indexOf(t)}))};function qe(e,t){return-1!==e.indexOf(t)}var He=function(e){return e.trim()},Ne=function(e){return e.replace(/^\$/,"")};function ze(e){var t,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"}var je=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.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e}({}),Ve=function(e){return e.GZipJS="gzip-js",e.Base64="base64",e}({}),Ue=["$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"],We=["token"],Ge=Object.prototype,Ke=Ge.hasOwnProperty,Qe=Ge.toString,Je=Array.isArray||function(e){return"[object Array]"===Qe.call(e)},Ye=e=>"function"==typeof e,Ze=e=>e===Object(e)&&!Je(e),Xe=e=>{if(Ze(e)){for(var t in e)if(Ke.call(e,t))return!1;return!0}return!1},et=e=>void 0===e,tt=e=>"[object String]"==Qe.call(e),it=e=>tt(e)&&0===e.trim().length,st=e=>null===e,rt=e=>et(e)||st(e),nt=e=>"[object Number]"==Qe.call(e)&&e==e,ot=e=>nt(e)&&e>0,at=e=>"[object Boolean]"===Qe.call(e),lt=e=>e instanceof FormData,ut=e=>qe(Ue,e),ct=e=>qe(We,e);function dt(e){return null===e||"object"!=typeof e}function ht(e,t){return{}.toString.call(e)==="[object "+t+"]"}function _t(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 gt(e,Error)}}function pt(e){return"u">typeof Event&>(e,Event)}function gt(e,t){try{return e instanceof t}catch(e){return!1}}var vt=[!0,"true",1,"1","yes"],ft=e=>qe(vt,e),mt=[!1,"false",0,"0","no"];function yt(e,t,i,s,r){return t>i&&(s.warn("min cannot be greater than max."),t=i),nt(e)?e>i?(s.warn(" cannot be greater than max: "+i+". Using max value instead."),i):t>e?(s.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(s.warn(" must be a number. using max or fallback. max: "+i+", fallback: "+r),yt(null!=r?r:i,t,i,s))}class bt{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=yt(e.bucketSize,0,100,e._logger),this._refillRate=yt(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=yt(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){var 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,i=Date.now(),s=String(e),r=this._buckets[s];return r?this._applyRefill(r,i):this._buckets[s]=r={tokens:this._bucketSize,lastAccess:i},0===r.tokens||(r.tokens--,0===r.tokens&&(null==(t=this._onBucketRateLimited)||t.call(this,e)),0===r.tokens)}stop(){this._buckets={}}}var St="Mobile",wt="iOS",Ct="Android",kt="Tablet",Et=Ct+" "+kt,xt="iPad",Pt="Apple",Ft=Pt+" Watch",It="Safari",Tt="BlackBerry",Rt="Samsung",At=Rt+"Browser",Lt=Rt+" Internet",Mt="Chrome",$t=Mt+" OS",Ot=Mt+" "+wt,Dt="Internet Explorer",Bt=Dt+" "+St,qt="Opera",Ht=qt+" Mini",Nt="Edge",zt="Microsoft "+Nt,jt="Firefox",Vt=jt+" "+wt,Ut="Nintendo",Wt="PlayStation",Gt="Xbox",Kt=Ct+" "+St,Qt=St+" "+It,Jt="Windows",Yt=Jt+" Phone",Zt="Nokia",Xt="Ouya",ei="Generic",ti=ei+" "+St.toLowerCase(),ii=ei+" "+kt.toLowerCase(),si="Konqueror",ri="Oculus Browser",ni="Vivaldi",oi="Yandex",ai="Whale",li="DuckDuckGo",ui="Pale Moon",ci="Waterfox",di="Brave",hi="Claude",_i="Codex",pi="ChatGPT",gi="Google Search App",vi="(\\d+(\\.\\d+)?)",fi=new RegExp("Version/"+vi),mi=new RegExp("("+hi+"|"+_i+"|"+pi+")\\/"+vi),yi=new RegExp(Gt,"i"),bi=new RegExp(Wt+" \\w+","i"),Si=new RegExp(Ut+" \\w+","i"),wi=new RegExp(Tt+"|PlayBook|BB10","i"),Ci={"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"},ki=function(e,t,i,s){t=t||"";var r=function(e){return null!=e&&e.brave?di:null}(i);return r||(null!=s&&s.detectGoogleSearchApp&&qe(e,"GSA/")?gi:qe(e," OPR/")&&qe(e,"Mini")?Ht:qe(e," OPR/")?qt:wi.test(e)?Tt:qe(e,"IE"+St)||qe(e,"WPDesktop")?Bt:qe(e,"OculusBrowser")?ri:qe(e,At)?Lt:qe(e,Nt)||qe(e,"Edg/")?zt:qe(e,ni+"/")?ni:qe(e,"YaBrowser/")?oi:qe(e,ai+"/")?ai:qe(e,li+"/")||qe(e,"Ddg/")?li:qe(e,hi+"/")?hi:qe(e,_i+"/")?_i:qe(e,pi+"/")?pi:qe(e,"FBIOS")?"Facebook "+St:qe(e,"UCWEB")||qe(e,"UCBrowser")?"UC Browser":qe(e,"CriOS")?Ot:qe(e,"CrMo")||qe(e,Mt)?Mt:qe(e,Ct)&&qe(e,It)?Kt:qe(e,"FxiOS")?Vt:qe(e.toLowerCase(),si.toLowerCase())?si:qe(e,di+"/")?di:((e,t)=>t&&qe(t,Pt)||function(e){return qe(e,It)&&!qe(e,Mt)&&!qe(e,Ct)}(e))(e,t)?qe(e,St)?Qt:It:qe(e,"PaleMoon/")?ui:qe(e,ci+"/")?ci:qe(e,jt)?jt:qe(e,"MSIE")||qe(e,"Trident/")?Dt:qe(e,"Gecko")?jt:"")},Ei={[Bt]:[new RegExp("rv:"+vi)],[zt]:[new RegExp(Nt+"?\\/"+vi)],[Mt]:[new RegExp("("+Mt+"|CrMo)\\/"+vi)],[Ot]:[new RegExp("CriOS\\/"+vi)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+vi)],[It]:[fi],[Qt]:[fi],[qt]:[new RegExp("(Opera|OPR)\\/"+vi)],[jt]:[new RegExp(jt+"\\/"+vi)],[Vt]:[new RegExp("FxiOS\\/"+vi)],[si]:[new RegExp("Konqueror[:/]?"+vi,"i")],[Tt]:[new RegExp(Tt+" "+vi),fi],[Kt]:[new RegExp("android\\s"+vi,"i")],[Lt]:[new RegExp(At+"\\/"+vi)],[ri]:[new RegExp("OculusBrowser\\/"+vi)],[ni]:[new RegExp(ni+"\\/"+vi)],[oi]:[new RegExp("YaBrowser\\/"+vi)],[ai]:[new RegExp(ai+"\\/"+vi)],[di]:[new RegExp(di+"\\/"+vi)],[hi]:[mi],[_i]:[mi],[pi]:[mi],[li]:[new RegExp("(DuckDuckGo|Ddg)\\/"+vi)],[ui]:[new RegExp("PaleMoon\\/"+vi)],[ci]:[new RegExp(ci+"\\/"+vi)],[gi]:[new RegExp("GSA\\/"+vi)],[Dt]:[new RegExp("(rv:|MSIE )"+vi)],Mozilla:[new RegExp("rv:"+vi)]},xi=function(e,t,i,s){var r=ki(e,t,i,s),n=Ei[r];if(et(n))return null;for(var o=0;n.length>o;o++){var a=e.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},Pi=[[new RegExp(Gt+"; "+Gt+" (.*?)[);]","i"),e=>[Gt,e&&e[1]||""]],[new RegExp(Ut,"i"),[Ut,""]],[new RegExp(Wt,"i"),[Wt,""]],[wi,[Tt,""]],[new RegExp(Jt,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Yt,""];if(new RegExp(St).test(t)&&!/IEMobile\b/.test(t))return[Jt+" "+St,""];var i=/Windows NT ([0-9.]+)/i.exec(t);if(i&&i[1]){var s=Ci[i[1]]||"";return/arm/i.test(t)&&(s="RT"),[Jt,s]}return[Jt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[wt,[e[3],e[4],e[5]||"0"].join(".")]:[wt,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=et(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ct+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ct+")","i"),e=>e&&e[2]?[Ct,[e[2],e[3],e[4]||"0"].join(".")]:[Ct,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var 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/,[$t,""]],[/Linux|debian/i,["Linux",""]]],Fi=function(e){for(var t=0;Pi.length>t;t++){var i=Pi[t],s=i[1],r=i[0].exec(e),n=r&&(Ye(s)?s(r,e):s);if(n)return n}return["",""]},Ii=function(e){return Si.test(e)?Ut:bi.test(e)?Wt:yi.test(e)?Gt:new RegExp(Xt,"i").test(e)?Xt:new RegExp("("+Yt+"|WPDesktop)","i").test(e)?Yt:/iPad/.test(e)?xt:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?Ft:wi.test(e)?Tt:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(Zt,"i").test(e)?Zt:/(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(St).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)?Ct:Et:new RegExp("(pda|"+St+")","i").test(e)?ti:new RegExp(kt,"i").test(e)&&!new RegExp(kt+" pc","i").test(e)?ii:""},Ti=20,Ri=1e3,Ai=1e4,Li="[Circular]",Mi="[Truncated]",$i="[Unserializable]",Oi="[Function]";function Di(e){for(var t="",i=0;e.length>i;i++){var s=e.charCodeAt(i);if(55296>s||s>56319)t+=56320>s||s>57343?e[i]:"�";else{var r=e.charCodeAt(i+1);56320>r||r>57343?t+="�":(t+=e[i]+e[i+1],i++)}}return t}var Bi,qi,Hi,Ni=/^[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)&&Ni.test(i)?e:t();var i}function ji(e,t){var i=new Error(t);try{Object.defineProperty(i,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){}return i}function Vi(e){return e?e.split("#")[0]:e}function Ui(e,t){var i=setTimeout(e,t);return(null==i?void 0:i.unref)&&(null==i||i.unref()),i}function Wi(e,t,i){return Gi.apply(this,arguments)}function Gi(){return(Gi=t((function*(e,t,i){var s;try{return yield Promise.race([e,new Promise(((e,r)=>{s=Ui((()=>{try{null==i||i(),e()}catch(e){r(e)}}),t)}))])}finally{clearTimeout(s)}}))).apply(this,arguments)}function Ki(e){var t=globalThis._posthogChunkIds;if(t){var i=Object.keys(t);return Hi&&i.length===qi||(qi=i.length,Hi=i.reduce(((i,s)=>{Bi||(Bi={});var r=Bi[s];if(r)i[r[0]]=r[1];else for(var n=e(s),o=n.length-1;o>=0;o--){var a=n[o],l=null==a?void 0:a.filename,u=t[s];if(l&&u){i[l]=u,Bi[s]=[l,u];break}}return i}),{})),Hi}}class Qi{constructor(e,t,i){void 0===i&&(i=[]),this.coercers=e,this.stackParser=t,this.modifiers=i}buildFromUnknown(e,t){void 0===t&&(t={});var i=t&&t.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(i,t,0).apply(e),r=this.buildParsingContext(t),n=this.parseStacktrace(s,r);return{$exception_list:this.convertToExceptionList(n,i),$exception_level:"error"}}modifyFrames(e){var i=this;return t((function*(){for(var t of e)t.stacktrace&&t.stacktrace.frames&&Je(t.stacktrace.frames)&&(t.stacktrace.frames=yield i.applyModifiers(t.stacktrace.frames));return e}))()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:null==(t=e.syntheticException)?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var s,r;return null!=e.cause&&(s=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(r=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),i({},e,{cause:s,stack:r})}applyChunkIds(e,t){return e.map((e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e)))}applyCoercers(e,t){for(var i of this.coercers)if(i.match(e))return i.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var i=this;return t((function*(){var t=e;for(var s of i.modifiers)t=yield s(t);return t}))()}convertToExceptionList(e,t){var s,r,n,o={type:e.type,value:e.value,mechanism:{type:null!==(s=t.type)&&void 0!==s?s:"generic",handled:null===(r=t.handled)||void 0===r||r,synthetic:null!==(n=e.synthetic)&&void 0!==n&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return null!=e.cause&&a.push(...this.convertToExceptionList(e.cause,i({},t,{handled:!0}))),a}buildParsingContext(e){var t;return{chunkIdMap:Ki(this.stackParser),skipFirstLines:null!==(t=e.skipFirstLines)&&void 0!==t?t:1}}buildCoercingContext(e,t,s){void 0===s&&(s=0);var r=(i,s)=>{if(4>=s){var r=this.buildCoercingContext(e,t,s);return this.applyCoercers(i,r)}};return i({},t,{syntheticException:0==s?t.syntheticException:void 0,mechanism:e,apply:e=>r(e,s),next:e=>r(e,s+1)})}}var Ji="?";function Yi(e,t,i,s,r){var n={platform:e,filename:t,function:""===i?Ji:i,in_app:!!t&&!t.startsWith("webkit-masked-url://")&&""!==t};return et(s)||(n.lineno=s),et(r)||(n.colno=r),n}var Zi=(e,t)=>{var i=-1!==e.indexOf("safari-extension"),s=-1!==e.indexOf("safari-web-extension");return i||s?[-1!==e.indexOf("@")?e.split("@")[0]:Ji,i?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},Xi=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,es=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ts=/\((\S*)(?::(\d+))(?::(\d+))\)/,is=(e,t)=>{var i=Xi.exec(e);if(i)return Yi(t,i[1],Ji,+i[2],+i[3]);var s=es.exec(e);if(s){if(s[2]&&0===s[2].indexOf("eval")){var r=ts.exec(s[2]);r&&(s[2]=r[1],s[3]=r[2],s[4]=r[3])}var n=Zi(s[1]||Ji,s[2]);return Yi(t,n[1],n[0],s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},ss=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,rs=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ns=(e,t)=>{var i=ss.exec(e);if(i){if(i[3]&&i[3].indexOf(" > eval")>-1){var s=rs.exec(i[3]);s&&(i[1]=i[1]||"eval",i[3]=s[1],i[4]=s[2],i[5]="")}var r=i[3],n=i[1]||Ji,o=Zi(n,r);return Yi(t,r=o[1],n=o[0],i[4]?+i[4]:void 0,i[5]?+i[5]:void 0)}},os=/\(error: (.*)\)/;class as{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){var i=tt(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){var t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?t+": "+e.message:t}isDOMException(e){return ht(e,"DOMException")}isDOMError(e){return ht(e,"DOMError")}}class ls{match(e){return _t(e)}coerce(e,t){var i,s=this.getStack(e),r=void 0===s;return{type:this.getType(e),value:this.getMessage(e,t),stack:null!=s?s:null==(i=t.syntheticException)?void 0:i.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:r}}getType(e){return e.name||e.constructor.name}getMessage(e,t){var i=e.message;return String(i.error&&"string"==typeof i.error.message?i.error.message:i)}getStack(e){return e.stacktrace||e.stack||void 0}}class us{match(e){return!!ht(e,"ErrorEvent")&&(null!=e.error||this._hasUsableMessage(e))}coerce(e,t){var s;if(null!=e.error)return t.apply(e.error);var r=t.apply(e.message);return i({},r,{stack:null!==(s=this._buildLocationStack(e))&&void 0!==s?s:r.stack,synthetic:!0})}_hasUsableMessage(e){return tt(e.message)&&e.message.length>0}_buildLocationStack(e){var t,i,s=e,r=null!==(t=s.lineno)&&void 0!==t?t:0,n=null!==(i=s.colno)&&void 0!==i?i:0;if(tt(s.filename)&&0!==s.filename.length&&0!==r)return"Error\n at "+s.filename+":"+r+":"+n}}var cs=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class ds{match(e){return"string"==typeof e}coerce(e,t){var i,s=this.getInfos(e),r=s[0],n=s[1];return{type:null!=r?r:"Error",value:null!=n?n:e,stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}getInfos(e){var t="Error",i=e,s=e.match(cs);return s&&(t=s[1],i=s[2]),[t,i]}}var hs=["fatal","error","warning","log","info","debug"];function _s(e,t){void 0===t&&(t=40);var i=Object.keys(e);if(i.sort(),!i.length)return"[object has no keys]";for(var s=i.length;s>0;s--){var r=i.slice(0,s).join(", ");if(t>=r.length)return s===i.length?r:r.length>t?r.slice(0,t)+"...":r}return""}class ps{match(e){return"object"==typeof e&&null!==e}coerce(e,t){var i,s,r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:null!==(i=this.getStack(e))&&void 0!==i?i:null==(s=t.syntheticException)?void 0:s.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(pt(e))return e.constructor.name;var t="name"in e?e.name:void 0;return tt(t)&&!it(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){var 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;var i=this.getObjectClassName(e);return(i&&"Object"!==i?"'"+i+"'":"Object")+" captured as exception with keys: "+_s(e)}isSeverityLevel(e){return tt(e)&&!it(e)&&hs.indexOf(e)>=0}getStack(e){try{return tt(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:tt(e.stack)&&e.stack.length>0?e.stack:void 0}catch(e){return}}getErrorPropertyFromObject(e){for(var t in e)if({}.hasOwnProperty.call(e,t)){var i=e[t];if(_t(i))return i}}getObjectClassName(e){try{var t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}class gs{match(e){return pt(e)}coerce(e,t){var i,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+_s(e),stack:null==(i=t.syntheticException)?void 0:i.stack,synthetic:!0}}}class vs{match(e){return dt(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.stack,synthetic:!0}}}class fs{match(e){return ht(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!pt(e))return!1;try{var t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch(e){return!1}}coerce(e,t){var i,s=this.getUnhandledRejectionReason(e);return dt(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:null==(i=t.syntheticException)?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}}var ms="$message",ys="$timestamp",bs=new Set([ms,ys]),Ss={enabled:!0,max_bytes:32768};function ws(e){var t;return e?{enabled:null!==(t=e.enabled)&&void 0!==t?t:Ss.enabled,max_bytes:ks(e.max_bytes,Ss.max_bytes)}:i({},Ss)}class Cs{constructor(e){this._entries=[],this._totalBytes=0,this._config=ws(e)}setConfig(e){this._config=ws(e),this._trimToMaxBytes()}add(e){var t=function(e){var t;try{t=ze(e)}catch(e){return}try{var i=JSON.parse(t);if(!Ze(i))return;var s=i,r=s[ms],n=s[ys];if(!tt(r)||0===r.trim().length)return;if(!tt(n)&&!nt(n))return;return{step:s,json:t}}catch(e){return}}(e);if(t){var i=function(e){if("u">typeof TextEncoder)return(new TextEncoder).encode(e).length;for(var t=encodeURIComponent(e),i=0,s=0;t.length>s;s++)"%"===t[s]?(i+=1,s+=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;){var e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function ks(e,t){if(!nt(e)||1/0===e||-1/0===e)return t;var i=Math.floor(e);return 0>i?t:i}var Es=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch(t){return e}};function xs(e){return"string"==typeof e||e}function Ps(e){return"string"==typeof e?e:void 0}var Fs,Is=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],Ts="NativeGzipValidationError",Rs=e=>e.length>=2&&31===e[0]&&139===e[1],As=(e,t)=>e===Ve.GZipJS||t===Ve.GZipJS||"gzip"===t,Ls=e=>!(!e||"object"!=typeof e)&&"NotReadableError"===("name"in e?String(e.name):""),Ms=e=>{throw ji(Ts,"Native gzip produced invalid output: "+e)},$s=function(){var e=t((function*(e,t){18>e.size&&Ms("too-short");var i=new Uint8Array(yield e.slice(0,10).arrayBuffer());Rs(i)&&8===i[2]||Ms("invalid-header");var s=new DataView(yield e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{for(var t=(()=>{if(Fs)return Fs;Fs=[];for(var e=0;256>e;e++){for(var t=e,i=0;8>i;i++)t=1&t?3988292384^t>>>1:t>>>1;Fs[e]=t>>>0}return Fs})(),i=4294967295,s=0;e.length>s;s++)i=t[255&(i^e[s])]^i>>>8;return(4294967295^i)>>>0})(t)&&Ms("invalid-crc");var r=t.length>>>0;s.getUint32(4,!0)!==r&&Ms("invalid-size")}));return function(t,i){return e.apply(this,arguments)}}();function Os(){return Os=t((function*(e,i,s){void 0===i&&(i=!0);try{var r=(new TextEncoder).encode(e),n=new globalThis.CompressionStream("gzip"),o=n.writable.getWriter(),a=o.write(r).then((()=>o.close())).catch(function(){var e=t((function*(e){try{yield o.abort(e)}catch(e){}throw e}));return function(t){return e.apply(this,arguments)}}()),l=new Response(n.readable).blob(),u=(yield Promise.all([l,a]))[0];return yield $s(u,r),u}catch(e){if(null!=s&&s.rethrow)throw e;return i&&console.error("Failed to gzip compress data",e),null}})),Os.apply(this,arguments)}var Ds=0x8000000000000000,Bs="9223372036854775808",qs={}.propertyIsEnumerable;function Hs(e,t){try{return js(e,t,{ancestors:new WeakSet,remainingNodes:Ai},0)}catch(e){return[]}}function Ns(e,t,i,s){if(0>=i.remainingNodes)return{stringValue:Mi};if(i.remainingNodes--,at(e))return{boolValue:e};if("bigint"==typeof e)return function(e,t){var i=e.toString(),s=BigInt(Bs);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)};var r=BigInt(e).toString();return e>=Ds||-Ds>e?(null==t||t.debug("Attribute "+r+" is outside the int64 range; encoding it as a string"),{stringValue:r}):{intValue:r}}return{doubleValue:e}}if("string"==typeof e)return{stringValue:Di(e)};if("function"==typeof e)return{stringValue:Oi};if("symbol"==typeof e)return{stringValue:String(e)};if("object"==typeof e&&null!==e){if(i.ancestors.has(e))return{stringValue:Li};if(s>=Ti)return{stringValue:Mi};if(e instanceof Date){var n=e.getTime(),o=Number.isFinite(n)?e.toISOString():String(e);return{stringValue:"string"==typeof o?Di(o):String(o)}}i.ancestors.add(e);try{try{var a=e.toJSON;if("function"==typeof a)return Ns(a.call(e),t,i,s+1)}catch(e){}return Je(e)?{arrayValue:{values:zs(e,t,i,s+1)}}:{kvlistValue:{values:js(e,t,i,s+1)}}}finally{i.ancestors.delete(e)}}return{stringValue:Di(String(e))}}function zs(e,t,i,s){for(var r=[],n=Math.min(e.length,Ri),o=0;n>o&&i.remainingNodes>0;o++)try{var a=o in e?e[o]:void 0;if(rt(a))continue;r.push(Ns(a,t,i,s))}catch(e){r.push({stringValue:$i})}return e.length>o&&r.push({stringValue:Mi}),r}function js(e,t,i,s){var r=[];for(var n in e)if(qs.call(e,n)){if(!n){null==t||t.debug("Dropping an attribute with an empty key");continue}if(r.length>=Ri||0>=i.remainingNodes){null==t||t.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{var o=e[n];if(st(o)||et(o))continue;r.push({key:Di(n),value:Ns(o,t,i,s)})}catch(e){r.push({key:Di(n),value:{stringValue:$i}})}}return r}function Vs(e,t,s){return i({},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":s})}var Us={darwin:"macOS",win32:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",sunos:"SunOS",aix:"AIX","Mac OS X":"macOS"};var Ws={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Gs=Ws.info;function Ks(e){try{return Di(String(e))}catch(e){return $i}}function Qs(e,t,s,r){var n,o=Ws[e.level||"info"]||Gs,a=o.text,l=o.number,u=(void 0===(n=nt(r)?r:void 0)&&(n=Date.now()),String(n)+"000000"),c={};t.distinctId&&(c.posthogDistinctId=t.distinctId),t.sessionId&&(c.sessionId=t.sessionId),t.windowId&&(c["window.id"]=t.windowId),rt(t.sessionStartTimestamp)||(c.sessionStartTimestamp=String(t.sessionStartTimestamp)),rt(t.lastActivityTimestamp)||(c.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(c["url.full"]=t.currentUrl),t.screenName&&(c["screen.name"]=t.screenName),t.appState&&(c["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(c.feature_flags=t.activeFeatureFlags);var d=i({},c),h=e.attributes;if(h){var _=[];try{_=Object.keys(h)}catch(e){_=[]}for(var p of _){var g=void 0;try{g=h[p]}catch(e){g=$i}Object.defineProperty(d,p,{value:g,enumerable:!0,writable:!0,configurable:!0})}}var v={timeUnixNano:u,observedTimeUnixNano:u,severityNumber:l,severityText:a,body:{stringValue:Ks(e.body)},attributes:Hs(d,s)};return e.trace_id&&(v.traceId=e.trace_id),e.span_id&&(v.spanId=e.span_id),et(e.trace_flags)||(v.flags=e.trace_flags),v}function Js(e,t,i){return Vs(e,t,i)}function Ys(e,t,i,s){return{resourceLogs:[{resource:{attributes:Hs(t)},scopeLogs:[{scope:{name:i,version:s},logRecords:e}]}]}}let Zs=class{constructor(e,t,i,s,r,n,o){var a;void 0===n&&(n=()=>Promise.resolve()),this._instance=e,this._config=t,this._logger=i,this._getContext=s,this._onReady=r,this._waitForStoragePersist=n,this._scopeName=o,this._flushPromise=null,this._evictedSinceAdvance=0,this._queueGeneration=0,this._consecutiveFlushFailures=0,this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._maxBufferSize=t.maxBufferSize,this._maxQueueSize=Math.max(null!==(a=t.maxQueueSize)&&void 0!==a?a:t.maxBufferSize,t.maxBufferSize),this._flushIntervalMs=t.flushIntervalMs,this._maxBatchRecordsPerPost=t.maxBatchRecordsPerPost,this._rateCapWindowMs=t.rateCapWindowMs,this._maxLogsPerInterval=t.maxLogsPerInterval}clearQueue(){this._queueGeneration++,this._instance.setPersistedProperty(je.LogsQueue,[])}reset(){this._clearFlushTimer(),this._intervalWindowStart=0,this._intervalLogCount=0,this._droppedWarned=!1,this._consecutiveFlushFailures=0,this._maxBatchRecordsPerPost=this._config.maxBatchRecordsPerPost}onReconnect(){this._consecutiveFlushFailures=0,this._flushInBackground()}captureLog(e,t){var i;if(!this._instance.isDisabled&&!this._instance.optedOut&&null!=e&&e.body){var s=this._runBeforeSend(e);if(null!==s)if(s.body){if(this._checkRateLimit()){var r={record:Qs(s,null!==(i=null==t?void 0:t.context)&&void 0!==i?i:this._getContext(),this._logger,null==t?void 0:t.occurredAtMs)};this._onReady((()=>this._enqueue(r)))}}else this._logger.info("Log was rejected in beforeSend function")}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=Je(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Log was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for log:",e),null}return s}_checkRateLimit(){if(void 0===this._maxLogsPerInterval)return!0;var 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 t((function*(){if(!e._instance.isDisabled)return e._flushPromise||(e._flushPromise=e._flushInner().finally((()=>{e._flushPromise=null}))),e._flushPromise}))()}_flushInner(){var e=this;return t((function*(){var t;e._clearFlushTimer();var i=null!==(t=e._instance.getPersistedProperty(je.LogsQueue))&&void 0!==t?t:[];if(0!==i.length)for(var s=i.length,r=0;i.length>0&&s>r;){var n,o,a=e._queueGeneration;e._evictedSinceAdvance=0;var l=Math.min(i.length,e._maxBatchRecordsPerPost),u=i.slice(0,l),c=Ys(u.map((e=>e.record)),e._buildResourceAttributes(),null!==(n=e._scopeName)&&void 0!==n?n:e._instance.getLibraryId(),e._instance.getLibraryVersion()),d=yield e._instance._sendLogsBatch(c);if(e._queueGeneration!==a)return;if("too-large"===d.kind&&u.length>1)e._maxBatchRecordsPerPost=Math.max(1,Math.floor(u.length/2)),e._logger.warn("Received 413 when sending logs batch of size "+u.length+", reducing batch size to "+e._maxBatchRecordsPerPost);else{if("retry-later"===d.kind)throw d.error;if("too-large"===d.kind?e._logger.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):"ok"===d.kind&&e._config.maxBatchRecordsPerPost>e._maxBatchRecordsPerPost&&(e._maxBatchRecordsPerPost=Math.min(e._config.maxBatchRecordsPerPost,e._maxBatchRecordsPerPost+1)),yield e._persistQueueAdvance(u.length),i=null!==(o=e._instance.getPersistedProperty(je.LogsQueue))&&void 0!==o?o:[],r+=u.length,"fatal"===d.kind)throw d.error}}}))()}_persistQueueAdvance(e){var i=this;return t((function*(){var t,s=Math.max(0,e-i._evictedSinceAdvance),r=null!==(t=i._instance.getPersistedProperty(je.LogsQueue))&&void 0!==t?t:[];i._instance.setPersistedProperty(je.LogsQueue,r.slice(s)),yield i._waitForStoragePersist()}))()}_buildResourceAttributes(){return Js(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion())}_enqueue(e){var t;if(!this._instance.optedOut){var i=null!==(t=this._instance.getPersistedProperty(je.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(je.LogsQueue,i),this._maxBufferSize>i.length?this._armFlushTimer():this._flushInBackground()}}_armFlushTimer(e){void 0===e&&(e=this._flushIntervalMs),this._flushTimer||(this._flushTimer=Ui((()=>{this._flushTimer=void 0,this._flushInBackground()}),e))}_nextFlushDelay(){var e=Math.min(Math.max(0,this._consecutiveFlushFailures-1),6);return this._flushIntervalMs*Math.pow(2,e)}_hasQueuedRecords(){var e=this._instance.getPersistedProperty(je.LogsQueue);return!!e&&e.length>0}shutdown(e){var i=this;return t((function*(){i._clearFlushTimer();var t=i.flush().catch((()=>{}));void 0!==e?yield Wi(t,e):yield t}))()}flushWithTimeout(e){var i=this;return t((function*(){var t=i.flush();yield Wi(t,e,(()=>{t.catch((()=>{}))}))}))()}_flushInBackground(){this.flush().then((()=>{this._consecutiveFlushFailures=0}),(e=>{this._consecutiveFlushFailures++,this._logger.error("PostHog logs flush failed:",e)})).finally((()=>{!this._instance.isDisabled&&this._hasQueuedRecords()&&this._armFlushTimer(this._nextFlushDelay())}))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}};var Xs=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function er(e){return String(e)+"000000"}function tr(e,t,i,s){var r="";return s&&(r=Object.keys(s).sort().map((e=>JSON.stringify(e)+":"+JSON.stringify(s[e]))).join(",")),e+"\0"+t+"\0"+(null!=i?i:"")+"\0"+r}let ir=class{constructor(e,t,i){this._instance=e,this._config=t,this._logger=i,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t,i){void 0===t&&(t=1),this._capture({name:e,type:"count",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}gauge(e,t,i){this._capture({name:e,type:"gauge",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}histogram(e,t,i){this._capture({name:e,type:"histogram",value:t,unit:null==i?void 0:i.unit,attributes:null==i?void 0:i.attributes})}flush(){var e=this,i=this._flushPromise,s=function(){var s=t((function*(){i&&(yield i.catch((()=>{}))),yield e._doFlush()}));return function(){return s.apply(this,arguments)}}(),r=s().finally((()=>{this._flushPromise===r&&(this._flushPromise=null)}));return this._flushPromise=r,r}drainWindow(){if(0===this._series.size)return null;var e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){if(!this._instance.isDisabled&&!this._instance.optedOut){var t=this._runBeforeSend(e);if(null!==t)if(t.name&&"string"==typeof t.name)if("number"==typeof t.value&&Number.isFinite(t.value))if("count"===t.type&&0>t.value)this._logger.warn("Dropping count '"+t.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=t.attributes?i({},t.attributes):void 0,r=tr(t.type,t.name,t.unit,s)}catch(e){return void this._logger.warn("Dropping metric '"+t.name+"': attributes could not be serialized",e)}var n=this._series.get(r);if(!n){if(!this._admitNewSeries())return;n={name:t.name,type:t.type,unit:t.unit,attributes:s,windowStartMs:Date.now()},this._series.set(r,n)}var 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(n,t.value),this._armFlushTimer()}else this._logger.warn("Dropping metric '"+t.name+"': value must be a finite number");else this._logger.warn("Dropping metric with empty name")}}_admitNewSeries(){return this._config.maxSeriesPerFlush>this._series.size||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn("Metric series cap reached ("+this._config.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}_fold(e,t){var i;switch(e.type){case"count":e.total=(null!==(i=e.total)&&void 0!==i?i:0)+t;break;case"gauge":e.last=t;break;case"histogram":e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(Xs.length+1).fill(0)});var s=e.hist;s.count+=1,s.sum+=t,s.min=Math.min(s.min,t),s.max=Math.max(s.max,t),s.bucketCounts[function(e,t){for(var i=0;t.length>i;i++)if(t[i]>=e)return i;return t.length}(t,Xs)]+=1}}_runBeforeSend(e){var t=this._config.beforeSend;if(!t)return e;var i=Je(t)?t:[t],s=e;for(var r of i)try{var n=r(s);if(!n)return this._logger.info("Metric was rejected in beforeSend function"),null;s=n}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return s}_armFlushTimer(){this._flushTimer||(this._flushTimer=Ui((()=>{this._flushTimer=void 0,this.flush().catch((e=>{this._logger.error("Metrics flush failed:",e)}))}),this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}_doFlush(){var e=this;return t((function*(){if(0!==e._series.size){var t=e._series;e._series=new Map,e._seriesCapWarned=!1,e._typeByName=new Map,e._typeCollisionWarned=new Set;var i=e._generation,s=yield e._instance._sendMetricsBatch(e._buildPayload(t));if(i===e._generation)switch(s.kind){case"ok":return;case"retry-later":return e._mergeWindowBack(t),void e._armFlushTimer();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 Vs(e,t,i)}(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),s=this._instance.getLibraryId(),r=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Hs(i)},scopeMetrics:[{scope:{name:s,version:r},metrics:t}]}]};var t,i,s,r}_buildMetrics(e){var t=er(Date.now()),s=new Map;for(var r of e.values()){var n,o=tr(r.type,r.name,r.unit,void 0),a=s.get(o);a||(a=i({name:r.name},r.unit&&{unit:r.unit}),"count"===r.type?a.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===r.type?a.gauge={dataPoints:[]}:a.histogram={aggregationTemporality:1,dataPoints:[]},s.set(o,a));var l=Hs(null!==(n=r.attributes)&&void 0!==n?n:{},this._logger),u=er(r.windowStartMs);if("count"===r.type){var c,d={attributes:l,startTimeUnixNano:u,timeUnixNano:t,asDouble:null!==(c=r.total)&&void 0!==c?c:0};a.sum.dataPoints.push(d)}else if("gauge"===r.type){var h,_={attributes:l,timeUnixNano:t,asDouble:null!==(h=r.last)&&void 0!==h?h:0};a.gauge.dataPoints.push(_)}else r.hist&&a.histogram.dataPoints.push({attributes:l,startTimeUnixNano:u,timeUnixNano:t,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Xs})}return Array.from(s.values())}_mergeWindowBack(e){var t,i;for(var s of e){var r=s[0],n=s[1],o=this._series.get(r);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=(null!==(t=o.total)&&void 0!==t?t:0)+(null!==(i=n.total)&&void 0!==i?i:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this._admitNewSeries()&&this._series.set(r,n)}}};var sr=function(e,t){var i=(void 0===t?{}:t).debugEnabled,s={_log(t){if(ke&&(r.DEBUG||ke.POSTHOG_DEBUG||i)&&!et(ke.console)&&ke.console){for(var s=("__rrweb_original__"in ke.console[t]?ke.console[t].__rrweb_original__:ke.console[t]),n=arguments.length,o=new Array(n>1?n-1:0),a=1;n>a;a++)o[a-1]=arguments[a];s(e,...o)}},debug(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("debug",...t)},info(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("log",...t)},warn(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("warn",...t)},error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];s._log("error",...t)},critical(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];console.error(e,...i)},uninitializedWarning(e){s.error("You must initialize PostHog before calling "+e)},createLogger:(t,i)=>sr(e+" "+t,i)};return s},rr=sr("[PostHog.js]"),nr=rr.createLogger;function or(e,t){Je(e)&&e.forEach(t)}function ar(e,t){if(!rt(e))if(Je(e))e.forEach(t);else if(lt(e))e.forEach(((e,i)=>t(e,i)));else for(var i in e)Ke.call(e,i)&&t(e[i],i)}var lr=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];for(var r of i)for(var n in r)void 0!==r[n]&&(e[n]=r[n]);return e};function ur(e){for(var t=Object.keys(e),i=t.length,s=new Array(i);i--;)s[i]=[t[i],e[t[i]]];return s}var cr=function(e){try{return e()}catch(e){return}},dr=function(e){return function(){try{for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,i)}catch(e){rr.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),rr.critical(e)}}},hr=function(e){var t={};return ar(e,(function(e,i){(tt(e)&&e.length>0||nt(e))&&(t[i]=e)})),t};var _r=["herokuapp.com","vercel.app","netlify.app"];function pr(e){var t=null==e?void 0:e.hostname;if(!tt(t))return!1;var i=t.split(".").slice(-2).join(".");for(var s of _r)if(i===s)return!1;return!0}function gr(e,t,i,s){var r=null!=s?s:{},n=r.capture,o=r.passive;null==e||e.addEventListener(t,i,{capture:void 0!==n&&n,passive:void 0===o||o})}function vr(e){return"ph_toolbar_internal"===e.name}var fr=e=>{if(Pe){try{for(var t=e+"=",i=Pe.cookie.split(";").filter((e=>e.length)),s=0;i.length>s;s++){for(var r=i[s];" "==r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t))return decodeURIComponent(r.substring(t.length,r.length))}}catch(e){}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return nt(e)&&isFinite(e)&&Math.floor(e)===e});class mr{constructor(e){if(this.bytes=e,16!==e.length)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,t,i,s){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(i)||!Number.isInteger(s)||0>e||0>t||0>i||0>s||e>0xffffffffffff||t>4095||i>1073741823||s>4294967295)throw new RangeError("invalid field value");var r=new Uint8Array(16);return r[0]=e/Math.pow(2,40),r[1]=e/Math.pow(2,32),r[2]=e/Math.pow(2,24),r[3]=e/Math.pow(2,16),r[4]=e/256,r[5]=e,r[6]=112|t>>>8,r[7]=t,r[8]=128|i>>>24,r[9]=i>>>16,r[10]=i>>>8,r[11]=i,r[12]=s>>>24,r[13]=s>>>16,r[14]=s>>>8,r[15]=s,new mr(r)}toString(){for(var e="",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 mr(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(var t=0;16>t;t++){var i=this.bytes[t]-e.bytes[t];if(0!==i)return Math.sign(i)}return 0}}class yr{generate(){var e=this.generateOrAbort();if(!et(e))return e;this._timestamp=0;var t=this.generateOrAbort();if(et(t))throw new Error("Could not generate UUID after timestamp reset");return t}generateOrAbort(){var e=Date.now();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 mr.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 wr}}var br,Sr=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};ke&&!et(ke.crypto)&&crypto.getRandomValues&&(Sr=e=>crypto.getRandomValues(e));class wr{nextUint32(){return this._buffer.length>this._cursor||(Sr(this._buffer),this._cursor=0),this._buffer[this._cursor++]}constructor(){this._buffer=new Uint32Array(8),this._cursor=1/0}}var Cr=()=>kr().toString(),kr=()=>(br||(br=new yr)).generate(),Er="",xr=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;var Pr=null,Fr={_is_supported(){if(!st(Pr))return Pr;if(Pr=!1,Pe)try{var e="__ph_cookie_support_"+Cr();Fr._set(e,"xyz"),Pr='"xyz"'===fr(e),Fr._remove(e)}catch(e){Pr=!1}return Pr},_error(e){rr.error("cookieStore error: "+e)},_get:fr,_parse(e){var t;try{t=JSON.parse(Fr._get(e))||{}}catch(e){}return t},_set(e,t,i,s,r){if(!Pe)return!1;try{var n="",o="",a=function(e,t){if(t){var i=function(e,t){if(void 0===t&&(t=Pe),Er)return Er;if(!t)return"";if(["localhost","127.0.0.1"].includes(e))return"";for(var i=e.split("."),s=Math.min(i.length,8),r="dmn_chk_"+Cr();!Er&&s--;){var n=i.slice(s).join("."),o=r+"=1;domain=."+n+";path=/";t.cookie=o+";max-age=3",t.cookie.includes(r)&&(t.cookie=o+";max-age=0",Er=n)}return Er}(e);if(!i){var s=(e=>{var t=e.match(xr);return t?t[0]:""})(e);s!==i&&rr.info("Warning: cookie subdomain discovery mismatch",s,i),i=s}return i?"; domain=."+i:""}return""}(Pe.location.hostname,s);if(i){var l=new Date;l.setTime(l.getTime()+864e5*i),n="; expires="+l.toUTCString()}r&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&rr.warn("cookieStore warning: large cookie, len="+u.length),Pe.cookie=u,!0}catch(e){return!1}},_remove(e,t){if(null!=Pe&&Pe.cookie)try{Fr._set(e,"",-1,t)}catch(e){return}}},Ir=null,Tr={_is_supported(){if(!st(Ir))return Ir;var e=!0;if(et(ke))e=!1;else try{var t="__mplssupport__";Tr._set(t,"xyz"),'"xyz"'!==Tr._get(t)&&(e=!1),Tr._remove(t)}catch(t){e=!1}return e||rr.error("localStorage unsupported; falling back to cookie store"),Ir=e,e},_error(e){rr.error("localStorage error: "+e)},_get(e){try{return null==ke?void 0:ke.localStorage.getItem(e)}catch(e){Tr._error(e)}return null},_parse(e){try{return JSON.parse(Tr._get(e))||{}}catch(e){}return null},_set(e,t){try{return null==ke||ke.localStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Tr._error(e)}return!1},_remove(e){try{null==ke||ke.localStorage.removeItem(e)}catch(e){Tr._error(e)}}},Rr=[N,A,R,M,O,D,X,Z,J],Ar=[a,o,I,T,oe,ne,d,ee],Lr=e=>e+"_cpm",Mr=["__proto__","constructor","prototype"],$r=e=>{if(!Ze(e))return{};var t={};return Object.keys(e).forEach((i=>{-1===Mr.indexOf(i)&&(t[i]=e[i])})),t},Or=function(e,t){void 0===t&&(t=[]);var i={};return[...Ar,...t].forEach((t=>{var s=e[t];et(s)||st(s)||""===s||(i[t]=s)})),i},Dr=e=>{for(var t=5381,i=2166136261,s=0;e.length>s;s++){var r=e.charCodeAt(s);t=33*t^r,i=Math.imul(i^r,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(i>>>0).toString(36)},Br=(e,t)=>({p:t,f:Dr(JSON.stringify(e))}),qr=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{var i=Fr._parse(Lr(e)),s=(null==i?void 0:i.f)===Dr(t)&&Je(i.p);return{properties:s?i.p:[],isValid:s}}catch(e){return{properties:[],isValid:!1}}},Hr=(e,t)=>t+"|"+(Fr._get(Lr(e))||""),Nr={},zr={_is_supported:()=>!0,_error(e){rr.error("memoryStorage error: "+e)},_get:e=>e in Nr?Nr[e]:null,_parse:e=>e in Nr?Nr[e]:null,_set:(e,t)=>(Nr[e]=t,!0),_remove(e){delete Nr[e]}},jr=null,Vr={_is_supported(){if(!st(jr))return jr;if(jr=!0,et(ke))jr=!1;else try{var e="__support__";Vr._set(e,"xyz"),'"xyz"'!==Vr._get(e)&&(jr=!1),Vr._remove(e)}catch(e){jr=!1}return jr},_error(e){rr.error("sessionStorage error: ",e)},_get(e){try{return null==ke?void 0:ke.sessionStorage.getItem(e)}catch(e){Vr._error(e)}return null},_parse(e){try{return JSON.parse(Vr._get(e))||null}catch(e){}return null},_set(e,t){try{return null==ke||ke.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(e){Vr._error(e)}return!1},_remove(e){try{null==ke||ke.sessionStorage.removeItem(e)}catch(e){Vr._error(e)}}};class Ur{constructor(e){this._instance=e}get _config(){return this._instance.config}get consent(){return this._getDnt()?0:this._storedConsent}isOptedOut(){return this._config.cookieless_mode===pe||this.isRejected()||-1===this.consent&&this._config.cookieless_mode===_e}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(){var e=this._instance.config,t=e.token,i=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(i?i+t:"__ph_opt_in_out_"+t)}get _storedConsent(){var e=this._storage._get(this._storageKey);return ft(e)?1:qe(mt,e)?0:-1}get _storage(){var e=this._config.opt_out_capturing_persistence_type,t="localStorage"===e?Tr:Fr,i=t._is_supported()?t:zr;if(!this._persistentStore||this._persistentStore!==i){this._persistentStore=i;var s="localStorage"===e?Fr:Tr;s._get(this._storageKey)&&(this._persistentStore._get(this._storageKey)||this.optInOut(ft(s._get(this._storageKey))),s._remove(this._storageKey,this._config.cross_subdomain_cookie))}return this._persistentStore}_getDnt(){return!!this._config.respect_dnt&&[null==xe?void 0:xe.doNotTrack,null==xe?void 0:xe.msDoNotTrack,Oe.doNotTrack,null==xe?void 0:xe.globalPrivacyControl].some((e=>ft(e)))}}function Wr(e,t){var i,s=null==e||null==(i=e.config)?void 0:i.get_current_url;if(!Ye(s))return t;try{var r=s(t);return tt(r)&&r?r:t}catch(e){return rr.error("Error in get_current_url, falling back to window.location.href",e),t}}var Gr="__POSTHOG_TOOLBAR__",Kr=1,Qr=3,Jr=11;function Yr(e){return e instanceof Element&&(e.id===Gr||!(null==e.closest||!e.closest(".toolbar-global-fade-container")))}function Zr(e){return!!e&&e.nodeType===Kr}function Xr(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function en(e){return!!e&&e.nodeType===Qr}function tn(e){return!!e&&e.nodeType===Jr&&Zr(e.host)}var sn=1e3;function rn(e){return e?He(e).split(/\s+/):[]}function nn(e,t){var i=function(e){var t,i=null==ke||null==(t=ke.location)?void 0:t.href;return et(i)?void 0:Wr(e,i)}(t);return!!(i&&e&&e.some((e=>i.match(e))))}function on(e){var 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 rn(t)}function an(e){return rt(e)?null:He(e).split(/(\s+)/).filter((e=>Rn(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ln(e){var t="";return wn(e)&&!Cn(e)&&e.childNodes&&e.childNodes.length&&ar(e.childNodes,(function(e){var i;en(e)&&e.textContent&&(t+=null!==(i=an(e.textContent))&&void 0!==i?i:"")})),He(t)}function un(e){var t;return et(e.target)?e.srcElement||null:null!=(t=e.target)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var cn=["a","button","form","input","select","textarea","label"];function dn(e,t){if(et(t))return!0;var i,s=function(e){if(t.some((t=>function(e,t){var i=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!i&&i.call(e,t)}catch(e){return!1}}(e,t))))return{v:!0}};for(var r of e)if(i=s(r))return i.v;return!1}function hn(e){var t=e.parentNode;return!(!t||!Zr(t))&&t}var _n=[".ph-no-autocapture","[data-ph-no-autocapture]"],pn=["next","previous","prev",">","<"],gn=[...pn,"+","-","−","–"],vn=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,fn=[".ph-no-rageclick",".ph-no-capture"],mn=["","text","search","email","password","url","tel","number"];function yn(e,t){if(!ke||bn(e))return!1;var i,s,r,n,o;if(at(t)?(i=!!t&&fn,s=void 0,r=!1):(i=null!==(n=null==t?void 0:t.css_selector_ignorelist)&&void 0!==n?n:fn,s=null==t?void 0:t.content_ignorelist,r=null!==(o=null==t?void 0:t.ignore_text_selection)&&void 0!==o&&o),!1===i)return!1;if(r&&function(e){return!(!e||!Zr(e))&&(!!Xr(e,"textarea")||(Xr(e,"input")?qe(mn,(e.getAttribute("type")||"").toLowerCase()):function(e){if(e.isContentEditable)return!0;var t=null==e.getAttribute?void 0:e.getAttribute("contenteditable");return"true"===t||""===t}(e)))}(e))return!1;var a=Sn(e,!1).targetElementList;return!function(e,t){if(!1===e||et(e))return!1;var i;if(!0===e)i=pn;else{if(!Je(e))return!1;if(e.length>10)return rr.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;i=e.map((e=>e.toLowerCase()))}return t.some((e=>{var t=e.safeText,s=e.ariaLabel;return i.some((e=>vn(t,e)||vn(s,e)))}))}(s,a.map((e=>{var t;return{safeText:ln(e).toLowerCase(),ariaLabel:(null==(t=e.getAttribute("aria-label"))?void 0:t.toLowerCase().trim())||""}})))&&!dn(a,i)}var bn=e=>!e||Xr(e,"html")||!Zr(e),Sn=(e,t)=>{if(!ke||bn(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var i=!1,s=[e],r=e;r.parentNode&&!Xr(r,"body");)if(tn(r.parentNode))s.push(r.parentNode.host),r=r.parentNode.host;else{var n=hn(r);if(!n)break;if(t||cn.indexOf(n.tagName.toLowerCase())>-1)i=!0;else try{var o=ke.getComputedStyle(n);o&&"pointer"===o.getPropertyValue("cursor")&&(i=!0)}catch(e){}s.push(n),r=n}return{parentIsUsefulElement:i,targetElementList:s}};function wn(e){for(var t=new Set,i=0,s=e;s.parentNode&&!Xr(s,"body");s=s.parentNode){if(i++>=sn||t.has(s))return!1;t.add(s);var r=on(s);if(qe(r,"ph-sensitive")||qe(r,"ph-no-capture"))return!1}if(qe(on(e),"ph-include"))return!0;var n=e.type||"";if(tt(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=e.name||e.id||"";return!tt(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function Cn(e){return!!(Xr(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||Xr(e,"select")||Xr(e,"textarea")||"true"===e.getAttribute("contenteditable"))}var kn=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}))$"),En=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,xn=[16,15,14,13],Pn=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),Fn=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),In=/[0-9A-Za-z_]/;function Tn(e){for(var t=0,i=!1,s=e.length-1;s>=0;s--){var r=e.charCodeAt(s)-48;i&&(r*=2)>9&&(r-=9),t+=r,i=!i}return t%10==0}function Rn(e,t){if(void 0===t&&(t=!0),rt(e))return!1;if(tt(e)){e=He(e);var i=t?kn.test((e||"").replace(/[- ]/g,"")):function(e){var t;for(En.lastIndex=0;t=En.exec(e);){var i=t[2];if(i)for(var s=i.replace(/[- ]/g,""),r=0;s.length>r;r++)for(var n of xn){var o=r+n;if(s.length>=o){var a=s.slice(r,o);if(kn.test(a)&&Tn(a))return!0}}}return!1}(e);if(i)return!1;var s=t?Pn.test(e):function(e){var t;for(Fn.lastIndex=0;t=Fn.exec(e);){var i=t[1],s=t[3];if(!(i&&s&&In.test(i)&&In.test(s)))return!0}return!1}(e);if(s)return!1}return!0}function An(e){var t=ln(e);return Rn(t=(t+" "+Ln(e)).trim())?t:""}function Ln(e){var t="";return e&&e.childNodes&&e.childNodes.length&&ar(e.childNodes,(function(e){var i;if(e&&"span"===(null==(i=e.tagName)?void 0:i.toLowerCase()))try{var s=ln(e);t=(t+" "+s).trim(),e.childNodes&&e.childNodes.length&&(t=(t+" "+Ln(e)).trim())}catch(e){rr.error("[AutoCapture]",e)}})),t}function Mn(e){return e.replace(/"|\\"/g,'\\"')}function $n(e){var t=e.attr__class;if(t)return Je(t)?t:rn(t)}var On=nr("[Dead Clicks]"),Dn=()=>!0,Bn=e=>{var t,i=!(null==(t=e.instance.persistence)||!t.get_property(y)),s=e.instance.config.capture_dead_clicks;return at(s)?s:!!Ze(s)||i};class qn{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){var t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[y]:t.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this._loadScript((()=>{this._start()})):this.stop()}_loadScript(e){var t,i;null!=(t=Oe.__PosthogExtensions__)&&t.initDeadClicksAutocapture?e():null==(i=Oe.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this.instance,"dead-clicks-autocapture",(t=>{t?On.error("failed to load script",t):e()}))}_start(){var e;if(Pe){if(!this._lazyLoadedDeadClicksAutocapture&&null!=(e=Oe.__PosthogExtensions__)&&e.initDeadClicksAutocapture){var t=Ze(this.instance.config.capture_dead_clicks)?i({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this._lazyLoadedDeadClicksAutocapture=Oe.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this._lazyLoadedDeadClicksAutocapture.start(Pe),On.info("starting...")}}else On.error("`document` not found. Cannot start.")}stop(){this._lazyLoadedDeadClicksAutocapture&&(this._lazyLoadedDeadClicksAutocapture.stop(),this._lazyLoadedDeadClicksAutocapture=void 0,On.info("stopping..."))}}var Hn=nr("[SegmentIntegration]");function Nn(e,t,i){void 0===i&&(i=!0);var s=e.config.segment;if(!s)return t();!function(e,t,i){var s=e.config.segment;if(!s)return t();var r=s=>{var r=()=>s.anonymousId()||Cr();e.config.get_device_id=r,i&&s.id()&&(e.register({distinct_id:s.id(),$device_id:r()}),e.persistence.set_property(ee,ve)),t(i?void 0:s.anonymousId()||void 0)},n=s.user();"then"in n&&Ye(n.then)?n.then(r):r(n)}(e,(i=>{s.register(((e,t)=>{"undefined"!=typeof Promise&&Promise.resolve||Hn.warn("This browser does not have Promise support, and can not use the segment integration");var i=(i,s)=>{if(!s)return i;var r=!!t&&i.event.anonymousId===t&&!i.event.userId;r||i.event.userId||i.event.anonymousId===e.get_distinct_id()||(Hn.info("No userId set, resetting PostHog"),e.reset()),r||(t=void 0),i.event.userId&&i.event.userId!==e.get_distinct_id()&&(Hn.info("UserId set, identifying with PostHog"),e.identify(i.event.userId));var n=e.calculateEventProperties(s,i.event.properties);return i.event.properties=Object.assign({},n,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(e){return i(e,e.event.event)},page(e){return i(e,be)},identify(e){return i(e,we)},screen(e){return i(e,"$screen")}}})(e,i)).then((()=>{t()}),(e=>{Hn.error("Failed to register the Segment integration",e),t()}))}),i)}var zn="posthog-js";function jn(e,t){var s=void 0===t?{}:t,r=s.organization,n=s.projectId,o=s.prefix,a=s.severityAllowList,l=void 0===a?["error"]:a,u=s.sendExceptionsToPostHog,c=void 0===u||u;return t=>{var s,a,u,d,h;if("*"!==l&&!l.includes(t.level)||!e.__loaded)return t;t.tags||(t.tags={});var _=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());t.tags["PostHog Person URL"]=_,e.sessionRecordingStarted()&&(t.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p,g=(null==(s=t.exception)?void 0:s.values)||[],v=g.map((e=>i({},e,{stacktrace:e.stacktrace?i({},e.stacktrace,{type:"raw",frames:(e.stacktrace.frames||[]).map((e=>i({},e,{platform:"web:javascript"})))}):void 0}))),f={$exception_message:(null==(a=g[0])?void 0:a.value)||t.message,$exception_type:null==(u=g[0])?void 0:u.type,$exception_level:t.level,$exception_list:v,$sentry_event_id:t.event_id,$sentry_exception:t.exception,$sentry_exception_message:(null==(d=g[0])?void 0:d.value)||t.message,$sentry_exception_type:null==(h=g[0])?void 0:h.type,$sentry_tags:t.tags};return r&&n&&(f.$sentry_url=(o||"https://sentry.io/organizations/")+r+"/issues/?project="+n+"&query="+t.event_id),c&&(null==(p=e.exceptions)||p.sendExceptionEvent(f)),t}}class Vn{constructor(e,t,i,s,r,n){this.name=zn,this.setupOnce=function(o){o(jn(e,{organization:t,projectId:i,prefix:s,severityAllowList:r,sendExceptionsToPostHog:null==n||n}))}}}class Un{constructor(e){this._onSessionIdChange=(e,t,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(rr.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.onSessionId(this._onSessionIdChange)}destroy(){var e;null==(e=this._unsubscribeSessionId)||e.call(this),this._unsubscribeSessionId=void 0}doPageView(e,t){var i,s=this._previousPageViewProperties(e,t);return this._currentPageview={pathname:null!==(i=null==ke?void 0:ke.location.pathname)&&void 0!==i?i:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var t;return this._previousPageViewProperties(e,null==(t=this._currentPageview)?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:null==(e=this._currentPageview)?void 0:e.pageViewId}}_previousPageViewProperties(e,t){var i=this._currentPageview;if(!i)return{$pageview_id:t};var s={$pageview_id:t,$prev_pageview_id:i.pageViewId},r=this._instance.scrollManager.getContext();if(r&&!this._instance.config.disable_scroll_properties){var n=r.maxScrollHeight,o=r.lastScrollY,a=r.maxScrollY,l=r.maxContentHeight,u=r.lastContentY,c=r.maxContentY;if(!(et(n)||et(o)||et(a)||et(l)||et(u)||et(c))){n=Math.ceil(n),o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c);var d=n>1?yt(o/n,0,1,rr):1,h=n>1?yt(a/n,0,1,rr):1,_=l>1?yt(u/l,0,1,rr):1,p=l>1?yt(c/l,0,1,rr):1;s=lr(s,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:d,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:h,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:_,$prev_pageview_max_content:c,$prev_pageview_max_content_percentage:p})}}return i.pathname&&(s.$prev_pageview_pathname=i.pathname),i.timestamp&&(s.$prev_pageview_duration=(e.getTime()-i.timestamp.getTime())/1e3),s}}var Wn=["flags","surveys"],Gn={[n]:{exposure:"hidden"},[u]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[h]:{exposure:"hidden"},[d]:{exposure:"hidden"},[_]:{exposure:"event"},[p]:{exposure:"hidden"},[S]:{exposure:"hidden"},[g]:{exposure:"event"},[v]:{exposure:"hidden"},[f]:{exposure:"event"},[m]:{exposure:"event"},[y]:{exposure:"event"},[b]:{exposure:"hidden"},[w]:{exposure:"event"},[C]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[I]:{exposure:"hidden"},[T]:{exposure:"event"},[k]:{exposure:"event",shouldSkipFromEventProperties:e=>st(e)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[R]:{exposure:"hidden",storageGroup:"flags"},[A]:{exposure:"hidden",storageGroup:"flags"},[L]:{exposure:"hidden"},[M]:{exposure:"hidden",storageGroup:"flags"},[O]:{exposure:"hidden",storageGroup:"flags"},[D]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[B]:{exposure:"hidden",storageGroup:"flags"},[q]:{exposure:"hidden"},[H]:{exposure:"hidden"},[N]:{exposure:"hidden"},[z]:{exposure:"hidden"},[V]:{exposure:"hidden",storageGroup:"surveys"},[U]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[W]:{exposure:"event"},[G]:{exposure:"hidden"},[K]:{exposure:"hidden"},[Q]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[J]:{exposure:"hidden"},[Y]:{exposure:"hidden"},[j]:{exposure:"event"},[Z]:{exposure:"hidden"},[X]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[ee]:{exposure:"hidden"},[te]:{exposure:"hidden"},[ie]:{exposure:"hidden"},[se]:{exposure:"hidden"},[re]:{exposure:"hidden"},[ne]:{exposure:"hidden"},[oe]:{exposure:"hidden"},[E]:{exposure:"event"},[x]:{exposure:"event"},[P]:{exposure:"event"},[F]:{exposure:"event"},[ue]:{exposure:"event"},[ce]:{exposure:"event"},[de]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_pending_trigger_conditions:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},Kn=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Qn=e=>{var t=Gn[e];if(t)return t;for(var i of Kn){var s=i[1];if(0===e.indexOf(i[0]))return s}},Jn=(e,t)=>{try{return JSON.stringify(e,((e,t)=>"bigint"==typeof t?t.toString():t),t)}catch(t){return ze(e)}},Yn=e=>{var t=null==Pe?void 0:Pe.createElement("a");return et(t)?null:(t.href=e,t)},Zn=function(e,t){for(var i,s=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),r=0;s.length>r;r++){var n=s[r].split("=");if(n[0]===t){i=n;break}}if(!Je(i)||2>i.length)return"";var o=i[1];try{o=decodeURIComponent(o)}catch(e){rr.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Xn=function(e,t,i){if(!e||!t||!t.length)return e;for(var s=e.split("#"),r=s[1],n=(s[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");Je(d)&&(t.includes(d[0])?u.push(d[0]+"="+i):u.push(l[c]))}var h=a;return null!=o&&(h+="?"+u.join("&")),null!=r&&(h+="#"+r),h},eo=function(e,t){var i=e.match(new RegExp(t+"=([^&]*)"));return i?i[1]:null},to=(e,t)=>e>=t&&Me(),io=(e,t,i,s)=>{if(0===e){if(Me()){var r=t+1;return r===i&&s(),r}return t}return 0},so="https?://(.*)",ro=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],no=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...ro],oo="",ao=["li_fat_id"];function lo(e,t,i){if(!Pe)return{};var s,r=t?[...ro,...i||[]]:[],n=uo(Xn(Pe.URL,r,oo),e),o=(s={},ar(ao,(function(e){var t=fr(e);s[e]=t||null})),s);return lr(o,n)}function uo(e,t){var i=no.concat(t||[]),s={};return ar(i,(function(t){var i=Zn(e,t);s[t]=i||null})),s}function co(e){var t=function(e){return e?0===e.search(so+"google.([^/?]*)")?"google":0===e.search(so+"bing.com")?"bing":0===e.search(so+"yahoo.com")?"yahoo":0===e.search(so+"duckduckgo.com")?"duckduckgo":null:null}(e),i="yahoo"!=t?"q":"p",s={};if(!st(t)){s.$search_engine=t;var r=Pe?Zn(Pe.referrer,i):"";r.length&&(s.ph_keyword=r)}return s}function ho(){return navigator.language||navigator.userLanguage}var _o="$direct";function po(){return(null==Pe?void 0:Pe.referrer)||_o}function go(e,t,i){void 0===i&&(i=!1);var s=e?[...ro,...t||[]]:[],r=i?Vi(null==Fe?void 0:Fe.href):null==Fe?void 0:Fe.href,n=null==r?void 0:r.substring(0,1e3);return{r:po().substring(0,1e3),u:n?Xn(n,s,oo):void 0}}function vo(e,t){var i;void 0===t&&(t=!1);var s=e.r,r=e.u,n=t?Vi(r):r,o={$referrer:s,$referring_domain:null==s?void 0:s==_o?_o:null==(i=Yn(s))?void 0:i.host};if(n){o.$current_url=n;var a=Yn(n);o.$host=null==a?void 0:a.host,o.$pathname=null==a?void 0:a.pathname;var l=uo(n);lr(o,l)}if(s){var u=co(s);lr(o,u)}return o}function fo(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(e){return}}function mo(){try{return(new Date).getTimezoneOffset()}catch(e){return}}var yo={flags:X,surveys:U},bo=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],So=e=>e+"_cookie_identity_change_pending",wo=e=>{var t="",i=0;for(var s of e){var r=encodeURIComponent(JSON.stringify(s).slice(1,-1)).length;if(i+r>1e3)break;t+=s,i+=r}return t},Co="main",ko=[R,A,M,O,D,X,B,N],Eo=e=>-1!==ko.indexOf(e),xo=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch(i){return e===t}},Po=e=>{if(!e)return{};var t=JSON.parse(e);return Ze(t)?t:{}},Fo=(e,t)=>{ar(e,((i,s)=>{var r=Qn(s);r&&"event"!==r.exposure||{}.hasOwnProperty.call(t,s)||delete e[s]}))};class Io{constructor(e,t,s){if(void 0===s&&(s=!0),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._facebookClickIdChangePending=!1,this._crossTabFeatureFlagHandlers=new Set,this._config=e,this._ownsSplitStorage=s,this.props={},this._campaign_params_url=void 0,this._name=(e=>{var 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._storage=this._buildStorage(e),this._splitStorage=this._resolveSplitStorage(e),this.load(),this._markLoadedCrossTabFeatureFlagChangesPending(),e.debug&&rr.info("Persistence loaded",e.persistence,i({},this.props)),this.update_config(e,e,t),this.save(),ke){var r=()=>this.flush();gr(ke,"beforeunload",r,{capture:!1}),gr(ke,"pagehide",r,{capture:!1}),this._onStorage=e=>{if(this._splitStorageEligible&&(!e.storageArea||e.storageArea===(null==ke?void 0:ke.localStorage))&&e.key)if(e.key!==this._name){if(this._splitStorage){var t=Wn.find((t=>e.key===this._groupEntryName(t)));t&&this._syncCrossTabFeatureFlagProperties(e.key,t)}}else this._syncCrossTabFeatureFlagProperties(e.key,Co)},gr(ke,"storage",this._onStorage)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach((e=>{var t=e[0],i=e[1],s=this._pendingCrossTabFeatureFlagChanges.get(t);if(Eo(t)&&!0!==s)if(!0!==i){var r=new Set(s||[]);i.forEach((e=>r.add(e))),r.size&&this._setCrossTabFeatureFlagChangesPending(t,r)}else this._setCrossTabFeatureFlagChangesPending(t,!0)}))}onCrossTabFeatureFlagChange(e){return this._crossTabFeatureFlagHandlers.add(e),()=>this._crossTabFeatureFlagHandlers.delete(e)}destroy(){this._onStorage&&ke&&(ke.removeEventListener("storage",this._onStorage),this._onStorage=void 0),this._crossTabFeatureFlagHandlers.clear()}_syncCrossTabFeatureFlagProperties(e,t,i){if(void 0===i&&(i=!0),this._disabled)return!1;var s,r;try{if(r=Tr._get(e),st(r)){var n=this._slotWriteState(t);return n.storageValue=null,t!==Co&&(n.persisted=!1),!1}s=Po(r)}catch(e){return!1}var o=t===Co?s:Tr._parse(this._name);if(o&&this._hasCrossTabFeatureFlagIdentityMismatch(o))return!1;var a=this._mergeCrossTabFeatureFlagProperties(s,t,i);return t===Co&&this._splitStorage&&!xo(this._partitionProps().main,s)||this._rememberCrossTabStorageFingerprint(s,t,!0,r),a}_hasCrossTabFeatureFlagIdentityMismatch(e){var t=this.props[o],i=e[o];return!et(t)&&!et(i)&&t!==i}_rememberCrossTabStorageFingerprint(e,t,i,s){var r=this._slotWriteState(t);r.storageValue=s,t!==Co&&(r.persisted=i);try{r.fingerprint=this._entryFingerprint(e,t)}catch(e){r.fingerprint=void 0}}_mergeCrossTabFeatureFlagProperties(e,t,i){var s=!1;return ko.forEach((i=>{var r,n=null==(r=Qn(i))?void 0:r.storageGroup;if(!(t===Co&&this._splitStorage&&n||t!==Co&&n!==t)){var 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&&xo(a,this.props[i])||(l?this._setProp(i,a,!1):this._deleteProp(i,!1),s=!0)}})),s&&i&&this._crossTabFeatureFlagHandlers.forEach((e=>e())),s}_reconcileCrossTabFeatureFlagPropertiesBeforeWrite(){if(!this._splitStorageEligible)return!1;try{this._crossTabFeatureFlagIdentityMismatch=!1;var e,t=Tr._get(this._name),i=this._slotWriteState(Co),s=!1,r=!1;if(t!==i.storageValue)if(st(t))i.storageValue=null;else{if(e=Po(t),this._crossTabFeatureFlagIdentityMismatch=!this._localIdentityChangePending&&this._hasCrossTabFeatureFlagIdentityMismatch(e),this._crossTabFeatureFlagIdentityMismatch)return!1;r=this._mergeCrossTabFeatureFlagProperties(e,Co,!1),!this._splitStorage||xo(this._partitionProps().main,e)?this._rememberCrossTabStorageFingerprint(e,Co,!0,t):i.storageValue=t,s=!0}return this._splitStorage&&Wn.forEach((t=>{var i=Tr._get(this._groupEntryName(t)),n=this._slotWriteState(t),o=e||{},a=s&&ko.some((e=>{var i;return(null==(i=Qn(e))?void 0:i.storageGroup)===t&&e in o}));if(i!==n.storageValue||a){if(st(i))return n.storageValue=null,n.persisted=!1,void(a&&(r=this._mergeCrossTabFeatureFlagProperties(o,t,!1)||r));var l=Po(i);r=this._mergeCrossTabFeatureFlagProperties(l,t,!1)||r,this._rememberCrossTabStorageFingerprint(l,t,!0,i)}})),r}catch(e){return!1}}_setCrossTabFeatureFlagChangesPending(e,t){this._pendingCrossTabFeatureFlagChanges.set(e,t);var i=Qn(e);null!=i&&i.volatile||(this._slotWriteState((this._splitStorage?null==i?void 0:i.storageGroup:void 0)||Co).fingerprint=void 0,this._markGroupDirty(e))}_markAllCrossTabFeatureFlagChangesPending(){ko.forEach((e=>this._pendingCrossTabFeatureFlagChanges.set(e,!0)))}_markLoadedCrossTabFeatureFlagChangesPending(){if(this._splitStorageEligible)try{var e=Tr._get(this._name),t=Po(e);this._slotWriteState(Co).storageValue=e,ko.forEach((e=>{var i,s=this._splitStorage?null==(i=Qn(e))?void 0:i.storageGroup:void 0,r=s?Tr._get(this._groupEntryName(s)):null;if(s){var n=this._slotWriteState(s);n.storageValue=r,n.persisted=!st(r)}var o=s&&!st(r)?Po(r):t;e in this.props?this._markPendingCrossTabFeatureFlagChanges(e,o[e],this.props[e]):e in o&&this._setCrossTabFeatureFlagChangesPending(e,!0)}))}catch(e){}}_mergePendingCrossTabFeatureFlagChanges(e,t){var s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!s)return t;if(!0===s)return this.props[e];if(e===A){var r=new Set(Je(t)?t:[]),n=new Set(Je(this.props[e])?this.props[e]:[]);return s.forEach((e=>n.has(e)?r.add(e):r.delete(e))),Array.from(r)}var o=Ze(t)?i({},t):{},a=Ze(this.props[e])?this.props[e]:{};return s.forEach((e=>{e in a?o[e]=a[e]:delete o[e]})),o}_markPendingCrossTabFeatureFlagChanges(e,t,i){if(Eo(e)){var s=this._pendingCrossTabFeatureFlagChanges.get(e);if(!0!==s){var r=t;if(this._splitStorageEligible)try{var n,o=this._splitStorage?null==(n=Qn(e))?void 0:n.storageGroup:void 0,a=o?this._groupEntryName(o):this._name;r=Po(Tr._get(a))[e]}catch(e){}var l=new Set(s||[]);if(e===A){if(!et(t)&&!Je(t)||!et(r)&&!Je(r)||!Je(i))return void this._setCrossTabFeatureFlagChangesPending(e,!0);var u=new Set(t||[]),c=new Set(r||[]),d=new Set(i);new Set([...u,...d]).forEach((e=>{u.has(e)!==d.has(e)&&l.add(e)})),l.forEach((e=>{c.has(e)===d.has(e)&&l.delete(e)}))}else{if(!Ze(i))return void(xo(r,i)?this._pendingCrossTabFeatureFlagChanges.delete(e):this._setCrossTabFeatureFlagChangesPending(e,!0));if(!et(t)&&!Ze(t)||et(t)&&Xe(i)&&et(r))return void this._setCrossTabFeatureFlagChangesPending(e,!0);var h=Ze(t)?t:{},_=Ze(r)?r:{};new Set([...Object.keys(h),...Object.keys(i)]).forEach((e=>{e in h==e in i&&xo(h[e],i[e])||l.add(e)})),l.forEach((e=>{e in _==e in i&&xo(_[e],i[e])&&l.delete(e)}))}l.size?this._setCrossTabFeatureFlagChangesPending(e,l):this._pendingCrossTabFeatureFlagChanges.delete(e)}}}_saveDebounceMs(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return nt(t)&&t>0?t:0}_rememberCurrentCookieProperties(e){if(this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase())if(e)try{var t=Or(e,this._config.cookie_persisted_properties||[]),i=Br(t,this._config.cookie_persisted_properties||[]),s=JSON.stringify(t)+"|"+JSON.stringify(i),r=Fr._get(this._name)||void 0;r&&Hr(this._name,r)===s&&(this._lastSeenCookiePropertiesFingerprint=s,this._lastSeenMainCookieValue=r)}catch(e){}else try{var n=Fr._get(this._name)||void 0;this._lastSeenCookiePropertiesFingerprint=n?Hr(this._name,n):void 0,this._lastSeenMainCookieValue=n}catch(e){}}syncCookieProperties(){return this._syncCookieProperties(this._config)}_syncCookieProperties(e,t){if(void 0===t&&(t=!1),this._disabled&&!t||this._cookieSyncSuppressed||!e.cookieWinsOnConflict||"localstorage+cookie"!==e.persistence.toLowerCase())return!1;var i;try{i=Fr._get(this._name)||void 0}catch(e){}if(!i||i===this._lastSeenMainCookieValue)return!1;var s,r=Hr(this._name,i);try{s=$r(JSON.parse(i))}catch(e){return!1}if((Fr._get(this._name)||void 0)!==i)return!1;this._lastSeenCookiePropertiesFingerprint=r,this._lastSeenMainCookieValue=i;var n=qr(this._name,i),a=[...Ar,...n.properties],l={};if(Object.keys(s).forEach((e=>{var t=s[e];(et(t)||st(t)||""===t||e===ee&&t!==ge&&t!==ve)&&(l[e]=!0,delete s[e])})),Xe(s))return!1;var c=o in s||s[ee]===ge||s[ee]===ve,d=this.props,h=d[o],_=d[ee],p=lr({},d);[...Ar,...e.cookie_persisted_properties||[]].forEach((e=>{if(-1!==a.indexOf(e)&&!(e in s)&&!l[e]&&(c||e!==o&&e!==ee)){var t=p[e];!n.isValid&&-1!==Ar.indexOf(e)&&(!1===t||0===t)||delete p[e]}})),this.props=lr(p,s),ko.forEach((e=>{var t=e in this.props;e in d===t&&xo(d[e],this.props[e])||(t?this._markPendingCrossTabFeatureFlagChanges(e,d[e],this.props[e]):this._setCrossTabFeatureFlagChangesPending(e,!0))})),!c||ee in s||ee in this.props||this._setProp(ee,ge);var g=this.props[o],v=this.props[ee];return!c||g===h&&v===_||(this._localIdentityChangePending=!0,this._cookieIdentityChangePending=!0,Vr._set(So(this._name),!0),this._deleteProp(N),this._deleteProp(A),this._deleteProp(R),this._deleteProp(M),this._deleteProp(O),this._deleteProp(D),this._deleteProp(X),this._deleteProp(Z),this._deleteProp(J),v===ge&&(_===ve||s[ee]===ge||!et(h)&&g!==h)&&(Fo(this.props,s),this._deleteProp(z)),v===ve?this.props.$user_id=g:delete this.props.$user_id,this._deleteProp(u)),!0}consumeCookieIdentityChange(){var e=So(this._name),t=this._cookieIdentityChangePending||!!Vr._get(e);return this._cookieIdentityChangePending=!1,t&&Vr._remove(e),t}_beginCookieSyncSuppression(e){return void 0===e&&(e=!1),!(this._cookieSyncSuppressed||this._disabled&&!e||!this._config.cookieWinsOnConflict||"localstorage+cookie"!==this._config.persistence.toLowerCase()||(this._cookieSyncSuppressed=!0,0))}_publishSuppressedCookieSnapshot(){this._cookieSyncSuppressed&&(et(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),delete this._slotState[Co],this._writeNow(!0))}_endCookieSyncSuppression(e){if(void 0===e&&(e=!0),this._cookieSyncSuppressed)try{e?this._publishSuppressedCookieSnapshot():et(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0)}finally{this._cookieSyncSuppressed=!1}}isDisabled(){return!!this._disabled}_buildStorage(e){-1===bo.indexOf(e.persistence.toLowerCase())&&(rr.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t,s=function(e,t){void 0===e&&(e=[]),void 0===t&&(t=!1);var s=[...Ar,...e];return i({},Tr,{_parse(e){try{var i,r={};try{i=Fr._get(e)||void 0,r=i?$r(JSON.parse(i)):{}}catch(e){}var n,a=JSON.parse(Tr._get(e)||"{}");if(t){var l=qr(e,i),u=[...Ar,...l.properties],c={};Object.keys(r).forEach((e=>{var t=r[e];st(t)||""===t||e===ee&&t!==ge&&t!==ve||(c[e]=t)}));var d=o in c||c[ee]===ge||c[ee]===ve;if(Object.keys(c).length>0){var h,_=a[o],p=null!==(h=a[ee])&&void 0!==h?h:ge;s.forEach((e=>{if(-1!==u.indexOf(e)&&!(e in r)&&(d||e!==o&&e!==ee)){var t=a[e];!l.isValid&&-1!==Ar.indexOf(e)&&(!1===t||0===t)||delete a[e]}})),!d||ee in r||ee in a||(a[ee]=ge),!d||(o in c?c[o]:a[o])===_&&(ee in c?c[ee]:a[ee])===p||(Rr.forEach((e=>delete a[e])),c[ee]===ve&&o in c?a.$user_id=c[o]:delete a.$user_id,c[ee]!==ve&&(delete a[j],delete a[z]),delete a.__alias)}n=lr(a,c)}else n=lr(r,a);return Tr._set(e,n),n}catch(e){}return null},_set(i,s,r,n,o,a){var l=Tr._set(i,s,void 0,void 0,a);try{var u=Or(s,e);if(Object.keys(u).length){if(t){var c=Lr(i),d=Br(u,e);if(Fr._set(c,d,r,n,o,a),Fr._get(c)!==JSON.stringify(d)){Fr._remove(c,n);var h=Or(s);return Fr._set(i,h,r,n,o,a),l}}Fr._set(i,u,r,n,o,a)}}catch(e){Tr._error(e)}return l},_remove(e,t){try{null==ke||ke.localStorage.removeItem(e),Fr._remove(e,t),Fr._remove(Lr(e),t)}catch(e){Tr._error(e)}}})}(e.cookie_persisted_properties||[],e.cookieWinsOnConflict),r=!1,n=!1,a=e.persistence.toLowerCase();return"localstorage"===a&&Tr._is_supported()?(t=Tr,n=!0):"localstorage+cookie"===a&&s._is_supported()?(t=s,n=!0,r=!0):"sessionstorage"===a&&Vr._is_supported()?t=Vr:"memory"===a?t=zr:"cookie"===a&&Fr._is_supported()?(t=Fr,r=!0):s._is_supported()?(t=s,n=!0,r=!0):Fr._is_supported()?(t=Fr,r=!0):t=zr,this._splitStorageEligible=n,this._storesIdentityInCookie=r,t}_groupEntryName(e){return this._name+"__"+e}_resolveSplitStorage(e){return this._splitStorageEligible&&!!e.split_storage}properties(){var e={};return ar(this.props,((t,i)=>{var s=Qn(i);if(!s||"event"===s.exposure){if(null!=s&&null!=s.shouldSkipFromEventProperties&&s.shouldSkipFromEventProperties(t))return;e[i]=t}})),e}load(e){if(void 0===e&&(e=!1),!this._disabled||e){var t=this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase(),i=t?Tr._parse(this._name):null,s={};if(t)try{ar(s=$r(Fr._parse(this._name)),((e,t)=>{(et(e)||st(e)||""===e)&&delete s[t]}))}catch(e){}var r=this._storage._parse(this._name);if(r&&(this.props=lr({},r)),this._splitStorage&&this._loadGroupEntries(),t&&r){var n,a,l=null==i?void 0:i[o],u=null!==(n=null==i?void 0:i[ee])&&void 0!==n?n:ge,c=r[o],d=null!==(a=r[ee])&&void 0!==a?a:ge;if(c!==l||d!==u){this._cookieIdentityChangePending=!0,Vr._set(So(this._name),!0);var h=lr({},this.props);Rr.forEach((e=>delete h[e])),d===ge&&(u===ve||s[ee]===ge||!et(l)&&c!==l)&&(Fo(h,s),delete h[z]),this.props=h;var _=new Set;Rr.forEach((e=>{var t,i=null==(t=Qn(e))?void 0:t.storageGroup;i&&_.add(i)})),_.forEach((e=>{var t={};ar(this.props,((i,s)=>{var r;(null==(r=Qn(s))?void 0:r.storageGroup)===e&&(t[s]=i)})),Xe(t)?(Tr._remove(this._groupEntryName(e)),this._slotState[e]={}):Tr._set(this._groupEntryName(e),t)&&(this._slotState[e]={persisted:!0,fingerprint:this._entryFingerprint(t,e)})}))}}Vr._get(So(this._name))&&(this._cookieIdentityChangePending=!0)}}_loadGroupEntries(){for(var e of Wn){var t=Tr._parse(this._groupEntryName(e));if(t&&!Xe(t)){var i=this._slotWriteState(e);i.persisted=!0,this._mainCarriesGroupKey(e)||(i.fingerprint=this._entryFingerprint(t,e)),this._groupEntryIsStale(e,t)||lr(this.props,t)}}}_mainCarriesGroupKey(e){return Object.keys(this.props).some((t=>{var i;return(null==(i=Qn(t))?void 0:i.storageGroup)===e}))}_groupEntryIsStale(e,t){var i=yo[e];if(!i)return!1;var s=t[i],r=this.props[i];return nt(s)&&nt(r)&&r>s}refreshKey(e){var t;if(!(this._disabled||e===d&&this._facebookClickIdChangePending)){var i=this._splitStorage?null==(t=Qn(e))?void 0:t.storageGroup:void 0,s=i?Tr._parse(this._groupEntryName(i)):this._storage._parse(this._name);if(s&&e in s)this._setProp(e,s[e],!1);else{if(i){var r=this._storage._parse(this._name);if(r&&e in r)return void this._setProp(e,r[e],!1)}this._deleteProp(e,!1)}}}save(){if(!this._disabled){var e=this._saveDebounceMs();e>0?et(this._pendingSaveTimer)&&(this._pendingSaveTimer=setTimeout((()=>{this._pendingSaveTimer=void 0,this._writeNow()}),e)):this._writeNow()}}flush(){et(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0,this._writeNow())}_writeNow(e){if(void 0===e&&(e=!1),!(this._disabled||this._cookieSyncSuppressed&&!e)){e||(this.syncCookieProperties(),this._facebookClickIdChangePending||this._config.cookieWinsOnConflict&&"localstorage+cookie"===this._config.persistence.toLowerCase()||this.refreshKey(d));var t=!e&&!this._storageMigrationInProgress;t||(this._crossTabFeatureFlagIdentityMismatch=!1);var i=!!t&&this._reconcileCrossTabFeatureFlagPropertiesBeforeWrite();if(this._crossTabFeatureFlagIdentityMismatch)this._config.debug&&rr.warn("skipping persistence write because storage belongs to a different distinct ID");else{if(this._splitStorage)return this._writeNowSplit(),void(i&&this._crossTabFeatureFlagHandlers.forEach((e=>e())));var s=this._writeEntry(this._storage,this._name,this.props,Co);"written"===s&&this._rememberCurrentCookieProperties(this.props),"failed"!==s&&(this._pendingCrossTabFeatureFlagChanges.clear(),this._localIdentityChangePending=!1,this._facebookClickIdChangePending=!1),i&&this._crossTabFeatureFlagHandlers.forEach((e=>e()))}}}_writeNowSplit(){var e=this,t=this._partitionProps(),i=t.main,s=t.groups,r=this._writeEntry(this._storage,this._name,i,Co);"written"===r&&this._rememberCurrentCookieProperties(i),"failed"!==r&&(this._localIdentityChangePending=!1,this._facebookClickIdChangePending=!1,ko.forEach((e=>{var t;null!=(t=Qn(e))&&t.storageGroup||this._pendingCrossTabFeatureFlagChanges.delete(e)})));var n=function(t){var i,r=s[t];if(Xe(r)&&(null==(i=e._slotState[t])||!i.persisted))return ko.forEach((i=>{var s;(null==(s=Qn(i))?void 0:s.storageGroup)===t&&e._pendingCrossTabFeatureFlagChanges.delete(i)})),1;var n=e._writeEntry(Tr,e._groupEntryName(t),r,t);"failed"!==n&&ko.forEach((i=>{var s=Qn(i);(null==s?void 0:s.storageGroup)!==t||"written"!==n&&s.volatile||e._pendingCrossTabFeatureFlagChanges.delete(i)}))};for(var o of Wn)n(o)}_partitionProps(){var e={},t={flags:{},surveys:{}};return ar(this.props,((i,s)=>{var r,n=null==(r=Qn(s))?void 0:r.storageGroup;n?t[n][s]=i:e[s]=i})),{main:e,groups:t}}_entryFingerprint(e,t){if(t===Co)return JSON.stringify(e)+"|"+this._expire_days+"|"+this._cross_subdomain+"|"+this._secure;var i={};return ar(e,((e,t)=>{var s;i[t]=null!=(s=Qn(t))&&s.volatile?"__volatile__":e})),JSON.stringify(i)}_writeEntry(e,t,i,s){var r,n=this._slotWriteState(s);if(s!==Co&&!n.dirty&&!et(n.fingerprint))return"skipped";try{if((r=this._entryFingerprint(i,s))===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!==Co&&(n.persisted=!0),et(r)||(n.fingerprint=r),this._splitStorageEligible&&(n.storageValue=Tr._get(t)),"written"):(this._config.debug&&rr.warn('failed to persist storage entry "'+t+'"; will retry on next save'),"failed")}remove(e){var t=(void 0===e?{}:e).keepGroupEntries,i=void 0!==t&&t;if(this._markAllCrossTabFeatureFlagChangesPending(),et(this._pendingSaveTimer)||(clearTimeout(this._pendingSaveTimer),this._pendingSaveTimer=void 0),this._storage._remove(this._name,!1),this._storage._remove(this._name,!0),!i&&this._ownsSplitStorage)for(var s of Wn)Tr._remove(this._groupEntryName(s));i?delete this._slotState[Co]:this._slotState={},this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0}clear(){this.remove(),this.props={}}register_once(e,t,i){if(Ze(e)){this.syncCookieProperties(),et(t)&&(t="None"),this._expire_days=et(i)?this._default_expiry:i;var s=!1;if(ar(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(Ze(e)){this.syncCookieProperties(),this._expire_days=et(t)?this._default_expiry:t;var i=!1;if(ar(e,((t,s)=>{e.hasOwnProperty(s)&&(this.props[s]!==t||Ze(t)||Je(t))&&(this._setProp(s,t),i=!0)})),i)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();var t="string"==typeof e?[e]:e,i=!1;for(var s of t)s in this.props&&(this._deleteProp(s),i=!0);i&&this.save()}update_campaign_params(){var e=null==Pe?void 0:Pe.URL;if(e!==this._campaign_params_url){var t=lo(this._config.custom_campaign_params,this._config.mask_personal_data_properties,this._config.custom_personal_data_properties),i=!Xe(hr(t));return i&&this.register(t),this._campaign_params_url=e,i?t:void 0}}update_search_keyword(){var e;this.register((e=null==Pe?void 0:Pe.referrer)?co(e):{})}update_referrer_info(){var e;this.register_once({$referrer:po(),$referring_domain:null!=Pe&&Pe.referrer&&(null==(e=Yn(Pe.referrer))?void 0:e.host)||_o},void 0)}set_initial_person_info(){if(!this.props[se]&&!this.props[re]){var e=go(this._config.mask_personal_data_properties,this._config.custom_personal_data_properties,this._config.disable_capture_url_hashes);this.register_once({[ne]:this._storesIdentityInCookie?{r:wo(e.r),u:e.u?wo(e.u):void 0}:e},void 0)}}get_initial_props(){var e={};ar([re,se],(t=>{var i=this.props[t];i&&ar(i,(function(t,i){e["$initial_"+Ne(i)]=t}))}));var t=this.props[ne];if(t){var i=function(e,t){void 0===t&&(t=!1);var i=vo(e,t),s={};return ar(i,(function(e,t){s["$initial_"+Ne(t)]=e})),s}(t,this._config.disable_capture_url_hashes);lr(e,i)}return e}safe_merge(e){return ar(this.props,(function(t,i){i in e||(e[i]=t)})),e}update_config(e,t,s){var r=e.persistence!==t.persistence,n=!((e,t)=>{if(e.length!==t.length)return!1;var i=[...e].sort(),s=[...t].sort();return i.every(((e,t)=>e===s[t]))})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),o=r||n,a=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,l=e.disable_persistence||!!s,u=!!this._disabled&&!l;l||this._syncCookieProperties(t,u),this._config=e,!l&&(r||n||a)&&(this._lastSeenCookiePropertiesFingerprint=void 0,this._lastSeenMainCookieValue=void 0,this._syncCookieProperties(i({},e,{cookie_persisted_properties:t.cookie_persisted_properties}),u));var c=o||a?this._buildStorage(e):this._storage;this._truncateExistingPersonInfoForCookie();var d=this._resolveSplitStorage(e),h=o||d!==this._splitStorage,_=!l&&(h||e.cross_subdomain_cookie!==this._cross_subdomain||e.secure_cookie!==this._secure)&&this._beginCookieSyncSuppression(u);this._storageMigrationInProgress=h;try{if(this._default_expiry=this._expire_days=e.cookie_expiration,this.set_disabled(l),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){var p=this.props;this.clear(),this._storage=c,this._splitStorage=d,this.props=p,this.save()}else a&&(this._storage=c,l||(delete this._slotState[Co],this._writeNow()))}finally{this._storageMigrationInProgress=!1,_&&this._endCookieSyncSuppression()}}_truncateExistingPersonInfoForCookie(){var e=this.props[ne];if(this._storesIdentityInCookie&&Ze(e)&&"string"==typeof e.r){var t=wo(e.r),s="string"==typeof e.u?wo(e.u):e.u;t===e.r&&s===e.u||this._setProp(ne,i({},e,{r:t,u:s}))}}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){var i=this.props[h]||{};i[e]=t,this._setProp(h,i),this.save()}remove_event_timer(e){var t=this.props[h]||{},i=t[e];return et(i)||(delete t[e],this._setProp(h,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){var s;void 0===i&&(i=!0);var r=this.props[e];this.props[e]=t,i&&(e!==o&&e!==ee||r===t||(this._localIdentityChangePending=!0),e!==d||xo(r,t)||(this._facebookClickIdChangePending=!0),this._markPendingCrossTabFeatureFlagChanges(e,r,t),null!=(s=Qn(e))&&s.volatile||this._markGroupDirty(e))}_deleteProp(e,t){void 0===t&&(t=!0),delete this.props[e],t&&(Eo(e)&&this._setCrossTabFeatureFlagChangesPending(e,!0),e===d&&(this._facebookClickIdChangePending=!0),this._markGroupDirty(e))}_markGroupDirty(e){var t,i=null==(t=Qn(e))?void 0:t.storageGroup;i&&(this._slotWriteState(i).dirty=!0)}_slotWriteState(e){return this._slotState[e]||(this._slotState[e]={})}}var To="gzip-js",Ro="base64",Ao="events",Lo="cancelEvents",Mo="survey shown",$o="survey dismissed",Oo="survey sent",Do="popover";function Bo(e){var t=!0;return{dispose(){if(t){t=!1;var i=e();i&&Ye(i.then)&&i.then(void 0,(()=>{}))}}}}var qo=nr("[RateLimiter]");class Ho{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=e=>{var t=e.text;if(t&&t.length)try{(JSON.parse(t).quota_limited||[]).forEach((e=>{qo.info((e||"events")+" is quota limited."),this.serverLimits[e]=(new Date).getTime()+6e4}))}catch(e){return void qo.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.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max((null==(e=this.instance.config.rate_limiting)?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var t,i,s;void 0===e&&(e=!1);var r=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=(new Date).getTime(),a=null!==(t=null==(i=this.instance.persistence)?void 0:i.get_property(ie))&&void 0!==t?t:{tokens:r,last:o};a.tokens+=(o-a.last)/1e3*n,a.last=o,a.tokens>r&&(a.tokens=r);var l=1>a.tokens;if(l||e||(a.tokens=Math.max(0,a.tokens-1)),l&&!e){var u=(nt(a.dropped)?a.dropped:0)+1;a.dropped=u,!this.lastEventRateLimited&&this._captureWarning(u)&&(a.dropped=0)}return this.lastEventRateLimited=l,null==(s=this.instance.persistence)||s.set_property(ie,a),{isRateLimited:l,remainingTokens:a.tokens}}_isPropertyAllowed(e){var t=this.instance.config.property_denylist;return!Je(t)||!t.includes(e)}_triggeringPage(){var e;if(this._isPropertyAllowed("$current_url")&&this._isPropertyAllowed("$pathname")&&null!=Fe&&Fe.pathname)return""+(null!==(e=Fe.origin)&&void 0!==e?e:"")+Fe.pathname}_captureWarning(e){var t,i,s=this.captureEventsBurstLimit,r=this.captureEventsPerSecond,n=this._triggeringPage(),o=this._isPropertyAllowed("$session_id")?null==(t=(i=this.instance).get_session_id)?void 0:t.call(i):void 0,a=[e+" event(s) dropped since the last warning",n?"triggered on "+n:void 0,o?"session "+o:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+a+". Config is set to "+r+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var t=this.serverLimits[e||"events"]||!1;return!1!==t&&(new Date).getTime()e(this.remoteConfig))):e()}_loadRemoteConfigJSON(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return No.info("Using preloaded remote config",this.remoteConfig),void this._onRemoteConfig(this.remoteConfig);if(this._instance._shouldDisableFlags())return void No.warn("Remote config is disabled. Falling back to local config.");this._loadRemoteConfigJs((e=>{if(!e)return No.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){No.error("Error loading remote config",e),this._onRemoteConfig()}}_onRemoteConfig(e,t){!e&&t&&(0===t.statusCode?t.error||No.warn("Failed to fetch remote config from PostHog."):No.error("Failed to fetch remote config from PostHog."));try{this._instance._onRemoteConfig(e?{ok:!0,config:e}:{ok:!1})}catch(e){No.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)||i.ensureFlagsLoaded()}catch(e){No.error("Error loading feature flags",e)}}}var jo=Uint8Array,Vo=Uint16Array,Uo=Uint32Array,Wo=new jo([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]),Go=new jo([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]),Ko=new jo([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Qo=function(e,t){for(var i=new Vo(31),s=0;31>s;++s)i[s]=t+=1<s;++s)for(var n=i[s];i[s+1]>n;++n)r[n]=n-i[s]<<5|s;return[i,r]},Jo=Qo(Wo,2),Yo=Jo[1];Jo[0][28]=258,Yo[258]=28;for(var Zo=Qo(Go,0)[1],Xo=new Vo(32768),ea=0;32768>ea;++ea){var ta=(43690&ea)>>>1|(21845&ea)<<1;Xo[ea]=((65280&(ta=(61680&(ta=(52428&ta)>>>2|(13107&ta)<<2))>>>4|(3855&ta)<<4))>>>8|(255&ta)<<8)>>>1}var ia=function(e,t,i){for(var s=e.length,r=0,n=new Vo(t);s>r;++r)++n[e[r]-1];var o,a=new Vo(t);for(r=0;t>r;++r)a[r]=a[r-1]+n[r-1]<<1;if(i){o=new Vo(1<r;++r)if(e[r])for(var u=r<<4|e[r],c=t-e[r],d=a[e[r]-1]++<=d;++d)o[Xo[d]>>>l]=u}else for(o=new Vo(s),r=0;s>r;++r)o[r]=Xo[a[e[r]-1]++]>>>15-e[r];return o},sa=new jo(288);for(ea=0;144>ea;++ea)sa[ea]=8;for(ea=144;256>ea;++ea)sa[ea]=9;for(ea=256;280>ea;++ea)sa[ea]=7;for(ea=280;288>ea;++ea)sa[ea]=8;var ra=new jo(32);for(ea=0;32>ea;++ea)ra[ea]=5;var na=ia(sa,9,0),oa=ia(ra,5,0),aa=function(e){return(e/8>>0)+(7&e&&1)},la=function(e,t,i){(null==i||i>e.length)&&(i=e.length);var s=new(e instanceof Vo?Vo:e instanceof Uo?Uo:jo)(i-t);return s.set(e.subarray(t,i)),s},ua=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8},ca=function(e,t,i){var s=t/8>>0;e[s]|=i<<=7&t,e[s+1]|=i>>>8,e[s+2]|=i>>>16},da=function(e,t){for(var i=[],s=0;e.length>s;++s)e[s]&&i.push({s:s,f:e[s]});var r=i.length,n=i.slice();if(!r)return[new jo(0),0];if(1==r){var o=new jo(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],u=0,c=1,d=2;for(i[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=r-1;)a=i[i[d].f>i[u].f?u++:d++],l=i[u!=c&&i[d].f>i[u].f?u++:d++],i[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(s=1;r>s;++s)n[s].s>h&&(h=n[s].s);var _=new Vo(h+1),p=ha(i[c-1],_,0);if(p>t){s=0;var g=0,v=p-t,f=1<s;++s){var m=n[s].s;if(t>=_[m])break;g+=f-(1<>>=v;g>0;){var y=n[s].s;t>_[y]?g-=1<=0&&g;--s){var b=n[s].s;_[b]==t&&(--_[b],++g)}p=t}return[new jo(_),p]},ha=function(e,t,i){return-1==e.s?Math.max(ha(e.l,t,i+1),ha(e.r,t,i+1)):t[e.s]=i},_a=function(e){for(var t=e.length;t&&!e[--t];);for(var i=new Vo(++t),s=0,r=e[0],n=1,o=function(e){i[s++]=e},a=1;t>=a;++a)if(e[a]==r&&a!=t)++n;else{if(!r&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(r),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(r);n=1,r=e[a]}return[i.subarray(0,s),t]},pa=function(e,t){for(var i=0,s=0;t.length>s;++s)i+=e[s]*t[s];return i},ga=function(e,t,i){var s=i.length,r=aa(t+2);e[r]=255&s,e[r+1]=s>>>8,e[r+2]=255^e[r],e[r+3]=255^e[r+1];for(var n=0;s>n;++n)e[r+n+4]=i[n];return 8*(r+4+s)},va=function(e,t,i,s,r,n,o,a,l,u,c){ua(t,c++,i),++r[256];for(var d=da(r,15),h=d[0],_=d[1],p=da(n,15),g=p[0],v=p[1],f=_a(h),m=f[0],y=f[1],b=_a(g),S=b[0],w=b[1],C=new Vo(19),k=0;m.length>k;++k)C[31&m[k]]++;for(k=0;S.length>k;++k)C[31&S[k]]++;for(var E=da(C,7),x=E[0],P=E[1],F=19;F>4&&!x[Ko[F-1]];--F);var I,T,R,A,L=u+5<<3,M=pa(r,sa)+pa(n,ra)+o,O=pa(r,h)+pa(n,g)+o+14+3*F+pa(C,x)+(2*C[16]+3*C[17]+7*C[18]);if(M>=L&&O>=L)return ga(t,c,e.subarray(l,l+u));if(ua(t,c,1+(M>O)),c+=2,M>O){I=ia(h,_,0),T=h,R=ia(g,v,0),A=g;var D=ia(x,P,0);for(ua(t,c,y-257),ua(t,c+5,w-1),ua(t,c+10,F-4),c+=14,k=0;F>k;++k)ua(t,c+3*k,x[Ko[k]]);c+=3*F;for(var B=[m,S],q=0;2>q;++q){var H=B[q];for(k=0;H.length>k;++k)ua(t,c,D[N=31&H[k]]),c+=x[N],N>15&&(ua(t,c,H[k]>>>5&127),c+=H[k]>>>12)}}else I=na,T=sa,R=oa,A=ra;for(k=0;a>k;++k)if(s[k]>255){var N;ca(t,c,I[257+(N=s[k]>>>18&31)]),c+=T[N+257],N>7&&(ua(t,c,s[k]>>>23&31),c+=Wo[N]);var z=31&s[k];ca(t,c,R[z]),c+=A[z],z>3&&(ca(t,c,s[k]>>>5&8191),c+=Go[z])}else ca(t,c,I[s[k]]),c+=T[s[k]];return ca(t,c,I[256]),c+T[256]},fa=new Uo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ma=function(){for(var e=new Uo(256),t=0;256>t;++t){for(var i=t,s=9;--s;)i=(1&i&&3988292384)^i>>>1;e[t]=i}return e}(),ya=function(e,t,i){for(;i;++t)e[t]=i,i>>>=8};function ba(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=ma[255&i^t[s]]^i>>>8;e=i},d(){return 4294967295^e}}}(),s=e.length;i.p(e);var r,n,o,a,l,u=(a=10+((r=t).filename&&r.filename.length+1||0),l=8,function(e,t,i,s,r,n){var o=e.length,a=new jo(s+o+5*(1+Math.floor(o/7e3))+r),l=a.subarray(s,a.length-r),u=0;if(!t||8>o)for(var c=0;o>=c;c+=65535){var d=c+65535;o>d?u=ga(l,u,e.subarray(c,d)):(l[c]=!0,u=ga(l,u,e.subarray(c,o)))}else{for(var h=fa[t-1],_=h>>>13,p=8191&h,g=(1<c;++c){var I=b(c),T=32767&c,R=f[I];if(v[T]=R,f[I]=T,c>=P){var A=o-c;if((k>7e3||x>24576)&&A>423){u=va(e,l,0,S,w,C,E,x,F,c-F,u),x=k=E=0,F=c;for(var L=0;286>L;++L)w[L]=0;for(L=0;30>L;++L)C[L]=0}var M=2,O=0,D=p,B=T-R&32767;if(A>2&&I==b(c-B))for(var q=Math.min(_,A)-1,H=Math.min(32767,c),N=Math.min(258,A);H>=B&&--D&&T!=R;){if(e[c+M]==e[c+M-B]){for(var z=0;N>z&&e[c+z]==e[c+z-B];++z);if(z>M){if(M=z,O=B,z>q)break;var j=Math.min(B,z-2),V=0;for(L=0;j>L;++L){var U=c-B+L+32768&32767,W=U-v[U]+32768&32767;W>V&&(V=W,R=U)}}}B+=(T=R)-(R=v[T])+32768&32767}if(O){S[x++]=268435456|Yo[M]<<18|Zo[O];var G=31&Yo[M],K=31&Zo[O];E+=Wo[G]+Go[K],++w[257+G],++C[K],P=c+M,++k}else S[x++]=e[c],++w[e[c]]}}u=va(e,l,!0,S,w,C,E,x,F,c-F,u)}return la(a,0,s+aa(u)+r)}(n=e,null==(o=t).level?6:o.level,null==o.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=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&&ya(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),ya(u,c-8,i.d()),ya(u,c-4,s),u}var Sa=!!Te||!!Ie,wa="text/plain",Ca=!1,ka=(e,t)=>{var i=e.split("#"),s=i[1],r=i[0].split("?"),n=r[0],o=r[1];if(!o)return e;var a=o.split("&").filter((e=>e.split("=")[0]!==t)).join("&");return n+(a?"?"+a:"")+(s?"#"+s:"")},Ea=function(e,t,s){var r;void 0===s&&(s=!0);var n=e.split("?"),o=n[0],a=n[1],l=i({},t),u=null!==(r=null==a?void 0:a.split("&").map((e=>{var t,i=e.split("="),r=i[0],n=s&&null!==(t=l[r])&&void 0!==t?t:i[1];return delete l[r],r+"="+n})))&&void 0!==r?r:[],c=function(e,t){var i,s;void 0===t&&(t="&");var r=[];return ar(e,(function(e,t){et(e)||et(t)||"undefined"===t||(i=encodeURIComponent((e=>e instanceof File)(e)?e.name:e.toString()),s=encodeURIComponent(t),r[r.length]=s+"="+i)})),r.join(t)}(l);return c&&u.push(c),u.length>0?o+"?"+u.join("&"):o},xa=e=>{if(e._encodedBody)return e._encodedBody;var t=e.data,i=e.compression;if(t){if(i===To){var s=ba(function(e,t){var i=e.length;if("undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);for(var s=new jo(e.length+(e.length>>>1)),r=0,n=function(e){s[r++]=e},o=0;i>o;++o){if(r+5>s.length){var a=new jo(r+8+(i-o<<1));a.set(s),s=a}var l=e.charCodeAt(o);128>l?n(l):2048>l?(n(192|l>>>6),n(128|63&l)):l>55295&&57344>l?(n(240|(l=65536+(1047552&l)|1023&e.charCodeAt(++o))>>>18),n(128|l>>>12&63),n(128|l>>>6&63),n(128|63&l)):(n(224|l>>>12),n(128|l>>>6&63),n(128|63&l))}return la(s,0,r)}(Jn(t)),{mtime:0});return{contentType:wa,body:s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength),estimatedSize:s.byteLength}}if(i===Ro){var r=function(e){return e?btoa(encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,((e,t)=>String.fromCharCode(parseInt(t,16))))):e}(Jn(t)),n=(e=>"data="+encodeURIComponent("string"==typeof e?e:Jn(e)))(r);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=Jn(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Pa=e=>{var t,s,r=()=>"sendBeacon"===e.transport?{url:Ea(e.url,{compression:Ro}),encodedBody:xa(i({},e,{compression:Ro,_encodedBody:void 0}))}:{url:ka(e.url,"compression"),encodedBody:xa(i({},e,{compression:void 0,_encodedBody:void 0}))};try{t=xa(e)}catch(t){if(As(e.compression,Zn(e.url,"compression")))return rr.error("Failed to gzip request body, sending uncompressed payload",t),r();throw t}return t&&As(e.compression,Zn(e.url,"compression"))&&!((s=t.body)instanceof ArrayBuffer?Rs(new Uint8Array(s)):ArrayBuffer.isView(s)&&Rs(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Ca=!0,r()):{url:e.url,encodedBody:t}},Fa=e=>{try{return Pa(e)}catch(t){return rr.error(t),void(null==e.callback||e.callback({statusCode:0,error:t}))}},Ia=function(){var e=t((function*(e){var t=Jn(e.data),s=yield function(e,t,i){return Os.apply(this,arguments)}(t,r.DEBUG,{rethrow:!0});if(!s)return e;var n=yield s.arrayBuffer();return i({},e,{_encodedBody:{contentType:wa,body:n,estimatedSize:n.byteLength}})}));return function(t){return e.apply(this,arguments)}}(),Ta=/Failed to fetch|NetworkError|Load failed/i,Ra=e=>"TypeError"===(null==e?void 0:e.name)&&Ta.test((null==e?void 0:e.message)||""),Aa=e=>{var t=Fa(e);if(t){var s=t.url,r=t.encodedBody,n=null!=r?r:{},o=n.contentType,a=n.body,l=n.estimatedSize,u=new Headers;ar(e.headers,(function(e,t){u.append(t,e)})),o&&u.append("Content-Type",o);var c=null,d=!1;if(Re){var h=new Re;c={signal:h.signal,timeout:setTimeout((()=>{var t;d=!0,h.abort(ji("AbortError","PostHog request timed out"+((t=e.timeout)?" after "+t+"ms":"")))}),e.timeout)}}var _=t=>{d&&"AbortError"===(null==t?void 0:t.name)||Ra(t)?rr.warn(t):rr.error(t),null==e.callback||e.callback({statusCode:0,error:t})};try{var p;Ie(s,i({method:(null==e?void 0:e.method)||"GET",headers:u,keepalive:"POST"===e.method&&!e._keepaliveDisabled&&52428.8>(l||0),body:a,signal:null==(p=c)?void 0:p.signal},e.fetchOptions)).then((t=>t.text().then((i=>{var s={statusCode:t.status,text:i};if(200===t.status)try{s.json=JSON.parse(i)}catch(e){rr.error(e)}null==e.callback||e.callback(s)})))).catch(_).finally((()=>c?clearTimeout(c.timeout):null))}catch(e){c&&clearTimeout(c.timeout),_(e)}}},La=e=>{try{var t,s=Pa(e),r=s.url,n=s.encodedBody,o=null!=n?n:{},a=o.body,l=o.estimatedSize;if(!a)return;var u=a instanceof Blob?a:new Blob([a],{type:o.contentType});if(xe.sendBeacon(r,u))return;var c=Je(e.data)?e.data:null==(t=e.data)?void 0:t.batch;if(Je(c)&&c.length>1&&(null!=l?l:0)>16384){var d=Math.ceil(c.length/2),h=t=>Je(e.data)?t:i({},e.data,{batch:t});return La(i({},e,{data:h(c.slice(0,d))})),void La(i({},e,{data:h(c.slice(d))}))}rr.warn("Beacon of ~"+(null!=l?l:0)+" bytes was rejected by the browser, falling back to fetch"),Aa(i({},e,{_keepaliveDisabled:!0}))}catch(e){rr.warn("Beacon send failed",e)}},Ma=(e,t,s,r)=>{var n="query"===r?"POST"===t?"sent_at":"_":void 0;return Ea(s===To?ka(e,"compression"):e,i({},n?{[n]:Date.now().toString()}:{},s===To?{}:{compression:s}))},$a=[];Ie&&$a.push({transport:"fetch",method:Aa}),Te&&$a.push({transport:"XHR",method(e){var t=Fa(e);if(t){var i=new Te,s=t.encodedBody;i.open(e.method||"GET",t.url,!0);var r=null!=s?s:{},n=r.contentType,o=r.body;ar(e.headers,(function(e,t){i.setRequestHeader(t,e)})),n&&i.setRequestHeader("Content-Type",n),e.timeout&&(i.timeout=e.timeout),i.onreadystatechange=()=>{if(4===i.readyState){var t={statusCode:i.status,text:i.responseText};if(200===i.status)try{t.json=JSON.parse(i.responseText)}catch(e){}null==e.callback||e.callback(t)}},i.send(o)}}}),null!=xe&&xe.sendBeacon&&$a.push({transport:"sendBeacon",method:La});var Oa=3e3;class Da{constructor(e,t){this._isPaused=!0,this._queue=[],this._flushTimeoutMs=yt((null==t?void 0:t.flush_interval_ms)||Oa,250,5e3,rr.createLogger("flush interval"),Oa),this._sendRequest=e}enqueue(e){this._queue.push(e),this._flushTimeout||this._setFlushTimeout()}unload(){this._clearFlushTimeout();var 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(i({},e,{transport:"sendBeacon"}))}))}enable(){this._isPaused=!1,this._setFlushTimeout()}_setFlushTimeout(){var e=this;this._isPaused||(this._flushTimeout=setTimeout((()=>{if(this._clearFlushTimeout(),this._queue.length>0){var t=this._formatQueue(),i=function(){var i=t[s],r=(new Date).getTime();i.data&&Je(i.data)&&ar(i.data,(e=>{e.offset=Math.abs(e.timestamp-r),delete e.timestamp})),e._sendRequestSafely(i)};for(var s in t)i()}}),this._flushTimeoutMs))}_sendRequestSafely(e){try{this._sendRequest(e)}catch(e){rr.error(e)}}_clearFlushTimeout(){clearTimeout(this._flushTimeout),this._flushTimeout=void 0}_formatQueue(){var e={};return ar(this._queue,(t=>{var s,r=t,n=(r?r.batchKey:null)||r.url;et(e[n])&&(e[n]=i({},r,{data:[]})),null==(s=e[n].data)||s.push(r.data)})),this._queue=[],e}}var Ba=["retriesPerformedSoFar"];class qa{constructor(e){this._isPolling=!1,this._pollIntervalMs=3e3,this._queue=[],this._instance=e,this._queue=[],this._areWeOnline=!0,!et(ke)&&"onLine"in ke.navigator&&(this._areWeOnline=ke.navigator.onLine,this._onlineListener=()=>{this._areWeOnline=!0,this._flush()},this._offlineListener=()=>{this._areWeOnline=!1},gr(ke,"online",this._onlineListener),gr(ke,"offline",this._offlineListener))}get length(){return this._queue.length}retriableRequest(e){var t=e.retriesPerformedSoFar,r=s(e,Ba);ot(t)&&(r.url=Ea(r.url,{retry_count:t})),this._instance._send_request(i({},r,{callback:e=>{if(200!==e.statusCode&&(400>e.statusCode||e.statusCode>=500)){if((0===e.statusCode?3:10)>(null!=t?t:0))return void this._enqueue(i({retriesPerformedSoFar:t},r));0===e.statusCode&&rr.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!=t?t:0)+" retries.")}null==r.callback||r.callback(e)}}))}_enqueue(e){var t=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=t+1;var i=function(e){var t=3e3*Math.pow(2,e),i=t/2,s=Math.min(18e5,t),r=Math.random()-.5;return Math.ceil(s+r*(s-i))}(t),s=Date.now()+i;this._queue.push({retryAt:s,requestOptions:e});var r="Enqueued failed request for retry in "+i;navigator.onLine||(r+=" (Browser is offline)"),rr.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(){var e=Date.now(),t=[],i=this._queue.filter((i=>e>i.retryAt||(t.push(i),!1)));if(this._queue=t,i.length>0)for(var s of i)this.retriableRequest(s.requestOptions)}unload(){for(var e of(this._poller&&(clearTimeout(this._poller),this._poller=void 0),this._isPolling=!1,et(ke)||(this._onlineListener&&(ke.removeEventListener("online",this._onlineListener),this._onlineListener=void 0),this._offlineListener&&(ke.removeEventListener("offline",this._offlineListener),this._offlineListener=void 0)),this._queue)){var t=e.requestOptions;try{this._instance._send_request(i({},t,{transport:"sendBeacon"}))}catch(e){rr.error(e)}}this._queue=[]}}class Ha{constructor(e){this._updateScrollData=()=>{var e,t,i,s;this._context||(this._context={});var r=this.scrollElement(),n=this.scrollY(),o=r?Math.max(0,r.scrollHeight-r.clientHeight):0,a=n+((null==r?void 0:r.clientHeight)||0),l=(null==r?void 0:r.scrollHeight)||0;this._context.lastScrollY=Math.ceil(n),this._context.maxScrollY=Math.max(n,null!==(e=this._context.maxScrollY)&&void 0!==e?e:0),this._context.maxScrollHeight=Math.max(o,null!==(t=this._context.maxScrollHeight)&&void 0!==t?t:0),this._context.lastContentY=a,this._context.maxContentY=Math.max(a,null!==(i=this._context.maxContentY)&&void 0!==i?i:0),this._context.maxContentHeight=Math.max(l,null!==(s=this._context.maxContentHeight)&&void 0!==s?s:0)},this._instance=e}get _scrollRoot(){return this._instance.config.scroll_root_selector}getContext(){return this._context}resetContext(){var e=this._context;return setTimeout(this._updateScrollData,0),e}startMeasuringScrollPosition(){gr(ke,"scroll",this._updateScrollData,{capture:!0}),gr(ke,"scrollend",this._updateScrollData,{capture:!0}),gr(ke,"resize",this._updateScrollData)}scrollElement(){var e;if(!this._scrollRoot)return null==ke||null==(e=ke.document)?void 0:e.documentElement;var t=Je(this._scrollRoot)?this._scrollRoot:[this._scrollRoot];for(var i of t){var s,r=null==ke||null==(s=ke.document)?void 0:s.querySelector(i);if(r)return r}}_scrollPosition(e){var t,i,s="y"===e?"scrollTop":"scrollLeft";if(this._scrollRoot){var r=this.scrollElement();return r&&r[s]||0}return ke?"y"===e?ke.scrollY||ke.pageYOffset||(null==(t=ke.document)||null==(t=t.documentElement)?void 0:t.scrollTop)||0:ke.scrollX||ke.pageXOffset||(null==(i=ke.document)||null==(i=i.documentElement)?void 0:i.scrollLeft)||0:0}scrollY(){return this._scrollPosition("y")}scrollX(){return this._scrollPosition("x")}}var Na=e=>go(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);class za{constructor(e,t,i,s){this._onSessionIdCallback=e=>{var t=this._getStored();if(!t||t.sessionId!==e){var i={sessionId:e,props:this._sessionSourceParamGenerator(this._instance)};this._persistence.register({[te]:i})}},this._instance=e,this._sessionIdManager=t,this._persistence=i,this._sessionSourceParamGenerator=s||Na,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}_getStored(){return this._persistence.props[te]}getSetOnceProps(){var e,t=null==(e=this._getStored())?void 0:e.props;return t?"r"in t?vo(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(){var e={};return ar(hr(this.getSetOnceProps()),((t,i)=>{"$current_url"===i&&(i="url"),e["$session_entry_"+Ne(i)]=t})),e}}class ja{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(var i of this._events[e]||[])i(t);for(var s of this._events["*"]||[])s(e,t)}constructor(){this._events={}}}var Va=nr("[SessionId]"),Ua=864e5;class Wa{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 ja,this._sessionHasBeenIdleTooLong=(e,t)=>!(!ot(e)||!ot(t))&&Math.abs(e-t)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===pe)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||Cr,this._windowIdGenerator=i||Cr;var r=this._config.persistence_name||this._config.token;if(this._sessionTimeoutMs=1e3*yt(this._config.session_idle_timeout_seconds||1800,60,36e3,Va.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this._resetIdleTimer(),this._window_id_storage_key="ph_"+r+"_window_id",this._primary_window_exists_storage_key="ph_"+r+"_primary_window_exists",this._canUseSessionStorage()){var n=Vr._parse(this._window_id_storage_key),o=Vr._parse(this._primary_window_exists_storage_key);n&&!o?this._windowId=n:Vr._remove(this._window_id_storage_key),Vr._set(this._primary_window_exists_storage_key,!0)}null!=(s=this._config.bootstrap)&&s.sessionID&&this.setBootstrapSessionId(this._config.bootstrap.sessionID),this._listenToReloadWindow()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return et(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&&Vr._is_supported()}_setWindowId(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&Vr._set(this._window_id_storage_key,e))}_getWindowId(){return this._windowId?this._windowId:this._canUseSessionStorage()?Vr._parse(this._window_id_storage_key):null}_isActivityChangeBelowGranularity(e){var t=this._lastPersistedActivityTimestamp;return!st(t)&&!st(e)&&5e3>Math.abs(e-t)}_setSessionId(e,t,i){var s=t!==this._sessionActivityTimestamp,r=!(e!==this._sessionId||i!==this._sessionStartTimestamp);this._sessionStartTimestamp=i,this._sessionActivityTimestamp=t,this._sessionId=e,r&&!s||r&&this._isActivityChangeBelowGranularity(t)||(this._lastPersistedActivityTimestamp=t,this._persistence.register({[I]:[t,e,i]}))}_useCrossTabRefreshHardening(){var e,t=null==(e=this._config)?void 0:e.persistence_save_debounce_ms;return ot(t)&&t>0}_refreshSessionIdFromStorage(){this._useCrossTabRefreshHardening()?this._persistence.refreshKey(I):(this._persistence.flush(),this._persistence.load())}_flushPendingActivityTimestamp(){var e;if(!st(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this._lastPersistedActivityTimestamp){this._refreshSessionIdFromStorage();var t=this._getSessionId();t[1]===this._sessionId&&t[2]===this._sessionStartTimestamp&&(this._lastPersistedActivityTimestamp=this._sessionActivityTimestamp,this._persistence.register({[I]:[this._sessionActivityTimestamp,null!==(e=this._sessionId)&&void 0!==e?e:null,this._sessionStartTimestamp]}),this._persistence.flush())}}_freshestActivityTimestamp(){var e=this._getSessionId()[0],t=ot(e)?e:0,i=ot(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,i)}_isSessionIdleAfterCrossTabRefresh(e){return this._refreshSessionIdFromStorage(),this._sessionHasBeenIdleTooLong(e,this._freshestActivityTimestamp())}_getSessionId(){var e=this._persistence.props[I];return Je(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){void 0===t&&(t=!1);var i=function(e,t){void 0===t&&(t=(new Date).getTime());try{var i=(e=>{var 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 Va.error("Bootstrap sessionID cannot be in the future"):i}catch(e){return void Va.error("Invalid sessionID in bootstrap",e)}}(e);return!et(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&&ke&&(ke.removeEventListener(ye,this._beforeUnloadListener,{capture:!1}),this._beforeUnloadListener=void 0),this._sessionIdChangedHandlers=[]}_listenToReloadWindow(){this._beforeUnloadListener=()=>{this._flushPendingActivityTimestamp(),this._canUseSessionStorage()&&Vr._remove(this._primary_window_exists_storage_key)},gr(ke,ye,this._beforeUnloadListener,{capture:!1})}checkAndGetSessionAndWindowId(e,t,i){if(void 0===e&&(e=!1),void 0===t&&(t=null),void 0===i&&(i=!1),this._config.cookieless_mode===pe)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var s=t||(new Date).getTime(),r=this._sessionId;if(i)this._lastCookieSyncTimestamp=s;else if(st(this._lastCookieSyncTimestamp)||this._lastCookieSyncTimestamp>s||s-this._lastCookieSyncTimestamp>=1e3){var n,o;null==(n=(o=this._persistence).syncCookieProperties)||n.call(o),this._lastCookieSyncTimestamp=s}var a=this._getSessionId(),l=a[1],u=a[2],c=!et(r)&&l!==r,d=this._freshestActivityTimestamp(),h=this._getWindowId(),_=this._pendingBootstrapSession,p=!!_&&(_.sessionStartTimestamp>s+6e4||s-_.sessionStartTimestamp>Ua),g=_?p:ot(u)&&Math.abs(s-u)>Ua,v=!1,f=c,m=!l||!!_,y=l,b=!m&&!e&&this._sessionHasBeenIdleTooLong(s,d);if(b){(b=this._isSessionIdleAfterCrossTabRefresh(s))||Va.info("cross-tab refresh kept the session alive",{sessionId:l});var S=this._getSessionId();l=S[1],u=S[2]}if(m||b||g){f=!1;var w=_&&!p;l=w?_.sessionId:this._sessionIdGenerator(),h=this._windowIdGenerator(),Va.info("new session ID assigned",{sessionId:l,windowId:h,bootstrapped:!!w,changeReason:{noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g}}),u=w?_.sessionStartTimestamp:s,this._pendingBootstrapSession=void 0,v=!0}else h||(h=this._windowIdGenerator(),v=!0),(f=f||l!==y)&&(Va.info("adopted cross-tab session id",{sessionId:l,windowId:h}),v=!0);var C=ot(d)&&e&&!g?d:s,k=ot(u)?u:(new Date).getTime();this._setWindowId(h),this._setSessionId(l,C,k),e||this._resetIdleTimer();var E={noSessionId:m,activityTimeout:b,sessionPastMaximumLength:g,crossTabAdoption:f};return v&&this._sessionIdChangedHandlers.forEach((e=>e(l,h,E))),{sessionId:l,windowId:h,sessionStartTimestamp:k,changeReason:v?E:void 0,lastActivityTimestamp:d}}_resetIdleTimer(){this._destroyed||(clearTimeout(this._enforceIdleTimeout),this._enforceIdleTimeout=setTimeout((()=>{if(!this._destroyed)if(this._isSessionIdleAfterCrossTabRefresh((new Date).getTime())){var e=this._sessionId;this.resetSessionId(),this._eventEmitter.emit("forcedIdleReset",{idleSessionId:e})}else this._resetIdleTimer()}),1.1*this.sessionTimeoutMs))}}var Ga=function(e,t){if(!e)return!1;var i=e.userAgent;if(i&&Be(i,t))return!0;try{var s=null==e?void 0:e.userAgentData;if(null!=s&&s.brands&&s.brands.some((e=>Be(null==e?void 0:e.brand,t))))return!0}catch(e){}return!!e.webdriver};function Ka(){return(Ka=t((function*(){var e=null==xe?void 0:xe.userAgentData;if(null!=e&&e.getHighEntropyValues)try{var t=yield e.getHighEntropyValues(["model"]),i=null==t?void 0:t.model;return tt(i)&&i.length>0?i:void 0}catch(e){return void rr.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",e)}}))).apply(this,arguments)}function Qa(e){var t;return!(null==(t=e.conditions)||null==(t=t.events)||null==(t=t.values)||!t.length)}var Ja=(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}},Ya=e=>e.toLowerCase(),Za={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=>Ja(t,e))))),not_regex:(e,t)=>t.every((t=>e.every((e=>!Ja(t,e))))),icontains:(e,t)=>t.map(Ya).some((t=>e.map(Ya).some((e=>t.includes(e))))),not_icontains:(e,t)=>t.map(Ya).every((t=>e.map(Ya).every((e=>!t.includes(e))))),gt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i>parseFloat(e)))})),lt:(e,t)=>t.some((t=>{var i=parseFloat(t);return!isNaN(i)&&e.some((e=>i{var i=e[1],s=null==t?void 0:t[e[0]];if(null==s)return!1;var r=Za[i.operator];return!!r&&r(i.values,[String(s)])}))}function el(e,t,i){return Jn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:i})}var tl="custom",il="i.posthog.com",sl=/^\/static\//,rl=["/s/","/e/","/i/"];class nl{constructor(e){this._regionCache={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return"https://app.posthog.com"===e?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,t=null==(e=this.instance.config.ui_host)?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace("."+il,".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":tl),this._regionCache[this.apiHost]}_staticAssetHostOverride(e){if(sl.test(e)){var t=this.instance.config.asset_host;if("string"==typeof t)return t.trim().replace(/\/$/,"")||void 0}}_urlKey(e){var t=Yn(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}_prepareEndpoint(e,t,i){if("ui"===e)return i;var s=i,r=this.instance.config.rewriteRequestPath;if(r){var n,o=(null==(n=Yn(i))?void 0:n.href)||i;s=r(new URL(o)).toString()}if(r&&"api"===e&&rl.some((e=>0===t.indexOf(e)))){var a=this._urlKey(s);if(a){var l,u=this.apiHost,c=this._ingestionEndpoints;(null==(l=c)?void 0:l.apiHost)===u&&c.rewriteRequestPath===r||(c={apiHost:u,rewriteRequestPath:r,urls:new Set},this._ingestionEndpoints=c),c.urls.add(a)}}return s}isIngestionEndpoint(e){var 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(void 0===t&&(t=""),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){var i=this._staticAssetHostOverride(t);if(i)return this._prepareEndpoint(e,t,""+i+t)}if(this.region===tl)return this._prepareEndpoint(e,t,this.apiHost+t);var s=il+t;switch(e){case"assets":return this._prepareEndpoint(e,t,"https://"+this.region+"-assets."+s);case"api":return this._prepareEndpoint(e,t,"https://"+this.region+"."+s)}}}var ol=nr("[Surveys]"),al="seenSurvey_",ll=e=>{try{var t=(e=>((e,t)=>""+e+function(e){return e.current_iteration&&e.current_iteration>0?e.id+"_"+e.current_iteration:e.id}(t))(al,e))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(e){ol.error("Failed to persist survey seen state",e)}},ul=["popover","widget","api"],cl={ignoreConditions:!1,ignoreDelay:!1,displayType:Do},dl=nr("[PostHog ExternalIntegrations]"),hl={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class _l{constructor(e){this._instance=e}_loadScript(e,t){var i;null==(i=Oe.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,e,(e=>{if(e)return dl.error("failed to load script",e);t()}))}startIfEnabledOrStop(){var e=this,t=function(){var t,s,r,n=i[0],o=i[1];!o||null!=(t=Oe.__PosthogExtensions__)&&null!=(t=t.integrations)&&t[n]||e._loadScript(hl[n],(()=>{var t;null==(t=Oe.__PosthogExtensions__)||null==(t=t.integrations)||null==(t=t[n])||t.start(e._instance)})),!o&&null!=(s=Oe.__PosthogExtensions__)&&null!=(s=s.integrations)&&s[n]&&(null==(r=Oe.__PosthogExtensions__)||null==(r=r.integrations)||null==(r=r[n])||r.stop())};for(var i of Object.entries(null!==(s=this._instance.config.integrations)&&void 0!==s?s:{})){var s;t()}}}class pl{constructor(e,t){this._logger=e,this._client=t,this._extensions=new Map,this._disposed=!1}add(e){var i=this;return t((function*(){if(i._disposed)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(i._extensions.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');i._extensions.set(e.name,e);try{var t=e.setup(i._client);t&&(yield t)}catch(t){var s=i._extensions.get(e.name)===e;s&&i._extensions.delete(e.name),i._logger.error('Failed to set up browser extension "'+e.name+'"',t),s&&i._disposeExtension(e)}}))()}getExtension(e){return this._extensions.get(e)}dispose(){if(!this._disposed){this._disposed=!0;var e=Array.from(this._extensions.values()).reverse();for(var t of(this._extensions.clear(),e))this._disposeExtension(t)}}_disposeExtension(e){try{var t=null==e.dispose?void 0:e.dispose();t&&Ye(t.then)&&t.then(void 0,(t=>{this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}))}catch(t){this._logger.error('Failed to dispose browser extension "'+e.name+'"',t)}}}class gl{constructor(e){this._instance=e}initialize(){}get(e){var t=this._instance.persistence;if("string"==typeof e)return null==t?void 0:t.get_property(e);var i={};for(var s of e){var r=null==t?void 0:t.get_property(s);et(r)||(i[s]=r)}return i}set(e,t){var i;null==(i=this._instance.persistence)||i.register("string"==typeof e?{[e]:t}:e)}remove(e){var t;null==(t=this._instance.persistence)||t.unregister(e)}}var vl="extensionsRemoteConfig";class fl{constructor(e){this._disposed=!1,this.instance=e,this._logger=rr,this._latestRemoteConfigResult=e._lastRemoteConfig,this.kv=new gl(e),this.onEvent=e=>Bo(this.instance.on("eventCaptured",(t=>{try{e({event:t.event,properties:t.properties})}catch(e){this._logger.error("Browser extension event listener failed",e)}}))),this.onRemoteConfig=e=>{if(this._disposed)return Bo((()=>{}));var t=t=>{try{e(t)}catch(e){this._logger.error("Browser extension remote config listener failed",e)}},i=this.instance._internalEventEmitter.on(vl,t);return this._latestRemoteConfigResult&&t(this._latestRemoteConfigResult),Bo(i)},this._runtime=new pl(rr.createLogger("[BrowserExtensions]"),this)}get logger(){return this._logger}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return null!==(e=this.instance.get_property(a))&&void 0!==e?e:this.distinctId}get deviceId(){var e=this.instance.get_property(a);return"string"==typeof e?e:void 0}get library(){return{name:r.LIB_NAME,version:r.LIB_VERSION}}get initialPersonProperties(){var e,t;return null!==(e=null==(t=this.instance.persistence)?void 0:t.get_initial_props())&&void 0!==e?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,i,s,r=null==(e=this.instance.sessionManager)?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}}catch(e){return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get canCapture(){return this.instance.is_capturing()}get projectToken(){return this.instance.config.token}add(e){return this._runtime.add(e)}getExtension(e){return this._runtime.getExtension(e)}capture(e,i,s){var r=this;return t((function*(){s?r.instance.capture(e,i,{timestamp:s.timestamp,uuid:s.uuid,$set:s.set,$set_once:s.setOnce}):r.instance.capture(e,i)}))()}registerDynamicEventProperties(e){return Bo(this.instance._registerExtensionEventProperties(e))}handleRemoteConfig(e){this._disposed||(this._latestRemoteConfigResult=e,this.instance._internalEventEmitter.emit(vl,e))}sendRequest(e,i){var s=this;return t((function*(){var t;void 0===i&&(i={});var r=s.instance.requestRouter.endpointFor(null!==(t=i.target)&&void 0!==t?t:"api",e),n={method:i.method,url:i.query?Ea(r,i.query):r,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?Ve.Base64:void 0,timestampMode:i.sentAt};return"sendBeacon"===i.transport?(s.instance._send_request(n),{statusCode:202}):new Promise((e=>{n.callback=e,s.instance._send_request(n)}))}))()}dispose(){this._disposed||(this._disposed=!0,this._runtime.dispose())}}var ml={},yl=0,bl=()=>{},Sl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',wl="Surveys module not available",Cl="sanitize_properties is deprecated. Use before_send instead",kl="Invalid value for property_denylist config: ",El=/^[A-Za-z0-9_-]{1,400}$/,xl=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,Pl=["token","distinct_id",le],Fl="posthog",Il=!Sa&&-1===(null==Le?void 0:Le.indexOf("MSIE"))&&-1===(null==Le?void 0:Le.indexOf("Mozilla")),Tl=e=>{var 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},Rl=e=>{var t;return i({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:pr(null==Pe?void 0:Pe.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:bl,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_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:Fe&&tt(null==Fe?void 0:Fe.search)&&-1!==Fe.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==ke||null==(t=ke.location)?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,surveys_request_timeout_ms:1e4,on_request_error(e){rr.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:fe,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:Oa},error_tracking:{},_onCapture:bl},(e=>({rageclick:e&&e>="2026-05-30"?{content_ignorelist:gn,ignore_text_selection:!0}:!e||"2025-11-30">e||{content_ignorelist:!0},capture_pageview:!e||"2025-05-24">e||"history_change",session_recording:Tl(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))},Al=[["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"]],Ll=e=>{var t={};for(var i of Al){var s=i[0],r=i[1];et(e[s])||(t[r]=e[s])}var n=lr({},t,e),o=e.__preview_external_dependency_versioned_paths;return et(o)||(et(e.strict_script_versioning)&&(n.strict_script_versioning=!!o),tt(o)&&et(e.asset_host)&&(n.asset_host=o)),Je(e.property_blacklist)&&(et(e.property_denylist)?n.property_denylist=e.property_blacklist:Je(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:rr.error(kl+e.property_denylist)),n};class Ml{constructor(){this.__forceAllowLocalhost=!1}get _forceAllowLocalhost(){return this.__forceAllowLocalhost}set _forceAllowLocalhost(e){rr.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class $l{_removeExtension(e){if(e){var t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}}_replaceExtension(e,t){return this._removeExtension(e),this._extensions.push(t),null==t.initialize||t.initialize(),t}_inCookielessMode(){return this.config.cookieless_mode===pe||this.config.cookieless_mode===_e&&this.consent.isRejected()}_warnIfVolatileIdentityWithoutStableId(){if(!(this._hasWarnedAboutVolatileIdentity||this.config.reuseAnonymousId||this.config.segment||this._inCookielessMode())){var e,t,i,s="memory"===this.config.persistence||"sessionStorage"===this.config.persistence;(s||this.config.disable_persistence)&&(this._hasStableInitialDistinctId||(s?(e="persistence is set to '"+this.config.persistence+"'",t="memory"===this.config.persistence?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(e="persistence is disabled (disable_persistence is true)",t="on every page load",i="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]",e+" but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID "+t+", 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. "+i)))}}_healCookielessSentinelDistinctId(){if(!this._inCookielessMode()&&this.get_distinct_id()===ae){var e=this.persistence;if(e){this._is_persistence_disabled()||e.load(!0);var t=this.get_distinct_id();if(!t||t===ae){var i=this.config.get_device_id(Cr());this.register({distinct_id:i,$device_id:i}),e.set_property(ee,ge)}this._sync_opt_out_with_persistence()}}}get decideEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}get flagsEndpointWasHit(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.hasLoadedFlags)&&void 0!==e&&e}constructor(){var e;this.webPerformance=new Ml,this._personProcessingSetOncePropertiesSent=!1,this.version=r.LIB_VERSION,this._sessionRegisteredPropKeys=new Set,this._sessionRegisteredPropertiesStorageKey="",this._internalEventEmitter=new ja,this._extensions=[],this._extensionEventPropertyProducers=[],this._hasStableInitialDistinctId=!1,this._hasWarnedAboutVolatileIdentity=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Rl(),this.SentryIntegration=Vn,this.sentryIntegration=e=>function(e,t){var i=jn(e,t);return{name:zn,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 Ha(this),this.pageViewManager=new Un(this),this.rateLimiter=new Ho(this),this.requestRouter=new nl(this),this.consent=new Ur(this),this.externalIntegrations=new _l(this);var t=null!==(e=$l.__defaultExtensionClasses)&&void 0!==e?e:{};this.featureFlags=t.featureFlags&&new t.featureFlags(this),this.toolbar=t.toolbar&&new t.toolbar(this),this.surveys=t.surveys&&new t.surveys(this),this.conversations=t.conversations&&new t.conversations(this),this.logs=t.logs&&new t.logs(this),this.metrics=t.metrics&&new t.metrics(this),this.experiments=t.experiments&&new t.experiments(this),this.exceptions=t.exceptions&&new t.exceptions(this),this.people={set:(e,t,i)=>{var s=tt(e)?{[e]:t}:e;this.setPersonProperties(s),null==i||i({})},set_once:(e,t,i)=>{var s=tt(e)?{[e]:t}:e;this.setPersonProperties(void 0,s),null==i||i({})}},this.on("eventCaptured",(e=>rr.info('send "'+(null==e?void 0:e.event)+'"',e)))}init(e,t,i){if(i&&i!==Fl){var s,r=null!==(s=ml[i])&&void 0!==s?s:new $l;return r._init(e,t,i),ml[i]=r,ml[Fl][i]=r,r}return this._init(e,t,i)}_init(e,t,s){var n,o,a;void 0===t&&(t={});var u,c=tt(e)?e.trim():"";if(!c)return rr.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return c!==(null==(u=this.config)?void 0:u.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('"+c+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Rl(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);var d=Rl(t.defaults),h=Ll(t),_=lr({},d,h,{name:s,token:c});Ze(d.rageclick)&&Ze(h.rageclick)&&(_.rageclick=lr({},d.rageclick,h.rageclick)),Ze(d.session_recording)&&Ze(h.session_recording)&&(_.session_recording=lr({},d.session_recording,h.session_recording)),this.set_config(_),this.config.on_xhr_error&&rr.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=t.disable_compression?void 0:To;var p=this._is_persistence_disabled();if(this.persistence=new Io(this.config,p),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Io(i({},this.config,{persistence:"sessionStorage"}),p,!1),this._sessionRegisteredPropertiesStorageKey="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties","memory"!==this.config.persistence&&!p&&Vr._is_supported()){var g=Vr._parse(this._sessionRegisteredPropertiesStorageKey);Je(g)&&g.forEach((e=>{tt(e)&&this._sessionRegisteredPropKeys.add(e)}))}else Vr._remove(this._sessionRegisteredPropertiesStorageKey);var v=i({},this.persistence.props),f=i({},this.sessionPersistence.props);this.register({$initialization_time:(new Date).toISOString()}),this._requestQueue=new Da((e=>this._send_retriable_request(e)),this.config.request_queue_config),this._retryQueue=new qa(this),this.__request_queue=[];var m=this._inCookielessMode();m||(this.sessionManager=new Wa(this),this.sessionPropsManager=new za(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId(((e,t,i)=>{(null!=i&&i.activityTimeout||null!=i&&i.sessionPastMaximumLength||null!=i&&i.crossTabAdoption)&&this._clearSessionRegisteredProps()}))),this._enrollFeatureFlags(),this.config.__preview_deferred_init_extensions?(rr.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this._initExtensions(m)}),0)):(rr.info("Initializing extensions synchronously"),this._initExtensions(m)),r.DEBUG=r.DEBUG||this.config.debug,r.DEBUG&&rr.info("Starting in debug mode",{this:this,config:t,thisC:i({},this.config),p:v,s:f}),!this.config.identity_distinct_id||null!=(n=t.bootstrap)&&n.distinctID||(t.bootstrap=i({},t.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));var y=null==(o=t.bootstrap)?void 0:o.distinctID;if(this._hasStableInitialDistinctId=!!y&&!it(y),void 0!==(null==(a=t.bootstrap)?void 0:a.distinctID)){var b=t.bootstrap.distinctID,S=this.get_distinct_id(),w=this.persistence.get_property(ee);if(t.bootstrap.isIdentifiedID&&null!=S&&S!==b&&w===ge)this.identify(b);else if(t.bootstrap.isIdentifiedID&&null!=S&&S!==b&&w===ve)rr.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{var C=this.config.get_device_id(Cr()),k=t.bootstrap.isIdentifiedID?C:b;this.persistence.set_property(ee,t.bootstrap.isIdentifiedID?ve:ge),this.register({distinct_id:b,$device_id:k})}}if(m)this.register_once({distinct_id:ae,$device_id:null},"");else if(!this.get_distinct_id()){var E=this.config.get_device_id(Cr());this.register_once({distinct_id:E,$device_id:E},""),this.persistence.set_property(ee,ge)}return gr(ke,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),t.segment?Nn(this,(()=>this._loaded())):this._loaded(),Ye(this.config._onCapture)&&this.config._onCapture!==bl&&(rr.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(e=>this.config._onCapture(e.event,e)))),this.config.ip&&rr.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 Ka.apply(this,arguments)}().then((e=>{e&&this.register({[l]:e})})).catch(bl),this}_isSharedExtension(e){var t=e;return tt(t.name)&&Ye(t.setup)}_enrollExtension(e,t){this._isSharedExtension(e)?t.push((()=>{this._getBrowserClientAdapter().add(e).catch((()=>null==e.dispose?void 0:e.dispose())).catch((t=>{rr.error('Failed to dispose browser extension "'+e.name+'"',t)}))})):this._extensions.push(e)}_enrollFeatureFlags(){var e,t,i,s,r,n,o=null!==(e=null==(t=this.config.__extensionClasses)?void 0:t.featureFlags)&&void 0!==e?e:null==(i=$l.__defaultExtensionClasses)?void 0:i.featureFlags;o&&(this.featureFlags&&this.featureFlags instanceof o||(null==(s=this._featureFlagsReloadingUnsubscribe)||s.call(this),this._featureFlagsReloadingUnsubscribe=void 0,this.featureFlags=new o(this)),Ye(this.featureFlags.onReloading)&&Ye(this.featureFlags.setup)?this._featureFlagsReloadingUnsubscribe||(this._featureFlagsReloadingUnsubscribe=this.featureFlags.onReloading((()=>{this._internalEventEmitter.emit("featureFlagsReloading",!0)})),this._getBrowserClientAdapter().add(this.featureFlags)):null==(r=(n=this.featureFlags).initialize)||r.call(n))}_initExtensions(e){var t,s,r,n,o,a,l,u=performance.now(),c=i({},$l.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this._extensions.push(this.exceptions=null!==(t=this.exceptions)&&void 0!==t?t:new c.exceptions(this)),c.historyAutocapture&&this._extensions.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this._extensions.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this._extensions.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this._extensions.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),c.autocapture&&this._enrollExtension(this.autocapture=new c.autocapture(this),d),c.surveys&&this._enrollExtension(this.surveys=null!==(s=this.surveys)&&void 0!==s?s:new c.surveys(this),d),c.logs&&this._enrollExtension(this.logs=null!==(r=this.logs)&&void 0!==r?r:new c.logs(this),d),c.metrics&&this._extensions.push(this.metrics=null!==(n=this.metrics)&&void 0!==n?n:new c.metrics(this)),c.conversations&&this._extensions.push(this.conversations=null!==(o=this.conversations)&&void 0!==o?o:new c.conversations(this)),c.productTours&&this._extensions.push(this.productTours=new c.productTours(this)),c.heatmaps&&this._extensions.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this._extensions.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this._extensions.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this._extensions.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,Bn)),c.toolbar&&this._extensions.push(this.toolbar=null!==(a=this.toolbar)&&void 0!==a?a:new c.toolbar(this)),c.experiments&&this._extensions.push(this.experiments=null!==(l=this.experiments)&&void 0!==l?l:new c.experiments(this)),this._extensions.forEach((e=>{e.initialize&&d.push((()=>{null==e.initialize||e.initialize()}))})),d.push((()=>{if(this._pendingRemoteConfig){var e=this._pendingRemoteConfig;this._pendingRemoteConfig=void 0,this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}})),this._processInitTaskQueue(d,u)}_processInitTaskQueue(e,t){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-t>=30&&e.length>0)return void setTimeout((()=>{this._processInitTaskQueue(e,t)}),0);var i=e.shift();if(i)try{i()}catch(e){rr.error("Error initializing extension:",e)}}var s=Math.round(performance.now()-t);this.register_for_session({[ue]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[ce]:s}),this.config.__preview_deferred_init_extensions&&rr.info("PostHog extensions initialized ("+s+"ms)")}_onRemoteConfig(e){var t;if(!Pe||!Pe.body)return rr.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 i,s=e.config;s.supportedCompression&&!this.config.disable_compression&&(this.compression=qe(s.supportedCompression,To)?To:qe(s.supportedCompression,Ro)?Ro:void 0),null!=(i=s.analytics)&&i.endpoint&&(this.analyticsDefaultEndpoint=s.analytics.endpoint)}this.set_config({person_profiles:this._initialPersonProfilesConfig?this._initialPersonProfilesConfig:fe}),null==(t=this._browserClientAdapter)||t.handleRemoteConfig(e),this._extensions.forEach((t=>null==t.onRemoteConfig?void 0:t.onRemoteConfig(e)))}_loaded(){try{this.config.loaded(this)}catch(e){rr.critical("`loaded` function failed",e)}if(this._start_queue_if_opted_in(),this.config.internal_or_test_user_hostname&&null!=Fe&&Fe.hostname){var e=Fe.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 zo(this),this._remoteConfigLoader.load()}_start_queue_if_opted_in(){var e;this.is_capturing()&&this.config.request_batching&&(null==(e=this._requestQueue)||e.enable())}_dom_loaded(){this.is_capturing()&&or(this.__request_queue,(e=>this._send_retriable_request(e))),this.__request_queue=[],this._start_queue_if_opted_in()}_handle_unload(){var e,t,i,s,r;null==(e=this.surveys)||null==e.handlePageUnload||e.handlePageUnload(),null==(t=this.metrics)||t.flush("sendBeacon"),this.config.request_batching?(this._shouldCapturePageleave()&&this.capture(Se),null==(i=this.logs)||i.flushLogs("sendBeacon"),null==(s=this._requestQueue)||s.unload(),null==(r=this._retryQueue)||r.unload()):this._shouldCapturePageleave()&&this.capture(Se,null,{transport:"sendBeacon"})}_send_request(e){var t;this.__loaded?Il?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=i({},this.config.request_headers,e.headers),e.compression="best-available"===e.compression?null!==(t=this.compression)&&void 0!==t?t:e.compressionFallback:e.compression,(et(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(e=>{var t,s,r,n=i({},e);n.timeout=n.timeout||6e4;var o,a,l,u,c,d=null!==(t=n.transport)&&void 0!==t?t:"fetch";"sendBeacon"===d&&et(n.compression)&&n.data&&(n.compression=Ro),"POST"===n.method&&n.data&&("capture-body"===n.timestampMode?n.data={api_key:null!==(a=null==(c=(u=(Je(o=n.data)?o:[o]).map((e=>i({},e,e.timestamp instanceof Date&&!isNaN(e.timestamp.getTime())?{timestamp:e.timestamp.toISOString()}:{}))))[0])||null==(l=c.properties)?void 0:l.token)&&void 0!==a?a:null==c?void 0:c.token,batch:u,sent_at:(new Date).toISOString()}:"body"===n.timestampMode&&(n.data=function(e,t){return void 0===t&&(t=(new Date).toISOString()),Je(e)?e.map((e=>i({},e,{sent_at:t}))):i({},e,{sent_at:t})}(n.data))),n.url=Ma(n.url,n.method,n.compression,n.timestampMode);var h=$a.filter((e=>!n.disableTransport||!e.transport||!n.disableTransport.includes(e.transport))),_=null!==(s=null==(r=function(e,t){for(var i=0;e.length>i;i++)if(e[i].transport===d)return e[i]}(h))?void 0:r.method)&&void 0!==s?s:h[0].method;if(!_)throw new Error("No available transport method");var p=e=>{try{_(e)}catch(e){Ra(e)?rr.warn(e):rr.error(e),null==n.callback||n.callback({statusCode:0,error:e})}};"sendBeacon"!==d&&n.data&&n.compression===To&&Ae&&"undefined"!=typeof Promise&&!Ca?Ia(n).then((e=>{p(e)})).catch((t=>{if(Ls(t))return Ca=!0,void p(i({},n,{compression:void 0,url:Ma(e.url,e.method,void 0,e.timestampMode)}));(e=>{if(!e||"object"!=typeof e)return!1;var t="name"in e?String(e.name):"";return Ls(e)||t===Ts})(t)&&(Ca=!0),p(n)})):_(n)})(i({},e,{callback:t=>{var i,s;this.rateLimiter.checkForLimiting(t),400>t.statusCode||null==(i=(s=this.config).on_request_error)||i.call(s,t),null==e.callback||e.callback(t)}}))):e.fireCallbackOnDrop&&(null==e.callback||e.callback({statusCode:0}))}_send_retriable_request(e){this._retryQueue?this._retryQueue.retriableRequest(e):this._send_request(e)}_execute_array(e){yl++;try{var t,i=[],s=[],r=[];or(e,(e=>{if(e)if(Je(t=e[0]))r.push(e);else if(Ye(e))try{e.call(this)}catch(t){rr.error("Error executing queued PostHog call",e,t)}else Je(e)&&"alias"===t?i.push(e):Je(e)&&-1!==t.indexOf("capture")&&Ye(this[t])?r.push(e):s.push(e)}));var n=function(e,t){or(e,(function(e){try{if(Je(e[0])){var i=t;ar(e,(function(e){i=i[e[0]].apply(i,e.slice(1))}))}else t[e[0]].apply(t,e.slice(1))}catch(t){rr.error("Error executing queued PostHog call",e,t)}}))};n(i,this),n(s,this),n(r,this)}finally{yl--}}push(e){if(yl>0&&Je(e)&&tt(e[0])){var t=$l.prototype[e[0]];Ye(t)&&t.apply(this,e.slice(1))}else this._execute_array([e])}_getPersistedFacebookClickId(){var e,t=null==(e=this.persistence)?void 0:e.get_property(d);return tt(t)&&xl.test(t)?{value:t,delivered:!1}:Ze(t)&&tt(t.value)&&xl.test(t.value)?{value:t.value,delivered:!0===t.delivered}:void 0}_updateFacebookClickId(e,t,i,s){if(this.persistence){this.persistence.refreshKey(d);var r=this._getPersistedFacebookClickId();if(!s){if(i)return tt(t)&&xl.test(t)?(t!==(null==r?void 0:r.value)&&this.persistence.register({[d]:{value:t,delivered:!1}}),{value:t,pending:t!==(null==r?void 0:r.value)||!r.delivered}):void this.persistence.unregister(d);if(tt(e)&&El.test(e)){if((null==r?void 0:r.value.split(".")[3])===e)return{value:r.value,pending:!r.delivered};var n="fb.1."+Date.now()+"."+e;return this.persistence.register({[d]:{value:n,delivered:!1}}),{value:n,pending:!0}}return r?{value:r.value,pending:!r.delivered}:void 0}this.persistence.unregister(d)}}_markFacebookClickIdDelivered(e){if(this.persistence){this.persistence.refreshKey(d);var t=this._getPersistedFacebookClickId();(null==t?void 0:t.value)!==e||t.delivered||this.persistence.register({[d]:{value:e,delivered:!0}})}}capture(e,t,s){var r,n,o,a,l,u,d,h,_,p;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this._requestQueue){if(this.is_capturing())if(!et(e)&&tt(e)){this._healCookielessSentinelDistinctId();var g=!this.config.opt_out_useragent_filter&&this._is_bot();if(!g||this.config.__preview_capture_bot_pageviews){var v=null!=s&&s.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(null==v||!v.isRateLimited){var f;null!=t&&t.$current_url&&!tt(null==t?void 0:t.$current_url)&&(rr.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!=s&&s._originatedFromCaptureException||rr.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&&(f=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();var m=new Date,y=(null==s?void 0:s.timestamp)||m,b=zi(null==s?void 0:s.uuid,Cr),S={uuid:b,event:e,properties:this.calculateEventProperties(e,t||{},y,b)};e===be&&this.config.__preview_capture_bot_pageviews&&g&&(S.event="$bot_pageview",S.properties.$browser_type="bot"),v&&(S.properties.$lib_rate_limit_remaining_tokens=v.remainingTokens);var w="$feature_flag_called"===e&&!1===S.properties.$feature_flag_has_experiment&&!0===this.get_property(B);(null==s?void 0:s.$set)&&!w&&(S.$set=null==s?void 0:s.$set);var C=Ze(null==t?void 0:t.$set)?t.$set:void 0,k=!(null==s||!s.$set)&&c in s.$set,E=k||!!C&&c in C,x=k?null==s||null==(r=s.$set)?void 0:r[c]:null==C?void 0:C[c],P=Je(null==t?void 0:t.$unset)?t.$unset:[],F=(null==s?void 0:s.$unset)||[],I=-1!==P.indexOf(c)||-1!==F.indexOf(c),T=this._updateFacebookClickId(null==(n=f)?void 0:n.fbclid,x,E,I);T&&!0===S.properties.$process_person_profile&&T.pending&&!E&&!w&&(S.$set=i({[c]:T.value},S.$set));var R=null==s?void 0:s.$unset;R&&(S.$unset=R);var A,L,M,O=w?void 0:this._calculate_set_once_properties(null==s?void 0:s.$set_once,e!==Ce,e===we);if(O&&(S.$set_once=O),null!=s&&s._noTruncate||(d=this.config.properties_string_max_length,h=S,_=e=>tt(e)?e.slice(0,d):e,p=new Set,S=function e(t,i){if(t!==Object(t))return _?_(t):t;if(!p.has(t)){var s;if(p.add(t),Je(t))s=[],or(t,(t=>{s.push(e(t))}));else{var r={};ar(t,((t,i)=>{p.has(t)||(r[i]=e(t,i))})),s=r}return s}}(h)),S.timestamp=y,et(null==s?void 0:s.timestamp)||(S.properties.$event_time_override_provided=!0,S.properties.$event_time_override_system_time=m),w&&(S.properties=function(e,t){void 0===t&&(t=[]);var i={},s=t=>{void 0!==e[t]&&(i[t]=e[t])};return Is.forEach(s),t.forEach(s),i}(S.properties,Pl)),e===$o||e===Oo){var D=null==t?void 0:t.$survey_id,q=null==t?void 0:t.$survey_iteration;ll({id:D,current_iteration:q}),S.$set=i({},S.$set,{[(A={id:D,current_iteration:q},L=e===Oo?"responded":"dismissed",M="$survey_"+L+"/"+A.id,A.current_iteration&&A.current_iteration>0&&(M="$survey_"+L+"/"+A.id+"/"+A.current_iteration),M)]:!0})}else e===Mo&&(S.$set=i({},S.$set,{$survey_last_seen_date:(new Date).toISOString()}));if("product tour shown"===e){var H=null==t?void 0:t.$product_tour_type;H&&(S.$set=i({},S.$set,{["$product_tour_last_seen_date/"+H]:(new Date).toISOString()}))}var N=i({},S.properties.$set,S.$set);if(Xe(N)||this.setPersonPropertiesForFlags(N),!rt(this.config.before_send)){var z=this._runBeforeSend(S);if(!z)return;(S=z).uuid=zi(S.uuid,Cr)}var j=null!==(o=null==(a=S.$set)?void 0:a[c])&&void 0!==o?o:Ze(null==(l=S.properties)?void 0:l.$set)?S.properties.$set[c]:void 0,V=null!=T&&T.pending&&j===T.value?T.value:void 0;this._internalEventEmitter.emit("eventCaptured",S);var U=null!==(u=null==s?void 0:s._url)&&void 0!==u?u:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),W=i({method:"POST",url:U,data:S,compression:"best-available",timestampMode:"recordings"===(null==s?void 0:s._batchKey)||/\/s\/(?:\?|$)/.test(U)?"body":"capture-body",batchKey:null==s?void 0:s._batchKey},null!=s&&s.transport?{transport:s.transport}:{},V?{fireCallbackOnDrop:!0,callback:e=>{e.statusCode>=200&&300>e.statusCode&&this._markFacebookClickIdDelivered(V)}}:{});return!this.config.request_batching||s&&(null==s||!s._batchKey)||null!=s&&s.send_instantly||V?this._send_retriable_request(W):this._requestQueue.enqueue(W),S}rr.critical("This capture call is ignored due to client rate limiting.")}}else rr.error("No event name provided to posthog.capture")}else rr.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",(t=>e(t.event,t)))}getExtension(e){var t;return null==(t=this._browserClientAdapter)?void 0:t.getExtension(e)}_getBrowserClientAdapter(){var e;return null!==(e=this._browserClientAdapter)&&void 0!==e?e:this._browserClientAdapter=new fl(this)}_registerExtensionEventProperties(e){this._extensionEventPropertyProducers.push(e);var t=!0;return()=>{if(t){t=!1;var i=this._extensionEventPropertyProducers.indexOf(e);-1!==i&&this._extensionEventPropertyProducers.splice(i,1)}}}_processCookieIdentityChange(e){var t,i,s;return void 0===e&&(e=!0),!(null==(t=this.persistence)||!t.consumeCookieIdentityChange())&&(this._cachedPersonProperties=null,this.persistence.get_property(ee)===ge&&(null==(s=this.sessionPersistence)||s.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),null==(i=this.featureFlags)||i.reset(),e&&this.reloadFeatureFlags(),!0)}calculateEventProperties(e,t,s,n,o){if(s=s||new Date,!this.persistence||!this.sessionPersistence)return t;this.persistence.syncCookieProperties(),this._processCookieIdentityChange();var a=o?void 0:this.persistence.remove_event_timer(e),l=i({},t);if(l.token=this.config.token,l.$config_defaults=this.config.defaults,this._inCookielessMode()&&(l[le]=!0),"$snapshot"===e){var u=i({},this.persistence.properties(),this.sessionPersistence.properties());return l.distinct_id=u.distinct_id,(!tt(l.distinct_id)&&!nt(l.distinct_id)||it(l.distinct_id))&&rr.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}var c,d=function(e,t,i,s){var n,o,a,l;if(void 0===s&&(s=!1),!Le)return{};var u,c=e?[...ro,...t||[]]:[],d=Fi(Le),h=d[0],_=d[1],p=null!=(u="u">typeof navigator?navigator:void 0)&&u.brave?{brave:!0}:{},g={};et(i)||(g.detectGoogleSearchApp=i);var v={},f=null==(n=navigator)||null==(n=n.userAgentData)?void 0:n.platform,m=null==(o=navigator)?void 0:o.maxTouchPoints,y=null==ke||null==(a=ke.screen)?void 0:a.width,b=null==ke||null==(l=ke.screen)?void 0:l.height,S=null==ke?void 0:ke.devicePixelRatio;et(f)||(v.userAgentDataPlatform=f),et(m)||(v.maxTouchPoints=m),et(y)||(v.screenWidth=y),et(b)||(v.screenHeight=b),et(S)||(v.devicePixelRatio=S);var w,C,k,E,x,P,F,I,T=lr(hr({$os:h,$os_version:_,$browser:ki(Le,navigator.vendor,p,g),$device:Ii(Le),$device_type:(C=Le,k=v,I=Ii(C),I===xt||I===Et||"Kobo"===I||"Kindle Fire"===I||I===ii?kt:I===Ut||I===Gt||I===Wt||I===Xt?"Console":I===Ft?"Wearable":I?St:"Android"===(null==k?void 0:k.userAgentDataPlatform)&&(null!==(E=null==k?void 0:k.maxTouchPoints)&&void 0!==E?E:0)>0?600>Math.min(null!==(x=null==k?void 0:k.screenWidth)&&void 0!==x?x:0,null!==(P=null==k?void 0:k.screenHeight)&&void 0!==P?P:0)/(null!==(F=null==k?void 0:k.devicePixelRatio)&&void 0!==F?F:1)?St:kt:"Desktop"),$timezone:fo(),$timezone_offset:mo()}),{$current_url:Xn(s?Vi(null==Fe?void 0:Fe.href):null==Fe?void 0:Fe.href,c,oo),$host:null==Fe?void 0:Fe.host,$pathname:null==Fe?void 0:Fe.pathname,$raw_user_agent:Le.length>1e3?Le.substring(0,997)+"...":Le,$browser_version:xi(Le,navigator.vendor,p,g),$browser_language:ho(),$browser_language_prefix:(w=ho(),"string"==typeof w?w.split("-")[0]:void 0),$screen_height:null==ke?void 0:ke.screen.height,$screen_width:null==ke?void 0:ke.screen.width,$viewport_height:null==ke?void 0:ke.innerHeight,$viewport_width:null==ke?void 0:ke.innerWidth,$lib:r.LIB_NAME,$lib_version:r.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return r.SDK_DIST_CHANNEL&&(T.$sdk_dist_channel=r.SDK_DIST_CHANNEL),T}(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){var h=this.sessionManager.checkAndGetSessionAndWindowId(o,s.getTime(),!0),_=h.windowId;l.$session_id=h.sessionId,l.$window_id=_}this.sessionPropsManager&&lr(l,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&lr(l,this.sessionRecording.sdkDebugProperties),l.$sdk_debug_retry_queue_size=null==(p=this._retryQueue)?void 0:p.length}catch(e){l.$sdk_debug_error_capturing_properties=String(e)}if(this.requestRouter.region===tl&&(l.$lib_custom_api_host=this.config.api_host),c=e!==be||o?e!==Se||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(s):this.pageViewManager.doPageView(s,n),l=lr(l,c),e===be&&Pe&&(l.title=Pe.title),!et(a)){var g=s.getTime()-a;l.$duration=parseFloat((g/1e3).toFixed(3))}Le&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser");var v=this.persistence.properties(),f=this.sessionPersistence.properties(),m=l.$groups,y=v.$groups;Ze(m)&&!Xe(m)&&(l.$groups=i({},Ze(y)?y:{},m)),ar(["$referrer","$referring_domain"],(e=>{e in v&&delete f[e]}));var b={};if(this._extensionEventPropertyProducers.length>0)for(var S of this._extensionEventPropertyProducers.slice())try{lr(b,S())}catch(e){rr.error("Failed to produce browser extension event properties",e)}(l=lr({},d,v,f,i({},b,l))).$is_identified=this._isIdentified(),Je(this.config.property_denylist)?ar(this.config.property_denylist,(function(e){delete l[e]})):rr.error(kl+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(rr.error(Cl),l=w(l,e));var C=this._hasPersonProcessing();return l.$process_person_profile=C,C&&!o&&this._requirePersonProcessing("_calculate_event_properties"),l}_calculate_set_once_properties(e,t,i){var s;if(void 0===t&&(t=!0),void 0===i&&(i=!1),!this.persistence||!this._hasPersonProcessing())return e;if(this._personProcessingSetOncePropertiesSent&&!i)return e;var r=this.persistence.get_initial_props(),n=null==(s=this.sessionPropsManager)?void 0:s.getSetOnceProps(),o=lr({},r,n||{},e||{}),a=this.config.sanitize_properties;return a&&(rr.error(Cl),o=a(o,"$set_once")),t&&(this._personProcessingSetOncePropertiesSent=!0),Xe(o)?void 0:o}register(e,t){var i;null==(i=this.persistence)||i.register(e,t)}register_once(e,t,i){var s;null==(s=this.persistence)||s.register_once(e,t,i)}register_for_session(e){var t,i;null==(t=this.persistence)||t.syncCookieProperties(),this._processCookieIdentityChange(),null==(i=this.sessionPersistence)||i.register(e),Object.keys(e).forEach((e=>this._sessionRegisteredPropKeys.add(e))),this._persistSessionRegisteredPropKeys()}unregister(e){var t;null==(t=this.persistence)||t.unregister(e)}unregister_for_session(e){var t;null==(t=this.sessionPersistence)||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)||t.unregister(e)})),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()}_persistSessionRegisteredPropKeys(){var e;if(this._sessionRegisteredPropertiesStorageKey)if("memory"===this.config.persistence||null!=(e=this.sessionPersistence)&&e._disabled||!Vr._is_supported())Vr._remove(this._sessionRegisteredPropertiesStorageKey);else{var t=[];this._sessionRegisteredPropKeys.forEach((e=>t.push(e))),t.length>0?Vr._set(this._sessionRegisteredPropertiesStorageKey,t):Vr._remove(this._sessionRegisteredPropertiesStorageKey)}}getFeatureFlag(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlag(e,t)}getFeatureFlagPayload(e){var t;return null==(t=this.featureFlags)?void 0:t.getFeatureFlagPayload(e)}getFeatureFlagResult(e,t){var i;return null==(i=this.featureFlags)?void 0:i.getFeatureFlagResult(e,t)}getAllFeatureFlags(){var e,t;return null!==(e=null==(t=this.featureFlags)?void 0:t.getAllFeatureFlags())&&void 0!==e?e:[]}isFeatureEnabled(e,t){var i,s;return null!==(i=null==(s=this.featureFlags)?void 0:s.isFeatureEnabled(e,t))&&void 0!==i?i:null==t?void 0:t.defaultValue}reloadFeatureFlags(){var e;null==(e=this.featureFlags)||e.reloadFeatureFlags()}updateFlags(e,t,i){var s;null==(s=this.featureFlags)||s.updateFlags(e,t,i)}updateEarlyAccessFeatureEnrollment(e,t,i){var s;null==(s=this.featureFlags)||s.updateEarlyAccessFeatureEnrollment(e,t,i)}getEarlyAccessFeatures(e,t,i){var s;return void 0===t&&(t=!1),null==(s=this.featureFlags)?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:wl}),()=>{})}onSessionId(e){var t,i;return null!==(t=null==(i=this.sessionManager)?void 0:i.onSessionId(e))&&void 0!==t?t:()=>{}}getSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getSurveys(e,t):e([],{isLoaded:!1,error:wl})}getActiveMatchingSurveys(e,t){void 0===t&&(t=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,t):e([],{isLoaded:!1,error:wl})}renderSurvey(e,t){var i;null==(i=this.surveys)||i.renderSurvey(e,t)}displaySurvey(e,t){var i;void 0===t&&(t=cl),null==(i=this.surveys)||i.displaySurvey(e,t)}cancelPendingSurvey(e){var t;null==(t=this.surveys)||t.cancelPendingSurvey(e)}canRenderSurvey(e){var t,i;return null!==(t=null==(i=this.surveys)?void 0:i.canRenderSurvey(e))&&void 0!==t?t:{visible:!1,disabledReason:wl}}canRenderSurveyAsync(e,t){var i,s;return void 0===t&&(t=!1),null!==(i=null==(s=this.surveys)?void 0:s.canRenderSurveyAsync(e,t))&&void 0!==i?i:Promise.resolve({visible:!1,disabledReason:wl})}_validateIdentifyId(e){return!e||it(e)?(rr.critical("Unique user id has not been set in posthog.identify"),!1):e===ae?(rr.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())||(rr.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 rr.uninitializedWarning("posthog.identify");if(nt(e)&&(e=e.toString(),rr.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)&&this._requirePersonProcessing("posthog.identify")){this._healCookielessSentinelDistinctId();var s=this.get_distinct_id(),r=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==s,n=this._processCookieIdentityChange(!1),o=this.persistence._beginCookieSyncSuppression(),l=!1;try{var c=this.get_distinct_id();this.register({$user_id:e}),this.get_property(a)||this.register_once({$had_persisted_distinct_id:!0,$device_id:c},""),e!==c&&e!==this.get_property(u)&&(this.unregister(u),this.register({distinct_id:e}));var d=(this.persistence.get_property(ee)||ge)===ge,h=e!==c,_=!h&&d;if(h&&d){var p,g=this.config.reuseAnonymousId?{distinct_id:e}:{distinct_id:e,$anon_distinct_id:c};this.persistence.set_property(ee,ve),this.setPersonPropertiesForFlags({$set:t||{},$set_once:i||{}},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture(we,g,{$set:t||{},$set_once:i||{}}),this._cachedPersonProperties=el(e,t,i),null==(p=this.featureFlags)||p.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:c)}else if(_){this.persistence.set_property(ee,ve);var v=t||{},f=i||{};this.setPersonPropertiesForFlags({$set:v,$set_once:f},!1),this.config.cookieWinsOnConflict&&this.persistence._publishSuppressedCookieSnapshot(),this.capture("$set",{$set:v,$set_once:f}),this._cachedPersonProperties=el(e,t,i)}else(t||i)&&this.setPersonProperties(t,i);h||r||n?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(J)):_&&(t||i)&&this.reloadFeatureFlags(),l=!0}finally{o&&this.persistence._endCookieSyncSuppression(l)}}}setPersonProperties(e,t){if((e||t)&&this._requirePersonProcessing("posthog.setPersonProperties")){var i=el(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):rr.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var t,i=(Je(e)?e:[e]).filter((e=>tt(e)&&e.length>0));0!==i.length&&this._requirePersonProcessing("posthog.unsetPersonProperties")&&(null==(t=this.featureFlags)||t.unsetPersonPropertiesForFlags(i,!0),this.capture("$set",{$unset:i}),this._cachedPersonProperties=null)}group(e,t,s){var r;if(e&&t){null==(r=this.persistence)||r.syncCookieProperties(),this._processCookieIdentityChange();var n=this.getGroups(),o=n[e]!==t;if(o&&this.resetGroupPropertiesForFlags(e),this.register({$groups:i({},n,{[e]:t})}),(o||s)&&this._hasPersonProcessing()){var a={$group_type:e,$group_key:t};s&&(a.$group_set=s),this.capture(Ce,a)}s&&this.setGroupPropertiesForFlags({[e]:s}),o&&!s&&this.reloadFeatureFlags()}else rr.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),null==(i=this.featureFlags)||i.setPersonPropertiesForFlags(e,t)}resetPersonPropertiesForFlags(e){var t;void 0===e&&(e=!0),null==(t=this.featureFlags)||t.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,t){var i;void 0===t&&(t=!0),this._requirePersonProcessing("posthog.setGroupPropertiesForFlags")&&(null==(i=this.featureFlags)||i.setGroupPropertiesForFlags(e,t))}resetGroupPropertiesForFlags(e){var t;null==(t=this.featureFlags)||t.resetGroupPropertiesForFlags(e)}reset(e){var t=at(e)?e:null==e?void 0:e.resetDeviceID,i=at(e)||null==e?void 0:e.bootstrap;this._reset(t,!1,i)}_reset(e,t,s){var r,n,o;if(void 0===t&&(t=!1),rr.info("reset"),!this.__loaded)return rr.uninitializedWarning("posthog.reset");var u=null==s?void 0:s.sessionID;this.config.bootstrap=s||(null==(r=this._originalUserConfig)?void 0:r.bootstrap)||{},null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags());var c=this.get_property(a),d=this.get_property(l),h=this.get_property(C),_=this.is_capturing();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.");var p=null==(o=this.persistence)||null==o._beginCookieSyncSuppression?void 0:o._beginCookieSyncSuppression(),g=!1;try{var v,f,m,y,b,S,w,k,E,x,P,F,I;if(null==(v=this.persistence)||v.clear(),null==(f=this.sessionPersistence)||f.clear(),this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys(),et(h)||null==(x=this.persistence)||x.register({[C]:h}),null==(m=this.surveys)||m.reset(),null==(y=this.featureFlags)||y.reset(),null==(b=this.conversations)||b.reset(),null==(S=this.logs)||S.reset(),null==(w=this.metrics)||w.reset(),null==(k=this.persistence)||k.set_property(ee,ge),null==(E=this.sessionManager)||E.resetSessionId(),this._cachedPersonProperties=null,this.config.cookieless_mode===pe)this.register_once({distinct_id:ae,$device_id:null},"");else{var T=this.config.get_device_id(Cr());this.register_once({distinct_id:T,$device_id:e?T:c},""),e||et(d)||this.register({[l]:d})}if(this.register({$last_posthog_reset:(new Date).toISOString()},1),s)if(void 0===s.distinctID||this._inCookielessMode()||(null==(I=this.persistence)||I.set_property(ee,s.isIdentifiedID?ve:ge),this.register({distinct_id:s.distinctID})),null==(P=this.featureFlags)||P.initialize(),!(et(u)||null!=(F=this.sessionManager)&&F.setBootstrapSessionId(u,!0))){var R=i({},s);delete R.sessionID,this.config.bootstrap=R}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,g=!0}finally{var A;p&&(null==(A=this.persistence)||null==A._endCookieSyncSuppression||A._endCookieSyncSuppression(g))}this.reloadFeatureFlags()}shutdown(e){var i=this;return t((function*(){var e,t,s,r,n,o,a;if(i.__loaded){i._getBrowserClientAdapter().dispose(),null==(e=i.sessionRecording)||e.dispose(),null==(t=i.logs)||t.flushLogs("sendBeacon"),null==(s=i.metrics)||s.flush("sendBeacon"),null==(r=i._requestQueue)||r.unload(),null==(n=i._retryQueue)||n.unload();try{var l;null==(l=i.featureFlags)||l.destroy()}catch(e){rr.error("Error while destroying feature flags",e)}null==(o=i.persistence)||o.destroy(),null==(a=i.sessionPersistence)||a.destroy()}else rr.uninitializedWarning("posthog.shutdown")}))()}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)||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)||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.checkAndGetSessionAndWindowId(!0).sessionId)&&void 0!==e?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var t=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=t.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+t.sessionId);if(null!=e&&e.withTimestamp&&i){var r,n=null!==(r=e.timestampLookBack)&&void 0!==r?r:10;if(!i)return s;s+="?t="+Math.max(Math.floor(((new Date).getTime()-i)/1e3)-n,0)}return s}alias(e,t){return e===this.get_property(n)?(rr.critical("Attempting to create alias for existing People user - aborting."),-2):this._requirePersonProcessing("posthog.alias")?(et(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(u,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(rr.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var t=i({},this.config);if(Ze(e)){var s,n,o,a,l,u,c,d,h,_,p,g;lr(this.config,Ll(e));var v=this._is_persistence_disabled();null==(s=this.persistence)||s.update_config(this.config,t,v),this.sessionPersistence="sessionStorage"===this.config.persistence||"memory"===this.config.persistence?this.persistence:new Io(i({},this.config,{persistence:"sessionStorage"}),v,!1);var f,m=this._checkLocalStorageForDebug(this.config.debug);at(m)&&(this.config.debug=m),at(this.config.debug)&&(this.config.debug?(r.DEBUG=!0,Tr._is_supported()&&Tr._set("ph_debug",!0),rr.info("set_config",{config:e,oldConfig:t,newConfig:i({},this.config)})):(r.DEBUG=!1,Tr._is_supported()&&Tr._remove("ph_debug"))),null==(n=this.featureFlags)||null==n.updateConfig||n.updateConfig(this.config,this._shouldDisableFlags()),null==(o=this.exceptionObserver)||o.onConfigChange(),null==(a=this.exceptions)||a.onConfigChange(),null==(l=this.sessionRecording)||l.startIfEnabledOrStop(),null==(u=this.tracingHeaders)||u.startIfEnabledOrStop(),null==(c=this.autocapture)||c.startIfEnabled(),null==(d=this.heatmaps)||d.startIfEnabled(),("capture_pageview"in e||"disable_capture_url_hashes"in e)&&(null==(f=this.historyAutocapture)||f.startIfEnabledOrStop()),null==(h=this.exceptionObserver)||h.startIfEnabledOrStop(),null==(_=this.deadClicksAutocapture)||_.startIfEnabledOrStop(),null==(p=this.surveys)||p.loadIfEnabled(),this._sync_opt_out_with_persistence(),null==(g=this.externalIntegrations)||g.startIfEnabledOrStop(),!t.segment&&this.config.segment&&this.persistence&&Nn(this,bl,!1)}}_overrideSDKInfo(e,t){r.LIB_NAME=e,r.LIB_VERSION=t}startSessionRecording(e){var t,i,s,r,n,o=!0===e,a={sampling:o||!(null==e||!e.sampling),linked_flag:o||!(null==e||!e.linked_flag),url_trigger:o||!(null==e||!e.url_trigger),event_trigger:o||!(null==e||!e.event_trigger)};Object.values(a).some(Boolean)&&(null==(t=this.sessionManager)||t.checkAndGetSessionAndWindowId(),a.sampling&&(null==(i=this.sessionRecording)||i.overrideSampling()),a.linked_flag&&(null==(s=this.sessionRecording)||s.overrideLinkedFlag()),a.url_trigger&&(null==(r=this.sessionRecording)||r.overrideTrigger("url")),a.event_trigger&&(null==(n=this.sessionRecording)||n.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)||!e.started)}captureException(e,t){try{if(!this.exceptions)return;var s=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:s});return this.exceptions.sendExceptionEvent(i({},r,t))}catch(e){return}}addExceptionStep(e,t){var i;null==(i=this.exceptions)||i.addExceptionStep(e,t)}captureLog(e){var t;null==(t=this.logs)||t.captureLog(e)}get logger(){var e,t;return null!==(e=null==(t=this.logs)?void 0:t.logger)&&void 0!==e?e:$l._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.loadToolbar(e))&&void 0!==t&&t}get_property(e){var t;return null==(t=this.persistence)?void 0:t.props[e]}getSessionProperty(e){var t;return null==(t=this.sessionPersistence)?void 0:t.props[e]}toString(){var e,t=null!==(e=this.config.name)&&void 0!==e?e:Fl;return t!==Fl&&(t=Fl+"."+t),t}_isIdentified(){var e,t;return(null==(e=this.persistence)?void 0:e.get_property(ee))===ve||(null==(t=this.sessionPersistence)?void 0:t.get_property(ee))===ve}_hasPersonProcessing(){var e,t;return!("never"===this.config.person_profiles||this.config.person_profiles===fe&&!this._isIdentified()&&Xe(this.getGroups())&&(null==(e=this.persistence)||null==(e=e.props)||!e[u])&&(null==(t=this.persistence)||null==(t=t.props)||!t[oe]))}_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?(rr.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this._warnIfVolatileIdentityWithoutStableId(),this._register_single(oe,!0),!0)}_is_persistence_disabled(){if("always"===this.config.cookieless_mode)return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==_e)}_sync_opt_out_with_persistence(){var e,t,i,s,r,n=this._is_persistence_disabled();return this.is_capturing()||null==(i=this.logs)||i._onOptOut(),(null==(e=this.persistence)?void 0:e._disabled)!==n&&(null==(s=this.persistence)||s.set_disabled(n)),(null==(t=this.sessionPersistence)?void 0:t._disabled)!==n&&(null==(r=this.sessionPersistence)||r.set_disabled(n)),n&&(this._sessionRegisteredPropKeys.clear(),this._persistSessionRegisteredPropKeys()),n}opt_in_capturing(e){var t;if(this.config.cookieless_mode!==pe){if(this._inCookielessMode()){var i,s,r,n,o,a;null==(i=this.sessionRecording)||i.dispose({discardBufferedEvents:!0}),this._reset(!0,!0),null==(s=this.sessionManager)||s.destroy(),null==(r=this.pageViewManager)||r.destroy(),this.sessionManager=new Wa(this),this.pageViewManager=new Un(this),this.persistence&&(this.sessionPropsManager=new za(this,this.sessionManager,this.persistence));var l,u=null!==(n=null==(o=this.config.__extensionClasses)?void 0:o.sessionRecording)&&void 0!==n?n:null==(a=$l.__defaultExtensionClasses)?void 0:a.sessionRecording;u&&(this.sessionRecording=this._replaceExtension(this.sessionRecording,new u(this)),this._lastRemoteConfig&&(null==(l=this.sessionRecording)||null==l.onRemoteConfig||l.onRemoteConfig(this._lastRemoteConfig)))}var c,d;this.consent.optInOut(!0),this._sync_opt_out_with_persistence(),this._start_queue_if_opted_in(),null==(t=this.sessionRecording)||t.startIfEnabledOrStop(),this.config.cookieless_mode==_e&&(null==(c=this.surveys)||c.loadIfEnabled()),(et(null==e?void 0:e.captureEventName)||null!=e&&e.captureEventName)&&this.capture(null!==(d=null==e?void 0:e.captureEventName)&&void 0!==d?d:"$opt_in",null==e?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this._captureInitialPageview()}else rr.warn(Sl)}opt_out_capturing(){if(this.config.cookieless_mode!==pe){var e,t,i=this.config.cookieless_mode===_e?this.sessionRecording:void 0;null==i||i.dispose({discardBufferedEvents:!0}),this.config.cookieless_mode===_e&&this.consent.isOptedIn()&&this._reset(!0,!0),this.consent.optInOut(!1),this._sync_opt_out_with_persistence(),this.config.cookieless_mode===_e&&(this.register({distinct_id:ae,$device_id:null}),this._removeExtension(i),this.sessionRecording=void 0,null==(e=this.sessionManager)||e.destroy(),null==(t=this.pageViewManager)||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this._captureInitialPageview(),this._start_queue_if_opted_in())}else rr.warn(Sl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return 1===e?"granted":0===e?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===pe||(this.config.cookieless_mode===_e?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 xe?Ga(xe,this.config.custom_blocked_useragents):void 0}_captureInitialPageview(){Pe&&("visible"===Pe.visibilityState?this._initialPageviewCaptured||(this._initialPageviewCaptured=!0,this.capture(be,{title:Pe.title},{send_instantly:!0}),this._visibilityStateListener&&(Pe.removeEventListener(me,this._visibilityStateListener),this._visibilityStateListener=null)):this._visibilityStateListener||(this._visibilityStateListener=this._captureInitialPageview.bind(this),gr(Pe,me,this._visibilityStateListener)))}debug(e){!1===e?(null==ke||ke.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(null==ke||ke.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(){var 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?(rr.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(e,t,i,s,r){var n=t in e&&!rt(e[t]),o=i in e&&!rt(e[i]);return n?e[t]:!!o&&(r&&r.warn("Config field '"+i+"' is deprecated. Please use '"+t+"' instead. The old field will be removed in a future major version."),e[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,rr)}_runBeforeSend(e){var t;if(rt(this.config.before_send))return e;var i=Object.keys(null!==(t=e.properties)&&void 0!==t?t:{}).filter(ct),s=Je(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var n of s)try{if(r=n(r),rt(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return ut(e.event)?rr.warn(o+". This can cause unexpected behavior."):rr.info(o),null}r.properties&&!Xe(r.properties)||rr.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}catch(t){return rr.error("Error in beforeSend function for event '"+e.event+"':",t),null}for(var a of i)if(r.properties&&rt(r.properties[a]))return rr.warn("Event '"+e.event+"' had its '"+a+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return r}getPageViewId(){var e;return null==(e=this.pageViewManager._currentPageview)?void 0:e.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){var t=at(e)&&!e,i=Tr._is_supported()&&"true"===Tr._get("ph_debug");return!t&&(!!i||e)}}$l.__defaultExtensionClasses={},$l._noopLogger=(()=>{var e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),function(e,t){for(var i=0;t.length>i;i++)e.prototype[t[i]]=dr(e.prototype[t[i]])}($l,["identify"]);class Ol{constructor(e){this.disabled=!1===e;var t=Ze(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;var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(t-s.y)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}}var Dl="$copy_autocapture",Bl=nr("[AutoCapture]");function ql(e,t){return t.length>e?t.slice(0,e)+"...":t}function Hl(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do{t=t.previousSibling}while(t&&!Zr(t));return t}function Nl(e,t){var s,r,n=t.e,o=t.maskAllElementAttributes,a=t.maskAllText,l=t.elementAttributeIgnoreList,u=t.elementsChainAsString,c=t.disableCaptureUrlHashes;if(!Zr(e))return{props:{}};for(var d=[e],h=new Set([e]),_=e;_.parentNode&&!Xr(_,"body")&&sn>d.length;)if(tn(_.parentNode)){var p=_.parentNode.host;if(h.has(p))break;h.add(p),d.push(p),_=p}else{if(!Zr(_.parentNode))break;if(h.has(_.parentNode))break;h.add(_.parentNode),d.push(_.parentNode),_=_.parentNode}var g,v,f=[],m={},y=!1,b=!1;if(ar(d,(e=>{var t=wn(e);if(Xr(e,"a")){var i=e.getAttribute("href");y=!!(t&&i&&Rn(i))&&(c?Vi(i):i)}qe(on(e),"ph-no-capture")&&(b=!0),f.push(function(e,t,i,s,r){void 0===r&&(r=!1);var n=e.tagName.toLowerCase(),o={tag_name:n};cn.indexOf(n)>-1&&!i&&(o.$el_text="a"===n.toLowerCase()||"button"===n.toLowerCase()?ql(1024,An(e)):ql(1024,ln(e)));var a=on(e);a.length>0&&(o.classes=a.filter((function(e){return""!==e}))),ar(e.attributes,(function(i){var n;if((!Cn(e)||-1!==["name","id","class","aria-label"].indexOf(i.name))&&(null==s||!s.includes(i.name))&&!t&&Rn(i.value)&&(!tt(n=i.name)||"_ngcontent"!==n.substring(0,10)&&"_nghost"!==n.substring(0,7))){var a=i.value;"class"===i.name&&(a=rn(a).join(" ")),o["attr__"+i.name]=ql(1024,"href"===i.name&&r?Vi(a):a)}}));for(var l=1,u=1,c=e;c=Hl(c);)l++,c.tagName===e.tagName&&u++;return o.nth_child=l,o.nth_of_type=u,o}(e,o,a,l,c));var s=function(e){if(!wn(e))return{};var t={};return ar(e.attributes,(function(e){if(e.name&&0===e.name.indexOf("data-ph-capture-attribute")){var i=e.name.replace("data-ph-capture-attribute-",""),s=e.value;i&&s&&Rn(s)&&(t[i]=s)}})),t}(e);ar(s,((e,t)=>{({}).hasOwnProperty.call(m,t)||(m[t]=e)}))})),b)return{props:{},explicitNoCapture:b};if(a||(f[0].$el_text=Xr(e,"a")||Xr(e,"button")?An(e):ln(e)),y){var S,w;f[0].attr__href=y;var C=null==(S=Yn(y))?void 0:S.host,k=null==ke||null==(w=ke.location)?void 0:w.host;C&&k&&C!==k&&(g=y)}return{props:lr({$event_type:n.type,$ce_version:1},u?{}:{$elements:f},{$elements_chain:(v=f,Je(v)?function(e){return e.map((e=>{var t,s,r="";if(e.tag_name&&(r+=e.tag_name),e.attr_class)for(var n of(e.attr_class.sort(),e.attr_class))r+="."+n.replace(/"/g,"");var o=i({},e.text?{text:e.text}:{},{"nth-child":null!==(t=e.nth_child)&&void 0!==t?t:0,"nth-of-type":null!==(s=e.nth_of_type)&&void 0!==s?s:0},e.href?{href:e.href}:{},e.attr_id?{attr_id:e.attr_id}:{},e.attributes),a={};return ur(o).sort(((e,t)=>{return(s=t[0])>(i=e[0])?-1:i>s?1:0;var i,s})).forEach((e=>{var t=e[1];return a[Mn(e[0].toString())]=Mn(t.toString())})),(r+=":")+ur(a).map((e=>e[0]+'="'+e[1]+'"')).join("")})).join(";")}(function(e){return e.map((e=>{var t,i,s={text:null==(t=e.$el_text)?void 0:t.slice(0,400),tag_name:e.tag_name,href:null==(i=e.attr__href)?void 0:i.slice(0,2048),attr_class:$n(e),attr_id:e.attr__id,nth_child:e.nth_child,nth_of_type:e.nth_of_type,attributes:{}};return ur(e).filter((e=>0===e[0].indexOf("attr__"))).forEach((e=>s.attributes[e[0]]=e[1])),s}))}(v)):"")},null!=(s=f[0])&&s.$el_text?{$el_text:null==(r=f[0])?void 0:r.$el_text}:{},g&&"click"===n.type?{$external_click_url:g}:{},m)}}class zl{constructor(e){this.name="autocapture",this._initialized=!1,this._isDisabledServerSide=null,this._hasReceivedConfigResponse=!1,this._elementsChainAsString=!1,this._config={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this._disposed=!1,this._configSource=e,this._configSource.refresh(this._config),this.rageclicks=new Ol(this._config.rageclick),this._elementSelectors=null}setup(e){this._compileUrlPatterns(),this._client=e;var 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)||e.dispose(),this._remoteConfigSubscription=void 0,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.map((e=>new RegExp(e))),this._config.url_ignorelist=null==(t=this._config.url_ignorelist)?void 0:t.map((e=>new RegExp(e))),this._config}_addDomEventHandlers(){if(this.isBrowserSupported()){if(ke&&Pe){var e=this._domEventHandler=e=>{e=e||(null==ke?void 0:ke.event);try{this._captureEvent(e)}catch(e){Bl.error("Failed to capture event",e)}};if(gr(Pe,"submit",e,{capture:!0}),gr(Pe,"change",e,{capture:!0}),gr(Pe,"click",e,{capture:!0}),this._refreshConfig().capture_copied_text){var t=this._copiedTextHandler=e=>{e=e||(null==ke?void 0:ke.event);try{this._captureEvent(e,Dl)}catch(e){Bl.error("Failed to capture clipboard event",e)}};gr(Pe,"copy",t,{capture:!0}),gr(Pe,"cut",t,{capture:!0}),gr(Pe,"paste",t,{capture:!0})}}}else Bl.info("Disabling Automatic Event Collection because this browser is not supported")}_removeDomEventHandlers(){this._domEventHandler&&(null==Pe||Pe.removeEventListener("submit",this._domEventHandler,!0),null==Pe||Pe.removeEventListener("change",this._domEventHandler,!0),null==Pe||Pe.removeEventListener("click",this._domEventHandler,!0),this._domEventHandler=void 0),this._copiedTextHandler&&(null==Pe||Pe.removeEventListener("copy",this._copiedTextHandler,!0),null==Pe||Pe.removeEventListener("cut",this._copiedTextHandler,!0),null==Pe||Pe.removeEventListener("paste",this._copiedTextHandler,!0),this._copiedTextHandler=void 0),this._initialized=!1}startIfEnabled(){!this._disposed&&this._client&&this.isEnabled&&!this._initialized&&(this._addDomEventHandlers(),this._initialized=!0)}onRemoteConfig(e){if(!this._disposed)if(this._hasReceivedConfigResponse=!0,e.ok){var t=e.config;t.elementsChainAsString&&(this._elementsChainAsString=t.elementsChainAsString);var i,s=t.autocapture_opt_out;at(s)&&(null==(i=this._client)||i.kv.set(_,s),this._isDisabledServerSide=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(e){this._elementSelectors=e}getElementSelectors(e){var t,i=[];return null==(t=this._elementSelectors)||t.forEach((t=>{var s=null==Pe?void 0:Pe.querySelectorAll(t);null==s||s.forEach((s=>{e===s&&i.push(t)}))})),i}get isEnabled(){var e,t;if(this._disposed)return!1;var i=null==(e=this._client)?void 0:e.kv.get(_),s=this._isDisabledServerSide,r=this._refreshConfig(),n=r.remoteRequestsDisabled&&!this._hasReceivedConfigResponse;if(st(s)&&!at(i)&&!n)return!1;var o=null!==(t=this._isDisabledServerSide)&&void 0!==t?t:!!i;return!!r.enabled&&!o}_captureEvent(e,t){if(void 0===t&&(t="$autocapture"),this.isEnabled){var s=un(e);en(s)&&(s=s.parentNode||null);var r,n=this._compileUrlPatterns();"$autocapture"===t&&"click"===e.type&&e instanceof MouseEvent&&n.rageclick&&null!=(r=this.rageclicks)&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||(new Date).getTime())&&yn(s,n.rageclick)&&this._captureEvent(e,"$rageclick");var o=t===Dl,a=o?i({},n,{dom_event_allowlist:void 0}):n;if(s&&function(e,t,i,s,r,n){var o;if(!ke||bn(e))return!1;if(null!=i&&i.url_allowlist&&!nn(i.url_allowlist,n))return!1;if(null!=i&&i.url_ignorelist&&nn(i.url_ignorelist,n))return!1;if(null!=i&&i.dom_event_allowlist){var a=i.dom_event_allowlist;if(a&&!a.some((e=>t.type===e)))return!1}var l=Sn(e,s),u=l.parentIsUsefulElement,c=l.targetElementList;if(!function(e,t){var i=null==t?void 0:t.element_allowlist;if(et(i))return!0;var s,r=function(e){if(i.some((t=>e.tagName.toLowerCase()===t)))return{v:!0}};for(var n of e)if(s=r(n))return s.v;return!1}(c,i))return!1;if(!dn(c,null==i?void 0:i.css_selector_allowlist))return!1;if(dn(c,null!==(o=null==i?void 0:i.css_selector_ignorelist)&&void 0!==o?o:_n))return!1;try{var d=ke.getComputedStyle(e);if(d&&"pointer"===d.getPropertyValue("cursor")&&"click"===t.type)return!0}catch(e){}var h=e.tagName.toLowerCase();switch(h){case"html":return!1;case"form":return(r||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(r||["change","click"]).indexOf(t.type)>=0;default:return u?(r||["click"]).indexOf(t.type)>=0:(r||["click"]).indexOf(t.type)>=0&&(cn.indexOf(h)>-1||"true"===e.getAttribute("contenteditable"))}}(s,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:n.getCurrentUrl}})){var l,u=Nl(s,{e:e,maskAllElementAttributes:n.maskAllElementAttributes,maskAllText:n.maskAllText,elementAttributeIgnoreList:n.element_attribute_ignorelist,elementsChainAsString:this._elementsChainAsString,disableCaptureUrlHashes:n.disableCaptureUrlHashes}),c=u.props;if(u.explicitNoCapture)return!1;var d=this.getElementSelectors(s);if(d&&d.length>0&&(c.$element_selectors=d),t===Dl){var h=e.type||"clipboard";if("paste"!==h){var _,p,g=null==ke||null==(_=ke.getSelection())?void 0:_.toString(),v=an(g);if(!v)return!1;c.$selected_content=v,c.$clipboard_text_length=null!==(p=null==g?void 0:g.length)&&void 0!==p?p:0}c.$copy_type=h}return null==(l=this._client)||l.capture(t,c).catch((e=>Bl.error("Failed to capture event",e))),!0}}}isBrowserSupported(){return Ye(null==Pe?void 0:Pe.querySelectorAll)}}class jl{constructor(e){this._instance=e}refresh(e){var t=this._instance.config,i=Ze(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance._shouldDisableFlags(),e.url_allowlist=null==i?void 0:i.url_allowlist,e.url_ignorelist=null==i?void 0:i.url_ignorelist,e.dom_event_allowlist=null==i?void 0:i.dom_event_allowlist,e.element_allowlist=null==i?void 0:i.element_allowlist,e.css_selector_allowlist=null==i?void 0:i.css_selector_allowlist,e.css_selector_ignorelist=null==i?void 0:i.css_selector_ignorelist,e.element_attribute_ignorelist=null==i?void 0:i.element_attribute_ignorelist,e.capture_copied_text=null==i?void 0:i.capture_copied_text}}var Vl=nr("[ExceptionAutocapture]"),Ul=()=>{},Wl=e=>{var t;if(Ye(e))return null!==(t=e.__posthog_layer__)&&void 0!==t?t:e.__rrweb_layer__};function Gl(e,t,i){try{if(!(t in e))return Ul;var s={next:e[t]},r=i((function(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];return s.next.apply(this,t)}));return Ye(r)&&(r.prototype=r.prototype||{},Object.defineProperties(r,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:s}})),e[t]=r,()=>{if(e[t]!==r)for(var i=e[t],n=Wl(i);n;){if(n.next===r)return void(n.next=s.next);n=Wl(i=n.next)}else e[t]=s.next}}catch(e){return Ul}}var Kl=nr("[TracingHeaders]"),Ql=nr("[Web Vitals]"),Jl=9e5,Yl=["CLS","FCP","INP","LCP"],Zl=["INP","LCP"],Xl=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],eu="disabled",tu="lazy_loading",iu="awaiting_config",su="missing_config";nr("[SessionRecording]"),nr("[SessionRecording]");var ru="[SessionRecording]",nu=nr(ru),ou=nr("[Heatmaps]");function au(e){return Ze(e)&&"clientX"in e&&"clientY"in e&&nt(e.clientX)&&nt(e.clientY)}var lu=nr("[Product Tours]"),uu=e=>{var t;return!e.config.disable_product_tours&&!(null==(t=e.persistence)||!t.get_property(b))},cu=["$set_once","$set"],du=nr("[SiteApps]"),hu="Error while initializing PostHog app with config id ",_u=(e,t)=>null!=e&&e.then?e.then(t):t(e),pu="SDK is not enabled or survey functionality is not yet loaded",gu="Disabled. Not loading surveys.";class vu{constructor(e,t){this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this._isInitializingSurveys=!1,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._lastSurveyRefreshFailedAt=null,this._disposed=!1,this._renderTimeouts=new Set,this.onRemoteConfig=e=>{if(!this._disposed&&!this._config.disableSurveys){if(!e.ok)return ol.warn("Remote config unavailable. Not loading surveys.");var t=e.config.surveys;if(rt(t))return ol.warn("Flags not loaded yet. Not loading surveys.");this._isSurveysEnabled=at(t)?t:t.length>0,ol.info("flags response received, isSurveysEnabled: "+this._isSurveysEnabled),this.loadIfEnabled()}},this._configSource=e,this._initialClientState=t}setup(e){if(!this._disposed)return this._initializingClient=e,_u(e.kv.initialize(),(()=>{if(this._initializingClient===e&&!this._disposed){this._initializingClient=void 0,this._client=e;var t=e.onRemoteConfig(this.onRemoteConfig);this._disposed?t.dispose():(this._remoteConfigSubscription=t,this.loadIfEnabled())}}))}dispose(){var e,t,i;this._disposed||(this._disposed=!0,this._initializingClient=void 0,this._client=void 0,null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,null==(t=this._surveyEventReceiver)||t.dispose(),this._surveyEventReceiver=null,null==(i=this._surveyManager)||null==i.dispose||i.dispose(),this._surveyManager=null,this._surveyCallbacks=[],this._getSurveysInFlightPromise=null,this._renderTimeouts.forEach((e=>clearTimeout(e))),this._renderTimeouts.clear())}get _config(){return this._configSource.get()}initialize(){this.loadIfEnabled()}reset(){try{var e;null==(e=this._surveyEventReceiver)||e.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var t=[],i=0;ilocalStorage.removeItem(e)))}catch(e){}}loadIfEnabled(){if(!this._disposed&&this._client){var e=this._config;if(!this._surveyManager)if(this._isInitializingSurveys)ol.info("Already initializing surveys, skipping...");else if(e.disableSurveys)ol.info(gu);else if(e.cookielessMode&&this._configSource.isOptedOut())ol.info("Not loading surveys in cookieless mode without consent.");else{var t=this._configSource.getExtensions();if(t){if(!et(this._isSurveysEnabled)||e.advancedEnableSurveys){var i=this._isSurveysEnabled||e.advancedEnableSurveys;this._isInitializingSurveys=!0;try{var s=t.generateSurveys;if(s)return this._completeSurveyInitialization(s,i),void(this._isInitializingSurveys=!1);var r=t.loadExternalDependency;if(!r)return this._handleSurveyLoadError(he),void(this._isInitializingSurveys=!1);r((e=>{try{if(this._disposed)return;var t=this._configSource.getExtensions();e||null==t||!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}}}else ol.error("PostHog Extensions not found.")}}}_completeSurveyInitialization(e,t){this._disposed||(this._surveyManager=e(t),this._surveyEventReceiver=this._configSource.createEventReceiver(),ol.info("Surveys loaded successfully"),this._notifySurveyCallbacks({isLoaded:!0}))}_handleSurveyLoadError(e,t){ol.error(e,t),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){var i;void 0===t&&(t=!1);var s=null!==(i=this._client)&&void 0!==i?i:this._initialClientState;if(s&&!this._disposed){if(this._config.disableSurveys)return ol.info(gu),e([]);var r=s.kv.get(V);if(r&&!t)return e(r,{isLoaded:!0}),void(this._shouldBackgroundRefreshSurveys()&&this.getSurveys((()=>{}),!0));if(this._getSurveysInFlightPromise)this._getSurveysInFlightPromise.then((t=>{this._disposed||e(t.surveys,t.context)})).catch((e=>ol.error("Error in survey callback",e)));else{var n=this._sendSurveysRequest("/api/surveys/",{method:"GET",query:{token:s.projectToken},sentAt:"query",timeoutMs:this._config.requestTimeoutMs}).then((e=>{try{return this._handleSurveyResponse(s,e)}catch(e){return ol.error("Error processing surveys response",e),this._handleSurveyResponse(s,{statusCode:0,error:e})}}),(e=>this._handleSurveyResponse(s,{statusCode:0,error:e})));this._getSurveysInFlightPromise=n;var o=()=>{this._getSurveysInFlightPromise===n&&(this._getSurveysInFlightPromise=null)};n.then((t=>{o(),this._disposed||e(t.surveys,t.context)}),o).catch((e=>ol.error("Error in survey callback",e)))}}}_sendSurveysRequest(e,t){var i=this._client;return i?i.sendRequest(e,t):new Promise((e=>e({statusCode:0,error:new Error(pu)})))}_handleSurveyResponse(e,t){if(this._disposed)return{surveys:[],context:{isLoaded:!1,error:pu}};var i=t.statusCode;if(200!==i||!t.json){var s="Surveys API could not be loaded, status: "+i;return 0!==i?ol.error(s):t.error||ol.warn(s),this._lastSurveyRefreshFailedAt=Date.now(),{surveys:[],context:{isLoaded:!1,error:s}}}this._lastSurveyRefreshFailedAt=null;var r,n=t.json.surveys||[],o=n.filter((e=>function(e){return!(!e.start_date||e.end_date)}(e)&&(Qa(e)||function(e){var t;return!(null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)||!t.length)}(e))));return o.length>0&&(null==(r=this._surveyEventReceiver)||r.register(o)),e.kv.set({[V]:n,[U]:Date.now()}),{surveys:n,context:{isLoaded:!0}}}_shouldBackgroundRefreshSurveys(){return this._isSurveyCacheStale()&&!this._getSurveysInFlightPromise&&!this._isSurveyRefreshBackingOff()}_isSurveyCacheStale(){var e,t,i=null==(e=null!==(t=this._client)&&void 0!==t?t:this._initialClientState)?void 0:e.kv.get(U);return nt(i)&&Date.now()-i>3e5}_isSurveyRefreshBackingOff(){return nt(this._lastSurveyRefreshFailedAt)&&3e5>Date.now()-this._lastSurveyRefreshFailedAt}markSurveyAsSeen(e,t){var i,s={id:e,current_iteration:null!==(i=null==t?void 0:t.iteration)&&void 0!==i?i:null};ll(s);try{localStorage.setItem("lastSeenSurveyDate",(new Date).toISOString())}catch(e){}}_notifySurveyCallbacks(e){for(var t of this._surveyCallbacks)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(e){ol.error("Error in survey callback",e)}}getActiveMatchingSurveys(e,t){if(void 0===t&&(t=!1),!rt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);ol.warn("init was not called")}_getSurveyById(e){var 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(rt(this._surveyManager))return{eligible:!1,reason:pu};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}_checkSurveyRenderability(e){if(rt(this._surveyManager))return{eligible:!1,reason:pu};var t="string"==typeof e?this._getSurveyById(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(rt(this._surveyManager))return ol.warn("init was not called"),{visible:!1,disabledReason:pu};var t=this._checkSurveyRenderability(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return rt(this._surveyManager)?(ol.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:pu})):new Promise((i=>{this.getSurveys((t=>{var s,r=null!==(s=t.find((t=>t.id===e)))&&void 0!==s?s:null;if(r){var n=this._checkSurveyRenderability(r);i({visible:n.eligible,disabledReason:n.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),t)}))}renderSurvey(e,t,i){var s;if(rt(this._surveyManager))ol.warn("init was not called");else{var r="string"==typeof e?this._getSurveyById(e):e;if(null!=r&&r.id)if(ul.includes(r.type)){var n=null==Pe?void 0:Pe.querySelector(t);if(n)if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds){ol.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds");var o=setTimeout((()=>{var e,t;this._renderTimeouts.delete(o),this._disposed||(ol.info("Rendering survey "+r.id+" with delay of "+(null==(e=r.appearance)?void 0:e.surveyPopupDelaySeconds)+" seconds"),null==(t=this._surveyManager)||t.renderSurvey(r,n,i),ol.info("Survey "+r.id+" rendered"))}),1e3*r.appearance.surveyPopupDelaySeconds);this._renderTimeouts.add(o)}else this._surveyManager.renderSurvey(r,n,i);else ol.warn("Survey element not found")}else ol.warn("Surveys of type "+r.type+" cannot be rendered in the app");else ol.warn("Survey not found")}}displaySurvey(e,t){var s;if(rt(this._surveyManager))ol.warn("init was not called");else{var r=this._getSurveyById(e);if(r){var n=r;if(null!=(s=r.appearance)&&s.surveyPopupDelaySeconds&&t.ignoreDelay&&(n=i({},r,{appearance:i({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==Do&&t.initialResponses&&ol.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),!1===t.ignoreConditions){var o=this._checkSurveyEligibility(r);if(!o.eligible)return void ol.warn("Survey is not eligible to be displayed: ",o.reason)}"inline"!==t.displayType?this._surveyManager.handlePopoverSurvey(n,t):this.renderSurvey(n,t.selector,t.properties)}else ol.warn("Survey not found")}}cancelPendingSurvey(e){rt(this._surveyManager)?ol.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;null==(e=this._surveyManager)||null==e.handlePageUnload||e.handlePageUnload()}}function fu(e,t,i){if(rt(e))return!1;switch(i){case"exact":return e===t;case"contains":var s=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(s,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch(e){return!1}default:return!1}}class mu{constructor(e){this._actionRegistry=new Set,this._actionEvents=new Set,this._debugEventEmitter=new ja,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||!t.event||(null==e?void 0:e.event)===(null==t?void 0:t.event),this._instance=e}init(){var e,t;et(null==(e=this._instance)?void 0:e._addCaptureHook)||(this._captureHookUnsubscribe=null==(t=this._instance)?void 0:t._addCaptureHook(((e,t)=>{this.on(e,t)})))}dispose(){var e;null==(e=this._captureHookUnsubscribe)||e.call(this),this._captureHookUnsubscribe=void 0,this._debugEventEmitter=new ja}register(e){var t,i;if(!et(null==(t=this._instance)?void 0:t._addCaptureHook)&&(e.forEach((e=>{var t;this._actionRegistry.add(e),null==(t=e.steps)||t.forEach((e=>{this._actionEvents.add((null==e?void 0:e.event)||"")}))})),null!=(i=this._instance)&&i.autocapture)){var s=new Set;this._actionRegistry.forEach((e=>{var t;null==(t=e.steps)||t.forEach((e=>{null!=e&&e.selector&&s.add(e.selector)}))})),this._instance.autocapture.setElementSelectors(s)}}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(var 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&&t.url){var i,s=null==e||null==(i=e.properties)?void 0:i.$current_url;if(!s||"string"!=typeof s)return!1;if(!fu(s,t.url,t.url_matching||"contains"))return!1}return!0}_checkStepElement(e,t){return!!this._checkStepHref(e,t)&&!!this._checkStepText(e,t)&&!!this._checkStepSelector(e,t)}_checkStepHref(e,t){var i;if(null==t||!t.href)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>fu(e.href,t.href,t.href_matching||"exact")));var r,n=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!n&&fu((r=n.match(/(?::|")href="(.*?)"/))?r[1]:"",t.href,t.href_matching||"exact")}_checkStepText(e,t){var i;if(null==t||!t.text)return!0;var s=this._getElementsList(e);if(s.length>0)return s.some((e=>fu(e.text,t.text,t.text_matching||"exact")||fu(e.$el_text,t.text,t.text_matching||"exact")));var r,n,o,a=(null==e||null==(i=e.properties)?void 0:i.$elements_chain)||"";return!!a&&(r=function(e){for(var t,i=[],s=/(?::|")text="(.*?)"/g;!rt(t=s.exec(e));)i.includes(t[1])||i.push(t[1]);return i}(a),n=t.text,o=t.text_matching||"exact",r.some((e=>fu(e,n,o))))}_checkStepSelector(e,t){var i,s;if(null==t||!t.selector)return!0;var r=null==e||null==(i=e.properties)?void 0:i.$element_selectors;if(null!=r&&r.includes(t.selector))return!0;var n=(null==e||null==(s=e.properties)?void 0:s.$elements_chain)||"";if(t.selector_regex&&n)try{return new RegExp(t.selector_regex).test(n)}catch(e){return!1}return!1}_getElementsList(e){var t;return null==(null==e||null==(t=e.properties)?void 0:t.$elements)?[]:null==e?void 0:e.properties.$elements}_checkStepProperties(e,t){return null==t||!t.properties||0===t.properties.length||Xa(t.properties.reduce(((e,t)=>{var i=Je(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)}}class yu{constructor(e){var t;this._pendingActivatedItems=[],this._instance=e,this._eventToItems=new Map,this._cancelEventToItems=new Map,this._actionToItems=new Map,this._sessionIdUnsubscribe=null==(t=this._instance)||null==t.onSessionId?void 0:t.onSessionId((e=>this._onSessionIdChanged(e)))}_shouldPersistArmedActivation(e){return!1}_getActivationTimestampsKey(){return null}_writeActivationTimestamps(e){}_clearActivationTimestampsStore(){}_doesEventMatchFilter(e,t){return!!e&&Xa(e.propertyFilters,null==t?void 0:t.properties)}_buildEventToItemMap(e,t){var i=new Map;return e.forEach((e=>{var s;null==(s=e.conditions)||null==(s=s[t])||null==(s=s.values)||s.forEach((t=>{if(null!=t&&t.name){var s=i.get(t.name)||[];s.push(e.id),i.set(t.name,s)}}))})),i}_getMatchingItems(e,t,i){var s=(i===Ao?this._eventToItems:this._cancelEventToItems).get(e),r=[];return this._getItems((e=>{r=e.filter((e=>null==s?void 0:s.includes(e.id)))})),r.filter((s=>{var r,n=null==(r=s.conditions)||null==(r=r[i])||null==(r=r.values)?void 0:r.find((t=>t.name===e));return this._doesEventMatchFilter(n,t)}))}register(e){this._register(e,!1)}replace(e){this._register(e,!0)}_register(e,t){var i;et(null==(i=this._instance)?void 0:i._addCaptureHook)||(this._setupEventBasedItems(e,t),this._setupActionBasedItems(e,t))}_setupActionBasedItems(e,t){var i=e.filter((e=>{var t;return null==(t=e.conditions)||null==(t=t.actions)||null==(t=t.values)?void 0:t.length}));if(t&&this._actionToItems.clear(),0!==i.length){this._actionMatcher||(this._actionMatcher=new mu(this._instance),this._actionMatcher.init(),this._actionMatcher._addActionHook((e=>this.onAction(e))));var s=[];i.forEach((e=>{var t;null==(t=e.conditions)||null==(t=t.actions)||t.values.forEach((t=>{if(s.push(t),t.name){var i,r=null!==(i=this._actionToItems.get(t.name))&&void 0!==i?i:[];r.includes(e.id)||r.push(e.id),this._actionToItems.set(t.name,r)}}))})),t?this._actionMatcher.replace(s):this._actionMatcher.register(s)}else{var r;t&&(null==(r=this._actionMatcher)||r.replace([]))}}_mergeItemMaps(e,t){t.forEach(((t,i)=>{var s,r=null!==(s=e.get(i))&&void 0!==s?s:[];t.forEach((e=>{r.includes(e)||r.push(e)})),e.set(i,r)}))}_setupEventBasedItems(e,t){var i,s,r=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.events)&&(null==(i=e.conditions)||null==(i=i.events)||null==(i=i.values)?void 0:i.length)>0})),n=e.filter((e=>{var t,i;return(null==(t=e.conditions)?void 0:t.cancelEvents)&&(null==(i=e.conditions)||null==(i=i.cancelEvents)||null==(i=i.values)?void 0:i.length)>0})),o=this._buildEventToItemMap(e,Ao),a=this._buildEventToItemMap(e,Lo);t?(this._eventToItems=o,this._cancelEventToItems=a):(this._mergeItemMaps(this._eventToItems,o),this._mergeItemMaps(this._cancelEventToItems,a)),(0!==r.length||0!==n.length)&&(null!==(i=this._captureHookUnsubscribe)&&void 0!==i||(this._captureHookUnsubscribe=null==(s=this._instance)?void 0:s._addCaptureHook(((e,t)=>{this.onEvent(e,t)}))))}onEvent(e,t){var i,s,r=this._getLogger(),n=(null==t||null==(i=t.properties)?void 0:i.$survey_id)||(null==t||null==(s=t.properties)?void 0:s.$product_tour_id);if(n&&this.getActivatedIds().includes(n)){var o=this._activationOutcome(e,n);if("consume"===o)return r.info("event consumed activated item, removing it",{event:e,itemId:n}),void this._deactivateItems([n]);if("persist"===o)return r.info("shown item promoted to persisted activation",{event:e,itemId:n}),this._persistActivation(n),void this._clearActivationTimestamps([n])}if(this._cancelEventToItems.has(e)){var a=this._getMatchingItems(e,t,Lo);a.length>0&&(r.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map((e=>e.id))}),this._deactivateItems(a.map((e=>e.id))),a.forEach((e=>this._cancelPendingItem(e.id))))}if(this._eventToItems.has(e)){r.info("event name matched",{event:e,eventPayload:t,items:this._eventToItems.get(e)});var l=this._getMatchingItems(e,t,Ao);this._activateItems(l.map((e=>e.id)))}}onAction(e){this._actionToItems.has(e)&&this._activateItems(this._actionToItems.get(e)||[])}_activateItems(e){var t;if(0!==e.length){var i=!(null==(t=this._instance)||null==t.get_session_id||!t.get_session_id()),s=[];for(var r of e)i&&this._shouldPersistArmedActivation(r)?this._persistActivation(r)&&this._recordActivationTimestamp(r):s.push(r);s.length>0&&(this._pendingActivatedItems=[...new Set([...this._pendingActivatedItems,...s])]),this._getLogger().info("updating activated items",{activatedItems:this.getActivatedIds()})}}_persistActivation(e){this._pendingActivatedItems=this._pendingActivatedItems.filter((t=>t!==e));var t=this._getPersistedActivatedIds();return!t.includes(e)&&(this._setActivatedItems([...t,e]),this._stampActivationSession(),!0)}_deactivateItems(e){var t=new Set(e);this._pendingActivatedItems=this._pendingActivatedItems.filter((e=>!t.has(e)));var 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)}_getRawActivationTimestamps(){var e,t=this._getActivationTimestampsKey();if(!t)return{};var i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t];return i&&"object"==typeof i?i:{}}_recordActivationTimestamp(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps();this._writeActivationTimestamps(i({},t,{[e]:Date.now()}))}}_clearActivationTimestamps(e){if(this._getActivationTimestampsKey()){var t=this._getRawActivationTimestamps(),i={},s=!1;for(var r of Object.entries(t)){var n=r[0],o=r[1];e.includes(n)?s=!0:i[n]=o}s&&(Xe(i)?this._clearActivationTimestampsStore():this._writeActivationTimestamps(i))}}_clearAllActivationTimestamps(){this._getActivationTimestampsKey()&&this._clearActivationTimestampsStore()}getActivationTimestamp(e){if(this._getPersistedActivatedIds().includes(e)){var t=this._getRawActivationTimestamps()[e];return nt(t)?t:void 0}}_getRawPersistedActivatedIds(){var e,t=this._getActivatedKey();return(null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[t])||[]}_getPersistedActivatedIds(){var e,t,i=this._getRawPersistedActivatedIds();if(0===i.length)return[];var s=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.props[this._getActivatedSessionKey()],r=null==(t=this._instance)||null==t.get_session_id?void 0:t.get_session_id();return r&&s===r?i:[]}_stampActivationSession(){var e,t=null==(e=this._instance)||null==e.get_session_id?void 0:e.get_session_id();t&&this._setActivatedSession(t)}_clearActivationSession(){this._clearActivatedSession()}_onSessionIdChanged(e){var t,i=null==(t=this._instance)||null==(t=t.persistence)?void 0:t.props[this._getActivatedSessionKey()];if(i&&i!==e){var s=this._getRawPersistedActivatedIds(),r=this._getRawActivationTimestamps();s.length>0&&(this._setActivatedItems([]),s.filter((e=>nt(r[e]))).forEach((e=>this._cancelPendingItem(e)))),this._clearActivationSession(),this._clearAllActivationTimestamps()}}getActivatedIds(){return[...new Set([...this._getPersistedActivatedIds(),...this._pendingActivatedItems])].filter((e=>!this._isItemPermanentlyIneligible(e)))}dispose(){var e,t,i;null==(e=this._sessionIdUnsubscribe)||e.call(this),this._sessionIdUnsubscribe=void 0,null==(t=this._captureHookUnsubscribe)||t.call(this),this._captureHookUnsubscribe=void 0,null==(i=this._actionMatcher)||i.dispose(),this._actionMatcher=void 0}reset(){this._pendingActivatedItems=[],this._getRawPersistedActivatedIds().length>0&&this._setActivatedItems([]),this._clearActivationSession(),this._clearAllActivationTimestamps()}getEventToItemsMap(){return this._eventToItems}_getActionMatcher(){return this._actionMatcher}}class bu extends yu{constructor(e){super(e)}_getActivatedKey(){return W}_getActivatedSessionKey(){return G}_getActivationTimestampsKey(){return K}_writeActivationTimestamps(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[K]:e})}_clearActivationTimestampsStore(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(K)}_shouldPersistArmedActivation(e){var t,i;this._getItems((t=>{i=t.find((t=>t.id===e))}));var s=null==(t=i)||null==(t=t.appearance)?void 0:t.surveyPopupDelaySeconds;return nt(s)&&s>0}_getShownEventName(){return Mo}_getItems(e){var t;null==(t=this._instance)||t.getSurveys(e)}_cancelPendingItem(e){var t;null==(t=this._instance)||t.cancelPendingSurvey(e)}_getLogger(){return ol}_setActivatedItems(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[W]:e})}_setActivatedSession(e){var t;null==(t=this._instance)||null==(t=t.persistence)||t.register({[G]:e})}_clearActivatedSession(){var e;null==(e=this._instance)||null==(e=e.persistence)||e.unregister(G)}_isItemPermanentlyIneligible(){return!1}_activationOutcome(e,t){var i;this._getItems((e=>{i=e.find((e=>e.id===t))}));var s=!i||function(e){var t;return Qa(e)&&!(null==(t=e.conditions)||null==(t=t.events)||!t.repeatedActivation)||"always"===e.schedule}(i);return s?e===Mo?"consume":"ignore":e===Mo?"persist":e===$o||e===Oo?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class Su{constructor(e){this._instance=e}initialize(){}get(e){if("string"==typeof e)return this._instance.get_property(e);var t={};for(var i of e){var s=this._instance.get_property(i);et(s)||(t[i]=s)}return t}set(e,t){this._instance.register("string"==typeof e?{[e]:t}:e)}remove(e){"string"!=typeof e?e.forEach((e=>this._instance.unregister(e))):this._instance.unregister(e)}}class wu{constructor(e){this._instance=e}get(){var e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}getExtensions(){var e=null==Oe?void 0:Oe.__PosthogExtensions__;if(e){var t=e.generateSurveys,i=e.loadExternalDependency;return{generateSurveys:t?e=>t(this._instance,e):void 0,loadExternalDependency:i?e=>i(this._instance,"surveys",e):void 0}}}createEventReceiver(){return new bu(this._instance)}}var Cu=null!=ke&&ke.location?eo(ke.location.hash,"__posthog")||eo(location.hash,"state"):null,ku="_postHogToolbarParams",Eu=nr("[Toolbar]"),xu=nr("[FeatureFlags]");class Pu{constructor(e,t){void 0===t&&(t=!1),this._loggedEvaluationEnvironmentsDeprecation=!1,this.update(e,t)}update(e,t){this._snapshot=((e,t)=>{var i,s,r,n,o;return{bootstrap:{featureFlags:null==(i=e.bootstrap)?void 0:i.featureFlags,featureFlagPayloads:null==(s=e.bootstrap)?void 0:s.featureFlagPayloads},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!==(r=e.remote_config_refresh_interval_ms)&&void 0!==r?r:3e5,requestTimeoutMs:e.feature_flag_request_timeout_ms,compression:e.disable_compression?void 0:"best-available",evaluationContexts:null!==(n=null!==(o=e.evaluation_contexts)&&void 0!==o?o:e.evaluation_environments)&&void 0!==n?n:[],flagKeys:Je(e.flag_keys)?e.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this._loggedEvaluationEnvironmentsDeprecation||(xu.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this._loggedEvaluationEnvironmentsDeprecation=!0),et(e.flag_keys)||Je(e.flag_keys)||xu.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this._snapshot}}var Fu=nr("[FeatureFlags]"),Iu=nr("[FeatureFlags]",{debugEnabled:!0}),Tu="\" failed. Feature flags didn't load in time.",Ru="connection_error",Au=e=>{for(var t={},i=0;e.length>i;i++)t[e[i]]=!0;return t},Lu=e=>{var t={};for(var i of ur(e||{})){var s=i[1];s&&(t[i[0]]=s)}return t},Mu=e=>_t(e)&&("RangeError"===e.name&&0===e.message.indexOf("Maximum call stack size exceeded")||"InternalError"===e.name&&"too much recursion"===e.message),$u=nr("[Error tracking]"),Ou="webkit-masked-url:",Du=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",Ou],Bu=["__firefox__","__gCrWeb"],qu="Refusing to render web experiment since the viewer is a likely bot",Hu={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>-1===t.toLowerCase().indexOf(e.toLowerCase()),regex:(e,t)=>Ja(t,e),not_regex:(e,t)=>!Ja(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e};class Nu{get _config(){return this._instance.config}constructor(e){var t=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(e){void 0===e&&(e=!1),t.getWebExperiments((e=>{Nu._logInfo("retrieved web experiments from the server"),t._flagToExperiments=new Map,e.forEach((e=>{if(e.feature_flag_key){var i;t._flagToExperiments&&(Nu._logInfo("setting flag key ",e.feature_flag_key," to web experiment ",e),null==(i=t._flagToExperiments)||i.set(e.feature_flag_key,e));var s=t._instance.getFeatureFlag(e.feature_flag_key);tt(s)&&e.variants[s]&&t._applyTransforms(e.name,s,e.variants[s].transforms)}else if(e.variants)for(var r in e.variants){var n=e.variants[r];Nu._matchesTestVariant(n,t._instance)&&t._applyTransforms(e.name,r,n.transforms)}}))}),e)},this._instance=e,this._instance.onFeatureFlags((e=>{this.onFeatureFlags(e)}))}initialize(){}onFeatureFlags(e){if(this._is_bot())Nu._logInfo(qu);else if(!this._config.disable_web_experiments){if(rt(this._flagToExperiments))return this._flagToExperiments=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Nu._logInfo("applying feature flags",e),e.forEach((e=>{var t;if(this._flagToExperiments&&null!=(t=this._flagToExperiments)&&t.has(e)){var i,s=this._instance.getFeatureFlag(e),r=null==(i=this._flagToExperiments)?void 0:i.get(e);s&&null!=r&&r.variants[s]&&this._applyTransforms(r.name,s,r.variants[s].transforms)}}))}}previewWebExperiment(){var e=Nu.getWindowLocation();if(null!=e&&e.search){var t=Zn(null==e?void 0:e.search,"__experiment_id"),i=Zn(null==e?void 0:e.search,"__experiment_variant");t&&i&&(Nu._logInfo("previewing web experiments "+t+" && "+i),this.getWebExperiments((e=>{this._showPreviewWebExperiment(parseInt(t),i,e)}),!1,!0))}}loadIfEnabled(){this._config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,t,i){if(this._config.disable_web_experiments&&!i)return e([]);var 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(e,t,i){var s=i.filter((t=>t.id===e));s&&s.length>0&&(Nu._logInfo("Previewing web experiment ["+s[0].name+"] with variant ["+t+"]"),this._applyTransforms(s[0].name,t,s[0].variants[t].transforms))}static _matchesTestVariant(e,t){return!rt(e.conditions)&&Nu._matchUrlConditions(e,t)&&Nu._matchUTMConditions(e)}static _matchUrlConditions(e,t){var i;if(rt(e.conditions)||rt(null==(i=e.conditions)?void 0:i.url))return!0;var s=Nu.getWindowLocation();if(s){var r,n,o,a=Wr(t,s.href);return null==(r=e.conditions)||!r.url||Hu[null!==(n=null==(o=e.conditions)?void 0:o.urlMatchType)&&void 0!==n?n:"icontains"](e.conditions.url,a)}return!1}static getWindowLocation(){return null==ke?void 0:ke.location}static _matchUTMConditions(e){var t;if(rt(e.conditions)||rt(null==(t=e.conditions)?void 0:t.utm))return!0;var i=lo();if(i.utm_source){var s,r,n,o,a,l,u,c,d=null==(s=e.conditions)||null==(s=s.utm)||!s.utm_campaign||(null==(r=e.conditions)||null==(r=r.utm)?void 0:r.utm_campaign)==i.utm_campaign,h=null==(n=e.conditions)||null==(n=n.utm)||!n.utm_source||(null==(o=e.conditions)||null==(o=o.utm)?void 0:o.utm_source)==i.utm_source,_=null==(a=e.conditions)||null==(a=a.utm)||!a.utm_medium||(null==(l=e.conditions)||null==(l=l.utm)?void 0:l.utm_medium)==i.utm_medium,p=null==(u=e.conditions)||null==(u=u.utm)||!u.utm_term||(null==(c=e.conditions)||null==(c=c.utm)?void 0:c.utm_term)==i.utm_term;return d&&_&&p&&h}return!1}static _logInfo(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;t>s;s++)i[s-1]=arguments[s];rr.info("[WebExperiments] "+e,i)}_applyTransforms(e,t,i){this._is_bot()?Nu._logInfo(qu):"control"!==t?i.forEach((i=>{if(i.selector){var s;Nu._logInfo("applying transform of variant "+t+" for experiment "+e+" ",i);var r=null==(s=document)?void 0:s.querySelectorAll(i.selector);null==r||r.forEach((e=>{var t=e;i.html&&(t.innerHTML=i.html),i.css&&t.setAttribute("style",i.css)}))}})):Nu._logInfo("Control variants leave the page unmodified.")}_is_bot(){return xe&&this._instance?Ga(xe,this._config.custom_blocked_useragents):void 0}}var zu=nr("[Conversations]"),ju="Conversations not available yet.";function Vu(e,t){var s,r,n,o,a,l,u,c=null!==(s=null==e?void 0:e.flushIntervalMs)&&void 0!==s?s:3e3,d=null!==(r=null==e?void 0:e.maxBufferSize)&&void 0!==r?r:100,h=null!=t&&t.consoleCapture?void 0:null!==(n=null==e?void 0:e.maxLogsPerInterval)&&void 0!==n?n:1e3,_=et(h)?Math.max(d,2048):Math.max(d,h),p=i({},function(){var e="",t="";try{var s=null==xe?void 0:xe.userAgent;if(s){var r=Fi(s);e=r[0],t=r[1]}}catch(e){}return function(e,t){var s=function(e){if(e)return{}.hasOwnProperty.call(Us,e)?Us[e]:e}(e);return i({},s?{"os.name":s}:{},t?{"os.version":t}:{})}(e,t)}(),null==e?void 0:e.resourceAttributes);return{serviceName:null!==(o=null!==(a=null==p?void 0:p["service.name"])&&void 0!==a?a:null==e?void 0:e.serviceName)&&void 0!==o?o:null==t?void 0:t.serviceNameDefault,serviceVersion:null!==(l=null==p?void 0:p["service.version"])&&void 0!==l?l:null==e?void 0:e.serviceVersion,environment:null!==(u=null==p?void 0:p["deployment.environment"])&&void 0!==u?u:null==e?void 0:e.environment,resourceAttributes:p,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:c,maxBufferSize:d,maxQueueSize:_,maxBatchRecordsPerPost:100,rateCapWindowMs:c,maxLogsPerInterval:h,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}var Uu=["debug","log","warn","error","info"],Wu="console",Gu="__posthogHandledLogsRequestError",Ku=(e,t)=>{var i=e instanceof Error?e:new Error(t);return i[Gu]=!0,i},Qu=e=>!!e&&"object"==typeof e&&!0===e[Gu],Ju={featureFlags:class{constructor(e){this.name="featureFlags",this._override_warning=!1,this.featureFlagEventHandlers=[],this._logger=Fu,this._baseEventProperties={},this._eventPropertiesWithFlagValues={},this._reloadingHandlers=[],this._hasLoadedFlags=!1,this._requestInFlight=!1,this._requestGeneration=0,this._reloadingDisabled=!1,this._additionalReloadRequested=!1,this._flagsLoadedFromRemote=!1,this._staleCacheRefreshTriggered=!1,this._consecutiveStatusZeroFailures=0,this._onOnline=()=>{var e=this._hasStatusZeroCircuitBreakerTripped();this._consecutiveStatusZeroFailures=0,e&&this.reloadFeatureFlags()},this._refreshIfDue=()=>{var e,t=this._refreshIntervalMs;et(t)||this._config.remoteRequestsDisabled||!Pe||"hidden"===Pe.visibilityState||Date.now()-(null!==(e=this._lastRefreshAt)&&void 0!==e?e:0){"visible"===(null==Pe?void 0:Pe.visibilityState)&&this._refreshIfDue()},"get"in e?this._configSource=e:(this._instance=e,this._mutableConfigSource=new Pu(e.config,e._shouldDisableFlags()),this._configSource=this._mutableConfigSource)}updateConfig(e,t){var i;null==(i=this._mutableConfigSource)||i.update(e,t),this._client&&this._syncAutomaticRefresh()}setup(e){return this._initializingClient=e,this._logger=e.logger.createLogger("[FeatureFlags]"),_u(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 ke&&gr(ke,"online",this._onOnline),this._syncAutomaticRefresh(),this._dynamicProperties=e.registerDynamicEventProperties((()=>this._isCacheStale()?this._baseEventProperties:this._eventPropertiesWithFlagValues)),this._crossTabPersistenceUnsubscribe=null==(t=this._instance)||null==(t=t.persistence)?void 0:t.onCrossTabFeatureFlagChange((()=>{this._clearBootstrapState(),this._rebuildEventProperties(),this._fireFeatureFlagsCallbacks()})),this._rebuildEventProperties(),this.initialize()}_syncAutomaticRefresh(){var e=this._config.refreshIntervalMs,t=!this._config.remoteRequestsDisabled&&Pe&&!et(e)&&e>0?e:void 0;t!==this._refreshIntervalMs&&(this._stopAutomaticRefresh(),et(t)||(this._refreshIntervalMs=t,this._scheduleNextRefresh(),null!=Pe&&Pe.addEventListener&&gr(Pe,me,this._onVisibilityChange)))}_scheduleNextRefresh(){et(this._refreshIntervalMs)||(et(this._refreshInterval)||clearInterval(this._refreshInterval),this._lastRefreshAt=Date.now(),this._refreshInterval=setInterval(this._refreshIfDue,this._refreshIntervalMs))}_stopAutomaticRefresh(){et(this._refreshInterval)||(clearInterval(this._refreshInterval),this._refreshInterval=void 0,null==Pe||null==Pe.removeEventListener||Pe.removeEventListener(me,this._onVisibilityChange)),this._refreshIntervalMs=void 0,this._lastRefreshAt=void 0}destroy(){this._dispose()}dispose(){this._dispose()}_dispose(){var e,t;this._stopAutomaticRefresh(),this._requestGeneration++,this._additionalReloadRequested=!1,this._initializingClient=void 0,this._client&&(this._clearDebouncer(),null==(e=this._dynamicProperties)||e.dispose(),this._dynamicProperties=void 0,null==(t=this._crossTabPersistenceUnsubscribe)||t.call(this),this._crossTabPersistenceUnsubscribe=void 0,this._reloadingHandlers=[],null==ke||ke.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.kv.get(e)}_clearBootstrapState(){return!!this._bootstrapState&&(this._bootstrapState=void 0,!0)}_fallBackToPersistedFlags(){var e;return!et(null==(e=this._client)?void 0:e.kv.get(R))&&this._clearBootstrapState()}_set(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.set(e)}))}_markCrossTabFeatureFlagSnapshot(e,t,i){var s;if(null!=(s=this._instance)&&s.persistence&&e[R]){var r=this._prop(R)||{},n=e[R]||{},o=t.flags||t.featureFlags,a=t.flags?Object.entries(t.flags).filter((e=>{var t=e[1];return!(null!=t&&t.failed)})).map((e=>e[0])):[],l=!!t.errorsWhileComputingFlags&&!!t.flags,u=l?a:i&&!Je(o)?Object.keys(o||{}):Array.from(new Set([...Object.keys(r),...Object.keys(n)])),c=this._prop(O)||{},d=e[O]||{},h=l||i?u:Array.from(new Set([...Object.keys(c),...Object.keys(d)])),_=!l&&!i,p=!!_||u,g={[A]:p,[R]:p,[O]:!!_||h};for(var v of(e[M]&&(g[M]=p),[D,X,B]))et(e[v])||(g[v]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(g)}}_remove(e){this._persist((()=>{var t;return null==(t=this._client)?void 0:t.kv.remove(e)}))}_persist(e){try{e()}catch(e){this._logger.error("Failed to update feature flag persistence",e)}}_rebuildEventProperties(){var e={};for(var t of[A,O,D,q]){var s=this._prop(t);et(s)||(e[t]=s)}this._baseEventProperties=e;var r=i({},e),n=this._prop(R);if(n)for(var o of Object.entries(n))r["$feature/"+o[0]]=o[1];this._eventPropertiesWithFlagValues=r}_isCacheStale(){var e=this._config.cacheTtlMs;if(!e||0>=e)return!1;var t=this._prop(X);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(){var e=this._config.evaluationContexts;return null!=e&&e.length?e.filter((e=>{var 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(){var e=this._config.flagKeys;if(!et(e))return e.filter((e=>{var 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,i=this._config,s=null!==(e=null==(t=i.bootstrap)?void 0:t.featureFlags)&&void 0!==e?e:{};if(Object.keys(s).length){var r,n,o=null!==(r=null==(n=i.bootstrap)?void 0:n.featureFlagPayloads)&&void 0!==r?r:{},a=Object.keys(s).filter((e=>!et(s[e]))).reduce(((e,t)=>(e[t]=s[t],e)),{}),l=Object.keys(o).filter((e=>a[e])).reduce(((e,t)=>(e[t]=o[t],e)),{});return this._receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l},void 0,{persist:!1})}}updateFlags(e,t,s){var r,n,o=null!=s&&s.merge&&null!==(r=this._prop(R))&&void 0!==r?r:{},a=null!=s&&s.merge&&null!==(n=this._prop(O))&&void 0!==n?n:{},l=i({},o,e),u=i({},a,t),c={};for(var d of Object.entries(l)){var h=d[0],_=d[1];c[h]={key:h,enabled:xs(_),variant:Ps(_),reason:void 0,metadata:et(null==u?void 0:u[h])?void 0:{id:0,version:void 0,description:void 0,payload:u[h]}}}this._receivedFeatureFlags({flags:c})}get hasLoadedFlags(){return this._hasLoadedFlags}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._prop(M),t=this._prop(q),s=this._prop(H);if(!s&&!t)return e||{};var r=lr({},e||{}),n=[...new Set([...Object.keys(s||{}),...Object.keys(t||{})])];for(var o of n){var a,l,u=r[o],c=null==t?void 0:t[o],d=et(c)?null!==(a=null==u?void 0:u.enabled)&&void 0!==a&&a:!!c,h=et(c)?null==u?void 0:u.variant:"string"==typeof c?c:void 0,_=null==s?void 0:s[o],p=i({},u,{enabled:d,variant:d?null!=h?h:null==u?void 0:u.variant:void 0});d!==(null==u?void 0:u.enabled)&&(p.original_enabled=null==u?void 0:u.enabled),h!==(null==u?void 0:u.variant)&&(p.original_variant=null==u?void 0:u.variant),_&&(p.metadata=i({},null==u?void 0:u.metadata,{payload:_,original_payload:null==u||null==(l=u.metadata)?void 0:l.payload})),r[o]=p}return this._override_warning||(this._logger.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:s,finalDetails:r}),this._override_warning=!0),r}getAllFeatureFlags(){var e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map((i=>{var s=e[i];return{key:i,enabled:xs(s),variant:Ps(s),payload:Es(t[i])}}))}getFlagVariants(){var e=this._prop(R),t=this._prop(q);if(!t)return e||{};for(var i=lr({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:i}),this._override_warning=!0),i}getFlagPayloads(){var e=this._prop(O),t=this._prop(H);if(!t)return e||{};for(var i=lr({},e||{}),s=Object.keys(t),r=0;s.length>r;r++)i[s[r]]=t[s[r]];return this._override_warning||(this._logger.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:i}),this._override_warning=!0),i}reloadFeatureFlags(){this._reloadingDisabled||this._config.featureFlagsDisabled||this._hasStatusZeroCircuitBreakerTripped()||(this._requestInFlight&&(this._additionalReloadRequested=!0),this._reloadDebouncer||(this._reloadingHandlers.slice().forEach((e=>{try{e()}catch(e){this._logger.error("Error while running feature flags reloading callback",e)}})),this._reloadDebouncer=setTimeout((()=>{this._callFlagsEndpoint()}),5)))}_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(J)}_callFlagsEndpoint(e){this._clearDebouncer();var t=this._client;if(t&&!this._config.remoteRequestsDisabled&&!this._hasStatusZeroCircuitBreakerTripped())if(this._requestInFlight)this._additionalReloadRequested=!0;else{var s={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:i({},t.initialPersonProperties,this._prop(N)||{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this._prop(z),timezone:fo()};et(t.deviceId)||(s.$device_id=t.deviceId),(null!=e&&e.disableFlags||this._config.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this._getValidEvaluationEnvironments();r.length&&(s.evaluation_contexts=r);var n=this._getValidFlagKeys();et(n)||(s.flag_keys=n);var o=this._config.onlyEvaluateSurveyFeatureFlags,a="/flags/?v=2"+(o?"&only_evaluate_survey_feature_flags=true":""),l=this._requestGeneration;this._requestInFlight=!0;var u=()=>{this._additionalReloadRequested&&(this._additionalReloadRequested=!1,this._callFlagsEndpoint())},c=e=>{this._requestInFlight=!1,l===this._requestGeneration?(this._set({[Z]:[Ru]}),this._logger.error("Feature flag request failed",e),this._fallBackToPersistedFlags()&&this._fireFeatureFlagsCallbacks(!0),u()):u()};try{t.sendRequest(a,{target:"flags",method:"POST",body:s,compression:this._config.compression,sentAt:"body",timeoutMs:this._config.requestTimeoutMs}).then((e=>{var t,i,r=null!==(t=e.json)&&void 0!==t?t:{},n=200!==e.statusCode;if(this._requestInFlight=!1,l===this._requestGeneration){if(this._trackStatusZeroReachability(e.statusCode),n||this._additionalReloadRequested||(this.$anon_distinct_id=void 0),!s.disable_flags||this._additionalReloadRequested){this._flagsLoadedFromRemote=!n;var a=[];e.error?a.push(e.error instanceof Error&&"AbortError"===e.error.name?"timeout":e.error instanceof Error?Ru:"unknown_error"):200!==e.statusCode&&a.push("api_error_"+e.statusCode),r.errorsWhileComputingFlags&&a.push("errors_while_computing_flags");var c=!(null==(i=r.quotaLimited)||!i.includes("feature_flags"));c&&a.push("quota_limited"),this._set({[Z]:a}),c?this._logger.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this._receivedFeatureFlags(r,n,{partialResponse:o}),u()}}else u()})).catch(c)}catch(e){c(e)}}}_hasStatusZeroCircuitBreakerTripped(){return to(this._consecutiveStatusZeroFailures,3)}_trackStatusZeroReachability(e){this._consecutiveStatusZeroFailures=io(e,this._consecutiveStatusZeroFailures,3,(()=>this._logger.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes.")))}getFeatureFlag(e,t){var i;if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s=this.getFeatureFlagResult(e,t);return null!==(i=null==s?void 0:s.variant)&&void 0!==i?i:null==s?void 0:s.enabled}}else this._logger.warn('getFeatureFlag for key "'+e+Tu)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return null==t?void 0:t.payload}getFeatureFlagResult(e,t){if(void 0===t&&(t={}),!t.fresh||this._flagsLoadedFromRemote)if(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0){if(!this._checkAndTriggerStaleRefresh()){var s,r=this.getFlagVariants(),n=e in r,o=r[e],a=this.getFlagPayloads()[e],l=String(o),u=this._prop(D)||void 0,c=this._prop(X)||void 0,d=this._prop(J)||{};if(this._config.deduplicateCallsPerSession){var h,_=null==(h=this._client)?void 0:h.session.sessionId,p=this._prop(Y);_&&_!==p&&(d={},s=_)}if(t.send_event||!("send_event"in t))if(e in d&&d[e].includes(l))s&&this._set({[J]:d,[Y]:s});else{var g,v,f,m,y,b,S,w,C,k,E,x;Je(d[e])?d[e].push(l):d[e]=[l],this._set(i({[J]:d},s?{[Y]:s}:{}));var P=this.getFeatureFlagDetails(e),F=[...null!==(g=this._prop(Z))&&void 0!==g?g:[]];et(o)&&F.push("flag_missing");var I={$feature_flag:e,$feature_flag_response:o,$feature_flag_payload:null!=a?a:null,$feature_flag_request_id:u,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:null!==(v=null==(f=this._config.bootstrap)||null==(f=f.featureFlags)?void 0:f[e])&&void 0!==v?v:null,$feature_flag_bootstrapped_payload:null!==(m=null==(y=this._config.bootstrap)||null==(y=y.featureFlagPayloads)?void 0:y[e])&&void 0!==m?m:null,$used_bootstrap_value:!this._flagsLoadedFromRemote};et(null==P||null==(b=P.metadata)?void 0:b.has_experiment)||(I.$feature_flag_has_experiment=P.metadata.has_experiment),et(null==P||null==(S=P.metadata)?void 0:S.version)||(I.$feature_flag_version=P.metadata.version);var T,R=null!==(w=null==P||null==(C=P.reason)?void 0:C.description)&&void 0!==w?w:null==P||null==(k=P.reason)?void 0:k.code;R&&(I.$feature_flag_reason=R),null!=P&&null!=(E=P.metadata)&&E.id&&(I.$feature_flag_id=P.metadata.id),et(null==P?void 0:P.original_variant)&&et(null==P?void 0:P.original_enabled)||(I.$feature_flag_original_response=et(P.original_variant)?P.original_enabled:P.original_variant),null!=P&&null!=(x=P.metadata)&&x.original_payload&&(I.$feature_flag_original_payload=null==P||null==(T=P.metadata)?void 0:T.original_payload),F.length&&(I.$feature_flag_error=F.join(",")),this._captureFeatureFlagCalled(I)}else s&&this._set({[J]:d,[Y]:s});if(n)return{key:e,enabled:!!o,variant:"string"==typeof o?o:void 0,payload:Es(a)}}}else this._logger.warn('getFeatureFlagResult for key "'+e+Tu)}_captureFeatureFlagCalled(e){try{var t;null==(t=this._client)||t.capture("$feature_flag_called",e).catch((e=>{this._logger.error("Failed to capture feature flag call",e)}))}catch(e){this._logger.error("Failed to capture feature flag call",e)}}getRemoteConfigPayload(e,t){this._getRemoteConfigPayload(e,t)}_getRemoteConfigPayload(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r={distinct_id:t.distinctId,token:t.projectToken,person_properties:{$lib:t.library.name,$lib_version:t.library.version}},n=s._getValidEvaluationEnvironments();n.length&&(r.evaluation_contexts=n);var o,a=s._getValidFlagKeys();et(a)||(r.flag_keys=a);try{var l,u=null==(l=(yield t.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:r,compression:s._config.compression,sentAt:"body",timeoutMs:s._config.requestTimeoutMs})).json)?void 0:l.featureFlagPayloads;o=(null==u?void 0:u[e])||void 0}catch(e){return void s._logger.error("Remote config feature flag request failed",e)}try{i(o)}catch(e){s._logger.error("Remote config feature flag callback failed",e)}}}))()}isFeatureEnabled(e,t){if(void 0===t&&(t={}),t.fresh&&!this._flagsLoadedFromRemote)return t.defaultValue;if(!(this._hasLoadedFlags||this.getFlags()&&this.getFlags().length>0))return this._logger.warn('isFeatureEnabled for key "'+e+Tu),t.defaultValue;var i=this.getFeatureFlag(e,t);return et(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,s){if(this._client){this._hasLoadedFlags=!0;var r=function(e,t,s,r,n,o){void 0===t&&(t={}),void 0===s&&(s={}),void 0===r&&(r={}),void 0===o&&(o=Fu);var a=((e,t)=>{var s=e.flags;return s?i({},e,{featureFlags:Object.fromEntries(Object.keys(s).map((e=>{var t;return[e,null!==(t=s[e].variant)&&void 0!==t?t:s[e].enabled]}))),featureFlagPayloads:Object.fromEntries(Object.keys(s).filter((e=>s[e].enabled)).filter((e=>{var t;return!et(null==(t=s[e].metadata)?void 0:t.payload)})).map((e=>{var t;return[e,null==(t=s[e].metadata)?void 0:t.payload]})))}):(e.featureFlags&&t.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e)})(e,o),l=a.flags,u=a.featureFlags,c=a.featureFlagPayloads;if(u){var d=e.requestId,h=e.evaluatedAt;if(Je(u)){o.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var _={};if(u)for(var p=0;u.length>p;p++)_[u[p]]=!0;return{[A]:u,[R]:_,[B]:!1}}var g=u,v=c,f=l;if(null!=n&&n.partialResponse){var m=Object.keys(g),y=v||{};g=i({},t,g),v=i({},s,y),m.forEach((e=>{var t;e in y||null==(t=v)||delete t[e]})),f=i({},r,f)}else if(e.errorsWhileComputingFlags)if(l){var b=new Set(Object.keys(l).filter((e=>{var t;return!(null!=(t=l[e])&&t.failed)})));g=i({},t,Object.fromEntries(Object.entries(g).filter((e=>b.has(e[0])))));var S=Object.fromEntries(Object.entries(v||{}).filter((e=>b.has(e[0]))));v=i({},s,S),b.forEach((e=>{var t;e in S||null==(t=v)||delete t[e]})),f=i({},r,Object.fromEntries(Object.entries(f||{}).filter((e=>b.has(e[0])))))}else g=i({},t,g),v=i({},s,v),f=i({},r,f);return i({[A]:Object.keys(Lu(g)),[R]:g||{},[O]:v||{},[M]:f||{},[B]:!0===e.minimalFlagCalledEvents},d?{[D]:d}:{},h?{[X]:h}:{})}}(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this._logger);if(r)if(!1===(null==s?void 0:s.persist)){var n=!et(this._client.kv.get(R));this._bootstrapState=r,n||this._set(r)}else this._clearBootstrapState(),this._markCrossTabFeatureFlagSnapshot(r,e,!(null==s||!s.partialResponse)),this._set(r);else t&&this._fallBackToPersistedFlags();t||(this._staleCacheRefreshTriggered=!1),this._fireFeatureFlagsCallbacks(t)}}override(e,t){void 0===t&&(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([q,H]),this._fireFeatureFlagsCallbacks(),void Iu.info("All overrides cleared");if(Je(e))return this._set({[q]:Au(e)}),this._fireFeatureFlagsCallbacks(),void Iu.info("Flag overrides set",{flags:e});if(e&&"object"==typeof e&&("flags"in e||"payloads"in e)){var t,i=e;this._override_warning=Boolean(null!==(t=i.suppressWarning)&&void 0!==t&&t);var s={},r=i.flags,n=i.payloads;return r&&(s[q]=Je(r)?Au(r):r),n&&(s[H]=n),Object.keys(s).length&&this._set(s),!1===r&&!1===n?this._remove([q,H]):!1===r?this._remove(q):!1===n&&this._remove(H),this._fireFeatureFlagsCallbacks(),!1===r?Iu.info("Flag overrides cleared"):r&&Iu.info("Flag overrides set",{flags:r}),void(!1===n?Iu.info("Payload overrides cleared"):n&&Iu.info("Payload overrides set",{payloads:n}))}if(e&&"object"==typeof e)return this._set({[q]:e}),this._fireFeatureFlagsCallbacks(),void Iu.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){var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;try{e(i,s)}catch(e){this._logger.error("Error while running feature flags callback",e)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,s){var r,n=(this._prop(L)||[]).find((t=>t.flagKey===e)),o={["$feature_enrollment/"+e]:t},a={$feature_flag:e,$feature_enrollment:t,$set:o};n&&(a.$early_access_feature_name=n.name),s&&(a.$feature_enrollment_stage=s);var l=i({},this.getFlagVariants(),{[e]:t});null==(r=this._instance)||null==(r=r.persistence)||r.markCrossTabFeatureFlagChanges({[A]:[e],[R]:[e],[N]:Object.keys(o)}),this._set({[A]:Object.keys(Lu(l)),[R]:l,[N]:i({},this._prop(N)||{},o)}),this._fireFeatureFlagsCallbacks();try{var u;null==(u=this._client)||u.capture("$feature_enrollment_update",a).catch((e=>{this._logger.error("Failed to capture early access feature enrollment",e)}))}catch(e){this._logger.error("Failed to capture early access feature enrollment",e)}}getEarlyAccessFeatures(e,t,i){void 0===t&&(t=!1);var s=this._prop(L);!s||t?this._getEarlyAccessFeatures(e,i):e(s)}_getEarlyAccessFeatures(e,i){var s=this;return t((function*(){var t=s._client;if(t){var r,n=i?"&"+i.map((e=>"stage="+e)).join("&"):"";try{var o=yield t.sendRequest("/api/early_access_features/?token="+t.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s._set({[L]:r=o.json.earlyAccessFeatures})}catch(e){return void s._logger.error("Early access feature request failed",e)}try{e(r)}catch(e){s._logger.error("Early access feature callback failed",e)}}}))()}_prepareFeatureFlagsForCallbacks(){var 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();var t=this._prepareFeatureFlagsForCallbacks(),i=t.flags,s=t.flagVariants;this.featureFlagEventHandlers.forEach((t=>{try{t(i,s,{errorsLoading:e})}catch(e){this._logger.error("Error while running feature flags callback",e)}}))}setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0),this._setPersonPropertiesForFlags(e,t)}_setPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(N)||{},r=(null==e?void 0:e.$set)||(null!=e&&e.$set_once?{}:e),n=null==e?void 0:e.$set_once,o={};if(n)for(var a in n)({}).hasOwnProperty.call(n,a)&&(a in s||(o[a]=n[a]));this._set({[N]:i({},s,o,r)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=i({},this._prop(N)||{});e.forEach((e=>{delete s[e]})),this._set({[N]:s}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e){void 0===e&&(e=!0),this._remove(N),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t){void 0===t&&(t=!0);var s=this._prop(z)||{},r=i({},s);for(var n of Object.keys(e))r[n]=i({},s[n],e[n]);this._set({[z]:r}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this._prop(z)||{};this._set({[z]:i({},t,{[e]:{}})})}else this._remove(z)}reset(){this._requestGeneration++,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}}},Yu={sessionRecording:class{get _config(){return this._instance.config}get _persistence(){return this._instance.persistence}get started(){var e;return!(null==(e=this._lazyLoadedSessionRecording)||!e.isStarted)}get status(){var e,t;return this._recordingStatus===iu||this._recordingStatus===su?this._recordingStatus:null!==(e=null==(t=this._lazyLoadedSessionRecording)?void 0:t.status)&&void 0!==e?e:this._recordingStatus}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this._recordingStatus=eu,this._persistFlagsOnSessionListener=void 0,this._sessionRecordingDisposed=!1,this._documentWasEverVisible=(()=>{var e;if(null==Pe||!Pe.visibilityState||"visible"===Pe.visibilityState)return!0;var t=null==ke||null==(e=ke.performance)||null==e.getEntriesByType?void 0:e.getEntriesByType("visibility-state");return!(null!=t&&t.length)||t.some((e=>"visible"===e.name))})(),this._onVisibilityChange=()=>{var e;"visible"===(null==Pe?void 0:Pe.visibilityState)&&(this._documentWasEverVisible=!0,null==(e=this._lazyLoadedSessionRecording)||null==e.setDocumentWasEverVisible||e.setDocumentWasEverVisible(!0))},this._instance=e,!this._instance.sessionManager)throw nu.error("started without valid sessionManager"),new Error(ru+" started without valid sessionManager. This is a bug.");if(this._config.cookieless_mode===pe)throw new Error(ru+' cannot be used with cookieless_mode="always"');null!=Pe&&Pe.addEventListener&&gr(Pe,"visibilitychange",this._onVisibilityChange)}initialize(){this.startIfEnabledOrStop()}dispose(e){var t=(void 0===e?{}:e).discardBufferedEvents,i=void 0!==t&&t;this._sessionRecordingDisposed=!0,null==Pe||null==Pe.removeEventListener||Pe.removeEventListener("visibilitychange",this._onVisibilityChange),i?this._discardRecording(!0):this.stopRecording()}get _isRecordingEnabled(){var e,t=!(null==(e=this._instance.get_property(C))||!e.enabled),i=!this._config.disable_session_recording,s=this._config.disable_session_recording||this._instance.consent.isOptedOut();return ke&&t&&i&&!s}startIfEnabledOrStop(e){var t;if(!(this._sessionRecordingDisposed||this._isRecordingEnabled&&null!=(t=this._lazyLoadedSessionRecording)&&t.isStarted)){var i=!et(Object.assign)&&!et(Array.from);this._isRecordingEnabled&&i?(this._lazyLoadAndStart(e),nu.info("starting")):(this._recordingStatus=eu,this.stopRecording())}}_lazyLoadAndStart(e){var t,i;if(this._isRecordingEnabled)if(this._recordingStatus!==iu&&this._recordingStatus!==su&&(this._recordingStatus=tu),null!=Oe&&null!=(t=Oe.__PosthogExtensions__)&&null!=(t=t.rrweb)&&t.record&&null!=(i=Oe.__PosthogExtensions__)&&i.initSessionRecording)this._onScriptLoaded(e);else{var s,r=this._instance.sessionManager;null==(s=Oe.__PosthogExtensions__)||null==s.loadExternalDependency||s.loadExternalDependency(this._instance,this._scriptName,(t=>{if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager===r)return t?(this._instance.register_for_session({[de]:!0}),nu.error("could not load recorder",t)):void this._onScriptLoaded(e);this._recordingStatus=eu}))}}stopRecording(){var e,t;null==(e=this._persistFlagsOnSessionListener)||e.call(this),this._persistFlagsOnSessionListener=void 0,null==(t=this._lazyLoadedSessionRecording)||t.stop()}_discardRecording(e){var t,i;void 0===e&&(e=!1),null==(t=this._persistFlagsOnSessionListener)||t.call(this),this._persistFlagsOnSessionListener=void 0,null==(i=this._lazyLoadedSessionRecording)||i.discard({discardProducerEvents:e})}_resetSampling(){var e,t;null==(e=this._persistence)||e.unregister(T),null==(t=this._persistence)||t.unregister(k)}_validateSampleRate(e,t){if(rt(e))return null;var i,s=nt(e)?e:parseFloat(e);return"number"!=typeof(i=s)||!Number.isFinite(i)||0>i||i>1?(nu.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):s}_persistRemoteConfig(e){if(this._persistence){var t,s,r=this._persistence,n=()=>{var t,s=!1===e.sessionRecording?void 0:e.sessionRecording,n=this._validateSampleRate(null==(t=this._config.session_recording)?void 0:t.sampleRate,"session_recording.sampleRate"),o=this._validateSampleRate(null==s?void 0:s.sampleRate,"remote config sampleRate"),a=null!=n?n:o;rt(a)&&this._resetSampling();var l=null==s?void 0:s.minimumDurationMilliseconds;r.register({[C]:i({cache_timestamp:Date.now(),enabled:!!s},s,{networkPayloadCapture:i({capturePerformance:e.capturePerformance},null==s?void 0:s.networkPayloadCapture),canvasRecording:{enabled:null==s?void 0:s.recordCanvas,fps:null==s?void 0:s.canvasFps,quality:null==s?void 0:s.canvasQuality},sampleRate:a,minimumDurationMilliseconds:et(l)?null:l,endpoint:null==s?void 0:s.endpoint,triggerMatchType:null==s?void 0:s.triggerMatchType,masking:null==s?void 0:s.masking,urlTriggers:null==s?void 0:s.urlTriggers,version:null==s?void 0:s.version,triggerGroups:null==s?void 0:s.triggerGroups})})};n(),null==(t=this._persistFlagsOnSessionListener)||t.call(this),this._persistFlagsOnSessionListener=null==(s=this._instance.sessionManager)?void 0:s.onSessionId(n)}}onRemoteConfig(e){var 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()):(this._recordingStatus===iu&&(this._recordingStatus=su,nu.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var i;void 0===t&&(t="log"),null!=(i=this._lazyLoadedSessionRecording)&&i.log?this._lazyLoadedSessionRecording.log(e,t):nu.warn("log called before recorder was ready")}get _scriptName(){var e,t,i=null==(e=this._instance)||null==(e=e.persistence)?void 0:e.get_property(C);return(null==i||null==(t=i.scriptConfig)?void 0:t.script)||"lazy-recorder"}_isRemoteConfigFresh(){var e,t=this._instance.get_property(C);if(!t)return!1;try{e="object"==typeof t?t:JSON.parse(t)}catch(e){return nu.warn("persisted remote config for session recording is invalid and will be ignored",e),!1}return!rt(e.cache_timestamp)&&36e5>=Date.now()-e.cache_timestamp}_onScriptLoaded(e){var t,i,s;if(!this._sessionRecordingDisposed&&this._isRecordingEnabled&&this._instance.sessionManager){if(null==(t=Oe.__PosthogExtensions__)||!t.initSessionRecording)return nu.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[de]:!0});var r;if(this._lazyLoadedSessionRecording||(this._lazyLoadedSessionRecording=null==(r=Oe.__PosthogExtensions__)?void 0:r.initSessionRecording(this._instance,this._documentWasEverVisible),this._lazyLoadedSessionRecording._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._isRemoteConfigFresh()){if(this._recordingStatus===su||this._recordingStatus===iu)return;return this._recordingStatus=iu,nu.info("persisted remote config is stale, requesting fresh config before starting"),void new zo(this._instance).load()}this._recordingStatus=tu,null==(i=(s=this._lazyLoadedSessionRecording).setDocumentWasEverVisible)||i.call(s,this._documentWasEverVisible),this._lazyLoadedSessionRecording.start(e)}else this._recordingStatus=eu}onRRwebEmit(e){var t;null==(t=this._lazyLoadedSessionRecording)||null==t.onRRwebEmit||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[x]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideLinkedFlag()}overrideSampling(){var e,t;this._lazyLoadedSessionRecording||null==(t=this._persistence)||t.register({[E]:!0}),null==(e=this._lazyLoadedSessionRecording)||e.overrideSampling()}overrideTrigger(e){var t,i;this._lazyLoadedSessionRecording||null==(i=this._persistence)||i.register({["url"===e?P:F]:!0}),null==(t=this._lazyLoadedSessionRecording)||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return(null==(e=this._lazyLoadedSessionRecording)?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var i;return!(null==(i=this._lazyLoadedSessionRecording)||!i.tryAddCustomEvent(e,t))}}},Zu={autocapture:class extends zl{constructor(e){super(new jl(e)),this.instance=e}},historyAutocapture:class{constructor(e){this._instance=e,this._lastLocation=this._getCurrentLocation()}initialize(){this.startIfEnabled()}get isEnabled(){var e=this._getCaptureOptions();return!!(e.path||e.search||this._shouldCaptureHashChanges(e))}startIfEnabled(){this.isEnabled&&(rr.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,rr.info("History API monitoring stopped")}monitorHistoryChanges(){ke&&ke.history&&(this._patchHistoryMethod("pushState"),this._patchHistoryMethod("replaceState"),this._setupPopstateListener(),this._shouldCaptureHashChanges()&&this._setupHashchangeListener())}_patchHistoryMethod(e){var t;if(ke&&(null==(t=ke.history[e])||!t.__posthog_wrapped__)){var i=this;Gl(ke.history,e,(t=>function(s,r,n){t.call(this,s,r,n),i._capturePageview(e)}))}}_getCurrentLocation(){var e=null==ke?void 0:ke.location;if(null!=e&&e.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}_getCaptureOptions(){var e=this._instance.config.capture_pageview;return"history_change"===e?{path:!0}:Ze(e)?e:{}}_shouldCaptureHashChanges(e){return void 0===e&&(e=this._getCaptureOptions()),!!e.hash&&!this._instance.config.disable_capture_url_hashes}_hasLocationChanged(e){var 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){try{var t=this._getCurrentLocation();if(!t)return;this._hasLocationChanged(t)&&this._instance.capture(be,{navigation_type:e}),this._lastLocation=t}catch(t){rr.error("Error capturing "+e+" pageview",t)}}_setupPopstateListener(){if(!this._popstateListener){var e=()=>{this._capturePageview("popstate")};gr(ke,"popstate",e),this._popstateListener=()=>{ke&&ke.removeEventListener("popstate",e)}}}_setupHashchangeListener(){if(!this._hashchangeListener){var e=()=>{this._capturePageview("hashchange")};gr(ke,"hashchange",e),this._hashchangeListener=()=>{ke&&ke.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)||!t.props[p]),this.rageclicks=new Ol(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return Ze(this._config.capture_heatmaps)&&this._config.capture_heatmaps.flush_interval_milliseconds&&(e=this._config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return rt(this._config.capture_heatmaps)?rt(this._config.enable_heatmaps)?this._enabledServerSide:this._config.enable_heatmaps:!1!==this._config.capture_heatmaps}startIfEnabled(){if(this.isEnabled){if(this._initialized)return;ou.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){var t=e.config;if("heatmaps"in t){var i=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[p]:i}),this._enabledServerSide=i,this.startIfEnabled()}}}getAndClearBuffer(){var e=this._buffer;return this._buffer=void 0,e}_onDeadClick(e){au(e.originalEvent)&&this._onClick(e.originalEvent,"deadclick")}_onVisibilityChange(){this._flushInterval&&clearInterval(this._flushInterval),this._flushInterval=function(e){return"visible"===(null==e?void 0:e.visibilityState)}(Pe)?setInterval(this._flush.bind(this),this.flushIntervalMilliseconds):null}_setupListeners(){ke&&Pe&&(this._flushHandler=this._flush.bind(this),gr(ke,ye,this._flushHandler),this._onClickHandler=e=>this._onClick(e||(null==ke?void 0:ke.event)),gr(Pe,"click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler=e=>this._onMouseMove(e||(null==ke?void 0:ke.event)),gr(Pe,"mousemove",this._onMouseMoveHandler,{capture:!0}),this._deadClicksCapture=new qn(this.instance,Dn,this._onDeadClick.bind(this)),this._deadClicksCapture.startIfEnabledOrStop(),this._onVisibilityChange_handler=this._onVisibilityChange.bind(this),gr(Pe,me,this._onVisibilityChange_handler),this._initialized=!0)}_removeListeners(){var e;ke&&Pe&&(this._flushHandler&&ke.removeEventListener(ye,this._flushHandler),this._onClickHandler&&Pe.removeEventListener("click",this._onClickHandler,{capture:!0}),this._onMouseMoveHandler&&Pe.removeEventListener("mousemove",this._onMouseMoveHandler,{capture:!0}),this._onVisibilityChange_handler&&Pe.removeEventListener(me,this._onVisibilityChange_handler),clearTimeout(this._mouseMoveTimeout),null==(e=this._deadClicksCapture)||e.stop(),this._initialized=!1)}_getProperties(e,t){var i=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),r=this.instance.scrollManager.scrollElement(),n=function(e,t,i){for(var s=e;s&&Zr(s)&&!Xr(s,"body");){if(s===i)return!1;var r=void 0;try{var n,o,a;r=null==(n=null!==(o=null==(a=s.ownerDocument)?void 0:a.defaultView)&&void 0!==o?o:ke)?void 0:n.getComputedStyle(s).position}catch(e){return!1}if(qe(t,r))return!0;s=hn(s)}return!1}(un(e),["fixed","sticky"],r);return{x:e.clientX+(n?0:s),y:e.clientY+(n?0:i),target_fixed:n,type:t}}_onClick(e,t){var s;if(void 0===t&&(t="click"),!Yr(e.target)&&au(e)){var r=this._getProperties(e,t);null!=(s=this.rageclicks)&&s.isRageClick(e.clientX,e.clientY,(new Date).getTime())&&yn(un(e),this.instance.config.rageclick)&&this._capture(i({},r,{type:"rageclick"})),this._capture(r)}}_onMouseMove(e){!Yr(e.target)&&au(e)&&(clearTimeout(this._mouseMoveTimeout),this._mouseMoveTimeout=setTimeout((()=>{this._capture(this._getProperties(e,"mousemove"))}),500))}_capture(e){if(ke){var t=this._config.disable_capture_url_hashes?Vi(ke.location.href):ke.location.href,i=this._config.custom_personal_data_properties,s=this._config.mask_personal_data_properties?[...ro,...i||[]]:[],r=Xn(t,s,oo);this._buffer=this._buffer||{},this._buffer[r]||(this._buffer[r]=[]),this._buffer[r].push(e)}}_flush(){this._buffer&&!Xe(this._buffer)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:qn,webVitalsAutocapture:class{constructor(e){var t;this._enabledServerSide=!1,this._initialized=!1,this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this._flushToCapture=()=>{clearTimeout(this._delayedFlushTimer),this._delayedFlushTimer=void 0,0!==this._buffer.metrics.length&&(this._instance.capture("$web_vitals",i({$current_url:this._buffer.url},this._buffer.metrics.reduce(((e,t)=>i({},e,{["$web_vitals_"+t.name+"_event"]:i({},t),["$web_vitals_"+t.name+"_value"]:t.value})),{}))),this._buffer={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this._addToBuffer=e=>{var t;if(this._buffer=this._buffer||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},rt(null==e?void 0:e.name)||rt(null==e?void 0:e.value))Ql.error("Invalid metric received",e);else{var s="string"==typeof e.navigationURL?e.navigationURL:void 0,r=this._maskedURL(s);if(!et(r)){var n=nt(e.navigationId)||"string"==typeof e.navigationId?"navigation:"+e.navigationId:"url:"+r;if(!this._maxAllowedValue||this._maxAllowedValue>e.value){this._buffer.navigationKey!==n&&(this._flushToCapture(),this._delayedFlushTimer=setTimeout(this._flushToCapture,this.flushToCaptureTimeoutMs)),et(this._buffer.navigationKey)&&(this._buffer.navigationKey=n,this._buffer.url=r),this._buffer.firstMetricTimestamp=et(this._buffer.firstMetricTimestamp)?Date.now():this._buffer.firstMetricTimestamp;var o=null==(t=this._instance.sessionManager)?void 0:t.checkAndGetSessionAndWindowId(!0),a=i({},e,s?{navigationURL:r}:{},{$current_url:r,timestamp:Date.now()});if(delete a.entries,Ze(e.attribution)&&this.attributionMetrics.indexOf(e.name)>-1){var l={};for(var u of Xl){var c="url"===u&&"string"==typeof e.attribution[u]?this._maskedURL(e.attribution[u]):e.attribution[u];et(c)||(l[u]=c)}a.attribution=l}else delete a.attribution;et(o)||(a.$session_id=o.sessionId,a.$window_id=o.windowId),this._buffer.metrics.push(a),this._buffer.metrics.length===this.allowedMetrics.length&&this._flushToCapture()}else Ql.error("Ignoring metric with value >= "+this._maxAllowedValue,e)}}},this._startCapturing=()=>{if(!this._initialized){var e,t,s,r,n=!1,o=Oe.__PosthogExtensions__,a=null==o?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(null==a?void 0:a[this._callbackFlavor])||("web-vitals"===this._callbackFlavor&&et(a)?null==o?void 0:o.postHogWebVitalsCallbacks:void 0);if(!et(l)){var u=l.withoutAttribution,c=this.attributionMetrics;n=!et(u),e=c.indexOf("LCP")>-1?l.onLCP:(null==u?void 0:u.onLCP)||l.onLCP,t=c.indexOf("CLS")>-1?l.onCLS:(null==u?void 0:u.onCLS)||l.onCLS,s=c.indexOf("FCP")>-1?l.onFCP:(null==u?void 0:u.onFCP)||l.onFCP,r=c.indexOf("INP")>-1?l.onINP:(null==u?void 0:u.onINP)||l.onINP}if(e&&t&&s&&r){var d={reportSoftNavs:this.useSoftNavs},h=n&&this.attributionMetrics.indexOf("INP")>-1?i({},d,{includeProcessedEventEntries:!1}):d;this.allowedMetrics.indexOf("LCP")>-1&&e(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("CLS")>-1&&t(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("FCP")>-1&&s(this._addToBuffer.bind(this),d),this.allowedMetrics.indexOf("INP")>-1&&r(this._addToBuffer.bind(this),h),this._initialized=!0}else Ql.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this._enabledServerSide=!(null==(t=this._instance.persistence)||!t.props[m]),this.startIfEnabled()}get _perfConfig(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,i=Ze(this._perfConfig)?null==(e=this._perfConfig)?void 0:e.web_vitals_allowed_metrics:void 0;return rt(i)?(null==(t=this._instance.persistence)?void 0:t.props[w])||Yl:i}get flushToCaptureTimeoutMs(){return(Ze(this._perfConfig)?this._perfConfig.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){var e=Ze(this._perfConfig)?this._perfConfig.web_vitals_attribution:void 0;return at(e)?e?Yl:[]:Je(e)?e:Zl}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){var e=Ze(this._perfConfig)?this._perfConfig.__preview_web_vitals_soft_navs:void 0;return null!=e&&e}get _maxAllowedValue(){var e=Ze(this._perfConfig)&&nt(this._perfConfig.__web_vitals_max_value)?this._perfConfig.__web_vitals_max_value:Jl;return e>0&&6e4>=e?Jl:e}get isEnabled(){var e=null==Fe?void 0:Fe.protocol;if("http:"!==e&&"https:"!==e)return Ql.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=Ze(this._perfConfig)?this._perfConfig.web_vitals:at(this._perfConfig)?this._perfConfig:void 0;return at(t)?t:this._enabledServerSide}startIfEnabled(){this.isEnabled&&!this._initialized&&(Ql.info("enabled, starting..."),this._loadScript(this._startCapturing))}onRemoteConfig(e){if(e.ok){var t=e.config;if("capturePerformance"in t){var i=Ze(t.capturePerformance)&&!!t.capturePerformance.web_vitals,s=Ze(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[m]:i}),this._instance.persistence.register({[w]: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=Oe.__PosthogExtensions__,i=this._callbackFlavor,s=null==t?void 0:t.postHogWebVitalsCallbacksByFlavor;null!=s&&s[i]||"web-vitals"===i&&et(s)&&null!=t&&t.postHogWebVitalsCallbacks?e():null==t||null==t.loadExternalDependency||t.loadExternalDependency(this._instance,i,(t=>{t?Ql.error("failed to load script",t):e()}))}_maskedURL(e){var t=e||(null==ke?void 0:ke.location.href);if(t){var i=this._instance.config.disable_capture_url_hashes?Vi(t):t,s=this._instance.config.custom_personal_data_properties,r=this._instance.config.mask_personal_data_properties?[...ro,...s||[]]:[];return Xn(i,r,oo)}Ql.error("Could not determine current URL")}}},Xu={exceptionObserver:class{constructor(e){var t;this._startCapturing=()=>{var e;if(ke&&this.isEnabled&&null!=(e=Oe.__PosthogExtensions__)&&e.errorWrappingFunctions){var t=Oe.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=Oe.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=Oe.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this._unwrapOnError&&this._config.capture_unhandled_errors&&(this._unwrapOnError=t(this.captureException.bind(this))),!this._unwrapUnhandledRejection&&this._config.capture_unhandled_rejections&&(this._unwrapUnhandledRejection=i(this.captureException.bind(this))),!this._unwrapConsoleError&&this._config.capture_console_errors&&(this._unwrapConsoleError=s(this.captureException.bind(this)))}catch(e){Vl.error("failed to start",e),this._stopCapturing()}}},this._instance=e,this._remoteEnabled=!(null==(t=this._instance.persistence)||!t.props[g]),this._rateLimiter=new bt(i({},function(e){var t,i,s,r;return void 0===e&&(e={}),{refillRate:null!==(t=null!==(i=e.exceptionRateLimiterRefillRate)&&void 0!==i?i:e.__exceptionRateLimiterRefillRate)&&void 0!==t?t:1,bucketSize:null!==(s=null!==(r=e.exceptionRateLimiterBucketSize)&&void 0!==r?r:e.__exceptionRateLimiterBucketSize)&&void 0!==s?s:10}}(this._instance.config.error_tracking),{refillInterval:1e4,_logger:Vl})),this._config=this._requiredConfig(),this.startIfEnabledOrStop()}_requiredConfig(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Ze(e)?t=i({},t,e):(et(e)?this._remoteEnabled:e)&&(t=i({},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?(Vl.info("enabled"),this._stopCapturing(),this._loadScript(this._startCapturing)):this._stopCapturing()}_loadScript(e){var t,i;null!=(t=Oe.__PosthogExtensions__)&&t.errorWrappingFunctions?e():null==(i=Oe.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"exception-autocapture",(t=>{if(t)return Vl.error("failed to load script",t);e()}))}_stopCapturing(){var e,t,i;null==(e=this._unwrapOnError)||e.call(this),this._unwrapOnError=void 0,null==(t=this._unwrapUnhandledRejection)||t.call(this),this._unwrapUnhandledRejection=void 0,null==(i=this._unwrapConsoleError)||i.call(this),this._unwrapConsoleError=void 0}onRemoteConfig(e){if(e.ok){var t=e.config;"autocaptureExceptions"in t&&(this._remoteEnabled=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[g]:this._remoteEnabled}),this._config=this._requiredConfig(),this.startIfEnabledOrStop())}}onConfigChange(){this._config=this._requiredConfig()}captureException(e){try{var t,i,s,r=null!==(t=null==e||null==(i=e.$exception_list)||null==(i=i[0])?void 0:i.type)&&void 0!==t?t:"Exception";if(this._rateLimiter.consumeRateLimit(r))return void Vl.info("Skipping exception capture because of client rate limiting.",{exception:r});null==(s=this._instance.exceptions)||s.sendExceptionEvent(e)}catch(e){}}},exceptions:class{constructor(e){var t,s;this._suppressionRules=[],this._errorPropertiesBuilder=new Qi([new as,new fs,new us,new ls,new gs,new ps,new ds,new vs],function(e){for(var t=arguments.length,s=new Array(t>1?t-1:0),r=1;t>r;r++)s[r-1]=arguments[r];return function(t,r){void 0===r&&(r=0);for(var n=[],o=t.split("\n"),a=r;o.length>a;a++){var l=o[a];if(1024>=l.length){var u=os.test(l)?l.replace(os,"$1"):l;if(!u.match(/\S*Error: /)){for(var c of s){var d=c(u,e);if(d){n.push(d);break}}if(n.length>=50)break}}}return function(e){if(!e.length)return[];var t=Array.from(e);return t.reverse(),t.slice(0,50).map((e=>{return i({},e,{filename:e.filename||(s=t,s[s.length-1]||{}).filename,function:e.function||Ji});var s}))}(n)}}("web:javascript",is,ns)),this._instance=e,this._suppressionRules=null!==(t=null==(s=this._instance.persistence)?void 0:s.get_property(v))&&void 0!==t?t:[],this._exceptionStepsConfig=ws(this._getExceptionStepsConfig()),this._exceptionStepsBuffer=new Cs(this._exceptionStepsConfig)}onConfigChange(){this._exceptionStepsConfig=ws(this._getExceptionStepsConfig()),this._exceptionStepsBuffer.setConfig(this._exceptionStepsConfig)}onRemoteConfig(e){var t,i,s;if(e.ok){var r=e.config;if("errorTracking"in r){var n=null!==(t=null==(i=r.errorTracking)?void 0:i.suppressionRules)&&void 0!==t?t:[],o=null==(s=r.errorTracking)?void 0:s.captureExtensionExceptions;this._suppressionRules=n,this._instance.persistence&&this._instance.persistence.register({[v]:this._suppressionRules,[f]:o})}}}get _captureExtensionExceptions(){var e,t=!!this._instance.get_property(f),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(!tt(e)||0===e.trim().length)return void $u.warn("Ignoring exception step because message must be a non-empty string");var s=function(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};var t=[];return{sanitizedProperties:Object.keys(e).reduce(((i,s)=>bs.has(s)?(t.push(s),i):(i[s]=e[s],i)),{}),droppedKeys:t}}(this._coerceExceptionStepProperties(t)),r=s.sanitizedProperties,n=s.droppedKeys;n.length>0&&$u.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this._exceptionStepsBuffer.add(i({[ms]:e,[ys]:(new Date).toISOString()},r))}catch(e){$u.error("Failed to add exception step. Ignoring breadcrumb.",e)}}sendExceptionEvent(e){try{var t=e.$exception_list;if(this._isExceptionList(t)){if(this._matchesSuppressionRule(t))return this._addDroppedExceptionStep("Exception dropped: matched a suppression rule"),void $u.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 $u.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 $u.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 $u.info("Skipping exception capture because it was thrown by the PostHog SDK")}var i=this._exceptionStepsConfig.enabled&&rt(e.$exception_steps)?this._addBufferedExceptionSteps(e):e,s="string"==typeof(n=globalThis._posthogReleaseId)&&n.length>0?n:void 0;s&&(i.$release_id=s);try{var r=this._instance.capture("$exception",i,{_noTruncate:!0,_batchKey:"exceptionEvent",_originatedFromCaptureException:!0});return r&&this._exceptionStepsBuffer.clear(),r}catch(e){return Mu(e)||$u.error("Failed to capture exception event. Dropping this exception.",e),void this._exceptionStepsBuffer.clear()}}catch(e){return void(Mu(e)||$u.error("Failed to process exception event. Ignoring this exception.",e))}var n}_addBufferedExceptionSteps(e){try{var t=this._exceptionStepsBuffer.getAttachable();return 0===t.length?e:i({},e,{$exception_steps:t})}catch(t){return $u.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_addDroppedExceptionStep(e){this._exceptionStepsConfig.enabled&&this._exceptionStepsBuffer.add({[ms]:e,[ys]:(new Date).toISOString()})}_coerceExceptionStepProperties(e){return Ze(e)?i({},e):{}}_getExceptionStepsConfig(){var e,t;return null!==(e=null==(t=this._instance.config.error_tracking)?void 0:t.exception_steps)&&void 0!==e?e:{}}_matchesSuppressionRule(e){if(0===e.length)return!1;try{var t=e.reduce(((e,t)=>{var i=t.type,s=t.value;return tt(i)&&i.length>0&&e.$exception_types.push(i),tt(s)&&s.length>0&&e.$exception_values.push(s),e}),{$exception_types:[],$exception_values:[]});return this._suppressionRules.some((e=>{var i=e.values.map((e=>{var i=Za[e.operator],s=t[e.key];if(!i||!s)return!1;var r=Je(e.value)?e.value:[e.value];return r.length>0&&i(r,s)}));return"OR"===e.type?i.some(Boolean):i.every(Boolean)}))}catch(e){return $u.warn("Failed to evaluate suppression rules. Capturing the exception.",e),!1}}_isExtensionException(e){var t=e.flatMap((e=>{var t,i;return null!==(t=null==(i=e.stacktrace)?void 0:i.frames)&&void 0!==t?t:[]})),i=t.filter((e=>{var t=e.filename;return!!t&&Du.some((e=>t.startsWith(e)))}));return 0!==i.length&&(!i.every((e=>{var t=e.filename;return!!t&&t.startsWith(Ou)}))||e.some((e=>{var t=e.value;return tt(t)&&t.includes("isolatedAPI.contexts.topHostname")}))&&!t.some((e=>{var t=e.filename;return e.in_app&&!(null!=t&&t.startsWith(Ou))})))}_isInjectedBrowserScriptException(e){return e.some((e=>{var t=e.value;return tt(t)&&Bu.some((e=>t.includes(e)))}))}_isPostHogException(e){if(e.length>0){var t,i,s,r,n=null!==(t=null==(i=e[0].stacktrace)?void 0:i.frames)&&void 0!==t?t:[],o=n[n.length-1];return null!==(s=null==o||null==(r=o.filename)?void 0:r.includes("posthog.com/static"))&&void 0!==s&&s}return!1}_isExceptionList(e){return!rt(e)&&Je(e)}}},ec=i({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){var t=e.config;if("productTours"in t){var i,s;if(this._persistence&&this._persistence.register({[b]:!!t.productTours}),!uu(this._instance))return!this._productTourManager&&rt(null==(i=this._persistence)?void 0:i.props[Q])||lu.info("product tours disabled; stopping and clearing cached tours"),null==(s=this._productTourManager)||s.stop(),this._productTourManager=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this._productTourManager&&uu(this._instance)&&this._loadScript((()=>this._startProductTours()))}_loadScript(e){var t,i;null!=(t=Oe.__PosthogExtensions__)&&t.generateProductTours?e():null==(i=Oe.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"product-tours",(t=>{t?lu.error("Could not load product tours script",t):e()}))}_startProductTours(){var e;!this._productTourManager&&null!=(e=Oe.__PosthogExtensions__)&&e.generateProductTours&&(this._productTourManager=Oe.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(void 0===t&&(t=!1),!Je(this._cachedTours)||t){var i=this._persistence;if(i){var s=i.props[Q];if(Je(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(uu(this._instance)){var s=t.statusCode;if(200!==s||!t.json){var r="Product Tours API could not be loaded, status: "+s;return 0===s?t.error||lu.warn(r):lu.error(r),void e([],{isLoaded:!1,error:r})}var n=Je(t.json.product_tours)?t.json.product_tours:[];this._cachedTours=n,i&&i.register({[Q]:n}),e(n,{isLoaded:!0})}else e([],{isLoaded:!0})}})}else e(this._cachedTours,{isLoaded:!0})}getActiveProductTours(e){rt(this._productTourManager)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this._productTourManager.getActiveProductTours(e)}showProductTour(e){var t;null==(t=this._productTourManager)||t.showTourById(e)}previewTour(e){this._productTourManager?this._productTourManager.previewTour(e):this._loadScript((()=>{var t;this._startProductTours(),null==(t=this._productTourManager)||t.previewTour(e)}))}dismissProductTour(){var e;null==(e=this._productTourManager)||e.dismissTour("user_clicked_skip")}nextStep(){var e;null==(e=this._productTourManager)||e.nextStep()}previousStep(){var e;null==(e=this._productTourManager)||e.previousStep()}clearCache(){var e;this._cachedTours=null,null==(e=this._persistence)||e.unregister(Q)}resetTour(e){var t;null==(t=this._productTourManager)||t.resetTour(e)}resetAllTours(){var e;null==(e=this._productTourManager)||e.resetAllTours()}cancelPendingTour(e){var t;null==(t=this._productTourManager)||t.cancelPendingTour(e)}}},Ju),tc={siteApps:class{constructor(e){this._siteAppElementPatchCount=0,this._instance=e,this._bufferedInvocations=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}_eventCollector(e,t){if(t){var 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=Oe._POSTHOG_REMOTE_CONFIG)||null==(e=e[this._instance.config.token])?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this._eventCollector.bind(this));this._stopBuffering=()=>{e(),this._bufferedInvocations=[],this._stopBuffering=void 0}}}globalsForEvent(e){var t,r,n,o,a,l,u;if(!e)throw new Error("Event payload is required");var c={},d=this._instance.get_property("$groups")||[],h=this._instance.get_property("$stored_group_properties")||{};for(var _ of Object.entries(h)){var p=_[0];c[p]={id:d[p],type:p,properties:_[1]}}var g=e.$set_once,v=e.$set;return{event:i({},s(e,cu),{properties:i({},e.properties,v?{$set:i({},null!==(t=null==(r=e.properties)?void 0:r.$set)&&void 0!==t?t:{},v)}:{},g?{$set_once:i({},null!==(n=null==(o=e.properties)?void 0:o.$set_once)&&void 0!==n?n:{},g)}:{}),elements_chain:null!==(a=null==(l=e.properties)?void 0:l.$elements_chain)&&void 0!==a?a:"",distinct_id:null==(u=e.properties)?void 0:u.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}_prepareElementForSiteApp(e){var t,i=null==(t=e.tagName)?void 0:t.toLowerCase();return"style"===i&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(du.error("prepare_external_dependency_stylesheet returned null"),null):"script"===i&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(du.error("prepare_external_dependency_script returned null"),null):e}_patchSiteAppElementInsertionMethods(){var e,t,i,s,r,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=null==Pe?void 0:Pe.defaultView,u=null==l||null==(e=l.Node)?void 0:e.prototype;if(!l||!u)return()=>{};if(this._siteAppElementPatchCount++,this._restoreSiteAppElementPatches)return this._releaseSiteAppElementPatches();var c=[],d=this,h=new WeakSet,_=(e,t,i)=>{if(null!=e&&e[t]){var s=e[t];e[t]=i(s),c.push((()=>{e[t]=s}))}},p=e=>{if(h.has(e))return e;var t=d._prepareElementForSiteApp(e);return t&&h.add(t),t},g=e=>e.map((e=>"string"==typeof e?e:p(e))).filter((e=>!st(e)));return _(u,"appendChild",(e=>function(t){var i=p(t);return i?e.call(this,i):t})),_(u,"insertBefore",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):t})),_(u,"replaceChild",(e=>function(t,i){var s=p(t);return s?e.call(this,s,i):i})),[null==(t=l.Element)?void 0:t.prototype,null==(i=l.Document)?void 0:i.prototype,null==(s=l.DocumentFragment)?void 0:s.prototype].forEach((e=>{_(e,"append",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"prepend",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))}))})),[null==(r=l.Element)?void 0:r.prototype,null==(n=l.CharacterData)?void 0:n.prototype,null==(o=l.DocumentType)?void 0:o.prototype].forEach((e=>{_(e,"before",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"after",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];return e.apply(this,g(i))})),_(e,"replaceWith",(e=>function(){for(var t=arguments.length,i=new Array(t),s=0;t>s;s++)i[s]=arguments[s];var r=g(i);return i.length&&!r.length?void 0:e.apply(this,r)}))})),_(null==(a=l.Element)?void 0:a.prototype,"insertAdjacentElement",(e=>function(t,i){var s=p(i);return s?e.call(this,t,s):null})),this._restoreSiteAppElementPatches=()=>{c.forEach((e=>e())),this._restoreSiteAppElementPatches=void 0},this._releaseSiteAppElementPatches()}_releaseSiteAppElementPatches(){var e=!1;return()=>{var t;e||(e=!0,this._siteAppElementPatchCount--,0===this._siteAppElementPatchCount&&(null==(t=this._restoreSiteAppElementPatches)||t.call(this)))}}_runWithPreparedSiteAppElements(e,t){void 0===t&&(t=!0);var i=this._patchSiteAppElementInsertionMethods();try{var s=e(i);return t&&i(),s}catch(e){throw i(),e}}setupSiteApp(e){var t=this.apps[e.id],i=()=>{var i;!t.errored&&this._bufferedInvocations.length&&(du.info("Processing "+this._bufferedInvocations.length+" events for site app with id "+e.id),this._bufferedInvocations.forEach((e=>this._runWithPreparedSiteAppElements((()=>null==t.processEvent?void 0:t.processEvent(e))))),t.processedBuffer=!0),Object.values(this.apps).every((e=>e.processedBuffer||e.errored))&&(null==(i=this._stopBuffering)||i.call(this))},s=!1,r=r=>{t.errored=!r,t.loaded=!0,du.info("Site app with id "+e.id+" "+(r?"loaded":"errored")),s&&i()};try{var n=this._runWithPreparedSiteAppElements((t=>e.init({posthog:this._instance,callback(e){t(),r(e)}})),!1).processEvent;n&&(t.processEvent=n),s=!0}catch(t){du.error(hu+e.id,t),r(!1)}if(s&&t.loaded)try{i()}catch(i){du.error("Error while processing buffered events PostHog app with config id "+e.id,i),t.errored=!0}}_setupSiteApps(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}_onCapturedEvent(e){var t=this;if(0!==Object.keys(this.apps).length){var i=this.globalsForEvent(e),s=function(s){try{t._runWithPreparedSiteAppElements((()=>null==s.processEvent?void 0:s.processEvent(i)))}catch(t){du.error("Error while processing event "+e.event+" for site app "+s.id,t)}};for(var r of Object.values(this.apps))s(r)}}onRemoteConfig(e){var t,i,s,r=this;if(null!=(t=this.siteAppLoaders)&&t.length)return this.isEnabled?(this._setupSiteApps(),void this._instance.on("eventCaptured",(e=>this._onCapturedEvent(e)))):void du.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if(null==(i=this._stopBuffering)||i.call(this),e.ok){var n=e.config;if(null!=(s=n.siteApps)&&s.length)if(this.isEnabled){var o=function(){var e,t=a.id,i=a.url;Oe["__$$ph_site_app_"+t]=r._instance,null==(e=Oe.__PosthogExtensions__)||null==e.loadSiteApp||e.loadSiteApp(r._instance,i,(e=>{if(e)return du.error(hu+t,e)}))};for(var a of n.siteApps)o()}else du.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},ic={tracingHeaders:class{constructor(e){this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0,this._hostnamesForPatch=void 0,this._startCapturing=()=>{var e,t,i=this._syncHostnamesForPatch();i?(et(this._restoreXHRPatch)&&(this._restoreXHRPatch=null==(e=Oe.__PosthogExtensions__)||null==(e=e.tracingHeadersPatchFns)?void 0:e._patchXHR(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager)),et(this._restoreFetchPatch)&&(this._restoreFetchPatch=null==(t=Oe.__PosthogExtensions__)||null==(t=t.tracingHeadersPatchFns)?void 0:t._patchFetch(i,(()=>this._instance.get_distinct_id()),this._instance.sessionManager))):this._stopCapturing()},this._instance=e}initialize(){this.startIfEnabledOrStop()}_loadScript(e){var t,i;null!=(t=Oe.__PosthogExtensions__)&&t.tracingHeadersPatchFns?e():null==(i=Oe.__PosthogExtensions__)||null==i.loadExternalDependency||i.loadExternalDependency(this._instance,"tracing-headers",(t=>{if(t)return Kl.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(){var e=this._getConfiguredHostnames();return Je(e)?(Je(this._hostnamesForPatch)?this._hostnamesForPatch.splice(0,this._hostnamesForPatch.length,...e):this._hostnamesForPatch=[...e],e.length>0?this._hostnamesForPatch:void 0):(Je(this._hostnamesForPatch)&&this._hostnamesForPatch.splice(0),this._hostnamesForPatch=e||void 0,this._hostnamesForPatch)}_stopCapturing(){var e,t;null==(e=this._restoreXHRPatch)||e.call(this),null==(t=this._restoreFetchPatch)||t.call(this),this._restoreXHRPatch=void 0,this._restoreFetchPatch=void 0}startIfEnabledOrStop(){this._syncHostnamesForPatch()?this._loadScript(this._startCapturing):this._stopCapturing()}}},sc=i({surveys:class extends vu{constructor(e){var t;super(new wu(e),{get projectToken(){return t.config.token},kv:new Su(t=e)}),this._instance=e}_sendSurveysRequest(e,t){var i=t.query?Ea(e,t.query):e;return new Promise((e=>{var s;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor(null!==(s=t.target)&&void 0!==s?s:"api",i),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:e})}))}}},Ju),rc={toolbar:class{constructor(e){this.instance=e}_setToolbarState(e){Oe.ph_toolbar_state=e}_getToolbarState(){var e;return null!==(e=Oe.ph_toolbar_state)&&void 0!==e?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,i){if(void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),vr(this.instance.config))return!1;if(!ke||!Pe)return!1;e=null!=e?e:ke.location,i=null!=i?i:ke.history;try{if(!t){try{ke.localStorage.setItem("test","test"),ke.localStorage.removeItem("test")}catch(e){return!1}t=null==ke?void 0:ke.localStorage}var s,r=Cu||eo(e.hash,"__posthog")||eo(e.hash,"state"),n=r?cr((()=>JSON.parse(atob(decodeURIComponent(r)))))||cr((()=>JSON.parse(decodeURIComponent(r)))):null;return n&&"ph_authorize"===n.action?((s=n).source="url",s&&Object.keys(s).length>0&&(n.desiredHash?e.hash=n.desiredHash:i?i.replaceState(i.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(t.getItem(ku)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token||(this.loadToolbar(s),0))}catch(e){return!1}}_callLoadToolbar(e){var t=Oe.ph_load_toolbar||Oe.ph_load_editor;!rt(t)&&Ye(t)?t(e,this.instance):Eu.warn("No toolbar load function found")}loadToolbar(e){var t=!(null==Pe||!Pe.getElementById(Gr));if(!ke||t)return!1;var s="custom"===this.instance.requestRouter.region&&this.instance.config.advanced_disable_toolbar_metrics,r=i({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(ke.localStorage.setItem(ku,JSON.stringify(i({},r,{source:void 0}))),2===this._getToolbarState())this._callLoadToolbar(r);else if(0===this._getToolbarState()){var n;this._setToolbarState(1),null==(n=Oe.__PosthogExtensions__)||null==n.loadExternalDependency||n.loadExternalDependency(this.instance,"toolbar",(e=>{if(e)return Eu.error("[Toolbar] Failed to load",e),void this._setToolbarState(0);this._setToolbarState(2),this._callLoadToolbar(r)})),gr(ke,"turbolinks:load",(()=>{this._setToolbarState(0),this.loadToolbar(r)}))}return!0}_loadEditor(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,i){return void 0===e&&(e=void 0),void 0===t&&(t=void 0),void 0===i&&(i=void 0),this.maybeLoadToolbar(e,t,i)}}},nc=i({experiments:Nu},Ju),oc={conversations:class{constructor(e){this._isConversationsEnabled=void 0,this._conversationsManager=null,this._isInitializing=!1,this._remoteConfig=null,this._loadFailed=!1,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations&&(this._remoteConfigSuccessful=e.ok,e.ok)){var t=e.config.conversations;rt(t)||(at(t)?this._isConversationsEnabled=t:(this._isConversationsEnabled=t.enabled,this._remoteConfig=t),this.loadIfEnabled())}}reset(){var e;null==(e=this._conversationsManager)||e.reset(),this._conversationsManager=null,this._isConversationsEnabled=void 0,this._remoteConfig=null,this._remoteConfigSuccessful=void 0,this._loadFailed=!1}loadIfEnabled(){if(!(this._conversationsManager||this._isInitializing||this._instance.config.disable_conversations||vr(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=null==Oe?void 0:Oe.__PosthogExtensions__;if(e&&!et(this._isConversationsEnabled)&&this._isConversationsEnabled)if(this._remoteConfig&&this._remoteConfig.token){this._isInitializing=!0;try{var t=e.initConversations;if(t)return this._completeInitialization(t),void(this._isInitializing=!1);var i=e.loadExternalDependency;if(!i)return void this._handleLoadError(he);i(this._instance,"conversations",(t=>{t||!e.initConversations?this._handleLoadError("Could not load conversations script",t):this._completeInitialization(e.initConversations),this._isInitializing=!1}))}catch(e){this._handleLoadError("Error initializing conversations",e),this._isInitializing=!1}}else zu.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,zu.info("Conversations loaded successfully")}catch(e){this._handleLoadError("Error completing conversations initialization",e)}else zu.error("Cannot complete initialization: remote config is null")}_handleLoadError(e,t){zu.error(e,t),this._conversationsManager=null,this._isInitializing=!1,this._loadFailed=!0}show(){this._conversationsManager?this._conversationsManager.show():zu.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}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":et(this._isConversationsEnabled)?this._remoteConfigSuccessful?"disabled_in_project":"remote_config_pending":this._isConversationsEnabled?rt(this._remoteConfig)||!this._remoteConfig.token?"missing_token":null!=Oe&&Oe.__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.isVisible())&&void 0!==e&&e}sendMessage(e,i,s){var r=this;return t((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,i,s):(zu.warn(ju),null)}))()}getMessages(e,i){var s=this;return t((function*(){return s._conversationsManager?s._conversationsManager.getMessages(e,i):(zu.warn(ju),null)}))()}markAsRead(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.markAsRead(e):(zu.warn(ju),null)}))()}getTickets(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.getTickets(e):(zu.warn(ju),null)}))()}requestRestoreLink(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.requestRestoreLink(e):(zu.warn(ju),null)}))()}restoreFromToken(e){var i=this;return t((function*(){return i._conversationsManager?i._conversationsManager.restoreFromToken(e):(zu.warn(ju),null)}))()}restoreFromUrlToken(){var e=this;return t((function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(zu.warn(ju),null)}))()}getCurrentTicketId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getCurrentTicketId())&&void 0!==e?e:null}getWidgetSessionId(){var e,t;return null!==(e=null==(t=this._conversationsManager)?void 0:t.getWidgetSessionId())&&void 0!==e?e:null}_onIdentityChanged(){var e;null==(e=this._conversationsManager)||e.setIdentity()}_onIdentityCleared(){var e;null==(e=this._conversationsManager)||e.clearIdentity()}}},ac={logs:class{constructor(e){var t,s=this;this.name="logs",this._isLogsEnabled=!1,this._isLoaded=!1,this._isLoading=!1,this._logger=nr("[logs]"),this._coreLogger=i({},this._logger,{error(){for(var e=arguments.length,t=new Array(e),i=0;e>i;i++)t[i]=arguments[i];t.some(Qu)||s._logger.error(...t)}}),this._queue=[],this._consoleQueue=[],this._consecutiveStatusZeroFailures=0,this._disposed=!1,this._consoleBuffer=[],this._consoleRecorderUnpatchers=[],this._isRecordingConsole=!1,this._isRecordingConsoleEntry=!1,this._onReconnect=()=>{var e,t;this._disposed||(this._consecutiveStatusZeroFailures=0,null==(e=this._core)||e.onReconnect(),null==(t=this._consoleCore)||t.onReconnect())},this._instance=e,this._instance&&null!=(t=this._instance.config.logs)&&t.captureConsoleLogs&&(this._isLogsEnabled=!0),ke&&gr(ke,"online",this._onReconnect)}_buildCore(e,t,i,s){var r,n=Vu(null==(r=this._instance)||null==(r=r.config)?void 0:r.logs,i);return[new Zs(this._createHost(e,t),n,this._coreLogger,(()=>this._getSdkContext()),(e=>e()),void 0,s),n]}_getCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._core||this._resolvedFrom!==t){var i;null==(i=this._core)||i.reset(),this._resolvedFrom=t;var s=this._buildCore((()=>this._queue),(e=>{this._queue=e}));this._core=s[0],this._resolvedConfig=s[1]}return this._core}_getConsoleCore(){var e,t=null==(e=this._instance)||null==(e=e.config)?void 0:e.logs;if(!this._consoleCore||this._consoleResolvedFrom!==t){var i;null==(i=this._consoleCore)||i.reset(),this._consoleResolvedFrom=t;var s=this._buildCore((()=>this._consoleQueue),(e=>{this._consoleQueue=e}),{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Wu);this._consoleCore=s[0],this._consoleResolvedConfig=s[1]}return this._consoleCore}setup(e){var t;if(!this._disposed){this._client=e,null!=(t=this._instance)&&null!=(t=t.config)&&null!=(t=t.logs)&&t.captureConsoleLogs&&(this._isLogsEnabled=!0),(this._isLogsEnabled||this._remoteConfigWillArrive()&&this._persistedCaptureHint())&&this._startConsoleRecorder();var i=!1,s=e.onRemoteConfig((e=>{var t;i=e.ok&&!0===(null==(t=e.config.logs)?void 0:t.captureConsoleLogs),this.onRemoteConfig(e)}));this._disposed?s.dispose():(this._remoteConfigSubscription=s,i||this.loadIfEnabled())}}dispose(){var e,t,i,s;this._disposed||(this._disposed=!0,this._stopConsoleRecorder(),null==(e=this._remoteConfigSubscription)||e.dispose(),this._remoteConfigSubscription=void 0,this._client=void 0,this._isLoading=!1,null==ke||ke.removeEventListener("online",this._onReconnect),null==(t=this._consoleLogsDispose)||t.call(this),this._consoleLogsDispose=void 0,null==(i=this._core)||i.reset(),null==(s=this._consoleCore)||s.reset())}onRemoteConfig(e){var t,i;if(!this._disposed){var s=e.ok?null==(t=e.config.logs)?void 0:t.captureConsoleLogs:void 0;rt(s)?this._stopRecorderStartedByPersistedHint():(null==(i=this._instance)||null==(i=i.persistence)||i.register({[S]:!!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)||e.clearQueue(),this._queue=[],null==(t=this._core)||t.reset(),null==(i=this._consoleCore)||i.clearQueue(),this._consoleQueue=[],null==(s=this._consoleCore)||s.reset(),this._consecutiveStatusZeroFailures=0}captureLog(e){this._disposed||this._getCore().captureLog(e)}captureConsoleLog(e){this._disposed||this._getConsoleCore().captureLog(e)}captureBufferedConsoleLog(e,t,i){this._disposed||this._getConsoleCore().captureLog(e,{context:t,occurredAtMs:i})}_persistedCaptureHint(){var e;return!(null==(e=this._instance)||null==(e=e.persistence)||null==(e=e.props)||!e[S])}_remoteConfigWillArrive(){var e,t;return null==(e=this._instance)||null==e._shouldDisableFlags||!e._shouldDisableFlags()||!(null==(t=Oe._POSTHOG_REMOTE_CONFIG)||null==(t=t[this._instance.config.token])||!t.config)}_onOptOut(){var e;this._stopConsoleRecorder(),null==(e=this._consoleCore)||e.clearQueue(),this._consoleQueue=[]}_stopRecorderStartedByPersistedHint(){this._isLogsEnabled||this._stopConsoleRecorder()}_startConsoleRecorder(){var e,t=this;if(!this._isRecordingConsole&&null!=Oe&&Oe.console){var i=Vu(null==(e=this._instance)||null==(e=e.config)?void 0:e.logs).maxBufferSize,s=function(e){var s;try{s=(e=>{for(;null!=(t=e)&&t.__rrweb_original__;){var t;e=e.__rrweb_original__}return e})(Oe.console[e])}catch(e){return 0}if(!s)return 0;t._consoleRecorderUnpatchers.push(Gl(Oe.console,e,(r=>{var n=function(){for(var s=arguments.length,n=new Array(s),o=0;s>o;o++)n[o]=arguments[o];try{t._recordConsoleEntry(e,n,i)}catch(e){}return r.apply(Oe.console,n)};return n.__rrweb_original__=s,n})))};for(var r of Uu)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._instance)&&s.is_capturing()){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){for(var e of(this._isRecordingConsole=!1,this._consoleRecorderTimeout&&(clearTimeout(this._consoleRecorderTimeout),this._consoleRecorderTimeout=void 0),this._consoleRecorderUnpatchers))e();this._consoleRecorderUnpatchers=[]}}_takeConsoleBuffer(){var 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){e?this._flushViaTransport(e):(this._core&&this._core.flush().catch((e=>this._logFlushError(e))),this._consoleCore&&this._consoleCore.flush().catch((e=>this._logFlushError(e))))}_logFlushError(e){Qu(e)||this._logger.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(!this._disposed&&this._isLogsEnabled&&!this._isLoaded&&!this._isLoading){var e=null==Oe?void 0:Oe.__PosthogExtensions__;if(!e)return this._logger.error("PostHog Extensions not found."),void this._stopConsoleRecorder();var t=e.loadExternalDependency;if(!t)return this._logger.error(he),void this._stopConsoleRecorder();this._isLoading=!0;try{t(this._instance,"logs",(t=>{if(this._isLoading=!1,!this._disposed&&this._isLogsEnabled){var i=e.logs;if(t||null==i||!i.initializeLogs)this._logger.error("Could not load logs script",t),this._stopConsoleRecorder();else{var s,r,n=this._takeConsoleBuffer();this._consoleLogsDispose=i.initializeLogs(null!==(s=this._client)&&void 0!==s?s:this._instance),this._isLoaded=!0,n.length>0&&(null==i.replayConsoleBuffer||i.replayConsoleBuffer(null!==(r=this._client)&&void 0!==r?r:this._instance,n))}}}))}catch(e){throw this._isLoading=!1,e}}}_createHost(e,t){var i=this._instance;return{get isDisabled(){return!1},get optedOut(){return!i.is_capturing()},getPersistedProperty:t=>t===je.LogsQueue?e():void 0,setPersistedProperty(e,i){var s;e===je.LogsQueue&&t(null!==(s=i)&&void 0!==s?s:[])},_sendLogsBatch:e=>this._sendLogsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendLogsBatch(e){return new Promise((t=>{if(to(this._consecutiveStatusZeroFailures,3))t({kind:"fatal",error:Ku(void 0,"logs endpoint is unreachable, dropping batch")});else{var i=!1,s=e=>{i||(i=!0,clearTimeout(r),t(e))},r=setTimeout((()=>{this._logger.warn("Logs request timed out before receiving a response"),s({kind:"retry-later",error:Ku(void 0,"logs request timed out")})}),9e4);this._instance._send_request({method:"POST",url:this._logsUrl(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:e=>{var t=e.statusCode;if(this._trackEndpointReachability(t),t>=200&&300>t)s({kind:"ok"});else if(413===t)s({kind:"too-large"});else if(0!==t&&408!==t&&429!==t&&500>t)s({kind:"fatal",error:new Error("logs request failed with status "+t)});else{var i;0===t?(e.error||this._logger.warn("Logs request failed before receiving an HTTP response"),s({kind:"retry-later",error:Ku(e.error,"logs request failed before receiving an HTTP response")})):s({kind:"retry-later",error:null!==(i=e.error)&&void 0!==i?i:new Error("logs request failed with status "+t)})}}})}}))}_trackEndpointReachability(e){(0!==e||this._instance.__loaded)&&(this._consecutiveStatusZeroFailures=io(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,r.LIB_NAME,(e=>{this._queue=e})),this._consoleQueue.length>0&&this._drainQueueViaTransport(e,this._consoleQueue,this._consoleResolvedConfig,Wu,(e=>{this._consoleQueue=e}))}_drainQueueViaTransport(e,t,i,s,n){if(0!==t.length){var o=t.map((e=>e.record));n([]);var a=Ys(o,Js(i,r.LIB_NAME,r.LIB_VERSION),s,r.LIB_VERSION);this._instance._send_request({method:"POST",url:this._logsUrl(),data:a,compression:"best-available",batchKey:"logs",transport:e})}}_logsUrl(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}_getSdkContext(){var e,t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var i=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),s=i.windowId,r=i.sessionStartTimestamp,n=i.lastActivityTimestamp;t.sessionId=i.sessionId,t.windowId=s,rt(r)||(t.sessionStartTimestamp=r),rt(n)||(t.lastActivityTimestamp=n)}if(null!=Oe&&null!=(e=Oe.location)&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Vi(Oe.location.href):Oe.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(t.activeFeatureFlags=o)}return t}}},lc={metrics:class{constructor(e){this._logger=nr("[metrics]"),this._instance=e}initialize(){}_getCore(){var e,t,i=null==(e=this._instance)||null==(e=e.config)?void 0:e.metrics;return this._core&&this._resolvedFrom===i||(null==(t=this._core)||t.reset(),this._resolvedFrom=i,this._core=new ir(this._createHost(),function(e){var t,i,s,r,n,o=null==e?void 0:e.resourceAttributes;return{serviceName:null!==(t=null==o?void 0:o["service.name"])&&void 0!==t?t:null==e?void 0:e.serviceName,serviceVersion:null!==(i=null==o?void 0:o["service.version"])&&void 0!==i?i:null==e?void 0:e.serviceVersion,environment:null!==(s=null==o?void 0:o["deployment.environment"])&&void 0!==s?s:null==e?void 0:e.environment,resourceAttributes:o,beforeSend:null==e?void 0:e.beforeSend,flushIntervalMs:null!==(r=null==e?void 0:e.flushIntervalMs)&&void 0!==r?r:1e4,maxSeriesPerFlush:null!==(n=null==e?void 0:e.maxSeriesPerFlush)&&void 0!==n?n:1e3}}(i),this._logger)),this._core}count(e,t,i){void 0===t&&(t=1),this._getCore().count(e,t,i)}gauge(e,t,i){this._getCore().gauge(e,t,i)}histogram(e,t,i){this._getCore().histogram(e,t,i)}flush(e){if(!this._core)return Promise.resolve();if(e){var 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)||e.reset()}_createHost(){var e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},_sendMetricsBatch:e=>t._sendMetricsBatch(e),getLibraryId:()=>r.LIB_NAME,getLibraryVersion:()=>r.LIB_VERSION}}_sendMetricsBatch(e,t){return new Promise((s=>{var r=!1,n=e=>{r||(r=!0,clearTimeout(o),s(e))},o=setTimeout((()=>n({kind:"retry-later",error:new Error("metrics request timed out")})),9e4);this._instance._send_request(i({method:"POST",url:this._metricsUrl(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t},{fireCallbackOnDrop:!0,callback(e){var 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)}}},uc=i({},Ju,Yu,Zu,Xu,ec,tc,sc,ic,rc,nc,oc,ac,lc);$l.__defaultExtensionClasses=i({},uc),function(){r.SDK_DIST_CHANNEL="cdn";var e=Oe.posthog;if(!e||Je(e._i)){var t=ml[Fl]=new $l;if(e){var i=[];ar(e._i,(function(s){if(s&&Je(s)){var r=t.init(s[0],s[1],s[2]),n=e[s[2]]||e;r.__loaded&&-1===i.indexOf(n)&&(i.push(n),r._execute_array.call(r.people,n.people),r._execute_array(n))}}))}t.__SV=1,Oe.posthog=t,function(){function e(){e.done||(e.done=!0,Il=!1,ar(ml,(function(e){e._dom_loaded()})))}null!=Pe&&Pe.addEventListener?"complete"===Pe.readyState?e():gr(Pe,"DOMContentLoaded",e,{capture:!1}):ke&&rr.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}()}}()}();