dexto 1.6.16 → 1.6.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,7 +26,7 @@ Error generating stack: `+d.message+`
26
26
  `),u=s;u<o.length;u++){var f=o[u];if(!(f.length>1024)){var h=zN.test(f)?f.replace(zN,"$1"):f;if(!h.match(/\S*Error: /)){for(var p of t){var g=p(h);if(g){i.push(g);break}}if(i.length>=$N)break}}}return(function(v){if(!v.length)return[];var y=Array.from(v);return y.reverse(),y.slice(0,$N).map((S=>{return We({},S,{filename:S.filename||(w=y,w[w.length-1]||{}).filename,function:S.function||ru});var w}))})(i)}}let n5=class{constructor(t,n,r){t===void 0&&(t=[]),n===void 0&&(n=[]),r===void 0&&(r=[]),this.coercers=t,this.modifiers=r,this.stackParser=t5(...n)}buildFromUnknown(t,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(r,n,0).apply(t),i=this.buildParsingContext(),o=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(t){var n=this;return DN((function*(){for(var r of t)r.stacktrace&&r.stacktrace.frames&&Rn(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return t}))()}coerceFallback(t){var n;return{type:"Error",value:"Unknown error",stack:(n=t.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(t,n){var r,s;return t.cause!=null&&(r=this.parseStacktrace(t.cause,n)),t.stack!=""&&t.stack!=null&&(s=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?1:0),n.chunkIdMap)),We({},t,{cause:r,stack:s})}applyChunkIds(t,n){return t.map((r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r)))}applyCoercers(t,n){for(var r of this.coercers)if(r.match(t))return r.coerce(t,n);return this.coerceFallback(n)}applyModifiers(t){var n=this;return DN((function*(){var r=t;for(var s of n.modifiers)r=yield s(r);return r}))()}convertToExceptionList(t,n){var r,s,i,o={type:t.type,value:t.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(s=n.handled)===null||s===void 0||s,synthetic:(i=t.synthetic)!==null&&i!==void 0&&i}};t.stack&&(o.stacktrace={type:"raw",frames:t.stack});var u=[o];return t.cause!=null&&u.push(...this.convertToExceptionList(t.cause,We({},n,{handled:!0}))),u}buildParsingContext(){return{chunkIdMap:G3(this.stackParser)}}buildCoercingContext(t,n,r){r===void 0&&(r=0);var s=(i,o)=>{if(o<=4){var u=this.buildCoercingContext(t,n,o);return this.applyCoercers(i,u)}};return We({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:t,apply:i=>s(i,r),next:i=>s(i,r+1)})}},r5=class{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,n){var r=yr(t.stack);return{type:this.getType(t),value:this.getValue(t),stack:r?t.stack:void 0,cause:t.cause?n.next(t.cause):void 0,synthetic:!1}}getType(t){return this.isDOMError(t)?"DOMError":"DOMException"}getValue(t){var n=t.name||(this.isDOMError(t)?"DOMError":"DOMException");return t.message?n+": "+t.message:n}isDOMException(t){return hp(t,"DOMException")}isDOMError(t){return hp(t,"DOMError")}},s5=class{match(t){return(n=>n instanceof Error)(t)}coerce(t,n){return{type:this.getType(t),value:this.getMessage(t,n),stack:this.getStack(t),cause:t.cause?n.next(t.cause):void 0,synthetic:!1}}getType(t){return t.name||t.constructor.name}getMessage(t,n){var r=t.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(t){return t.stacktrace||t.stack||void 0}},i5=class{constructor(){}match(t){return hp(t,"ErrorEvent")&&t.error!=null}coerce(t,n){var r,s=n.apply(t.error);return s||{type:"ErrorEvent",value:t.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}};var a5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;let o5=class{match(t){return typeof t=="string"}coerce(t,n){var r,[s,i]=this.getInfos(t);return{type:s??"Error",value:i??t,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(t){var n="Error",r=t,s=t.match(a5);return s&&(n=s[1],r=s[2]),[n,r]}};var l5=["fatal","error","warning","log","info","debug"];function UT(e,t){t===void 0&&(t=40);var n=Object.keys(e);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var s=n.slice(0,r).join(", ");if(!(s.length>t))return r===n.length||s.length<=t?s:s.slice(0,t)+"..."}return""}let c5=class{match(t){return typeof t=="object"&&t!==null}coerce(t,n){var r,s=this.getErrorPropertyFromObject(t);return s?n.apply(s):{type:this.getType(t),value:this.getValue(t),stack:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(t.level)?t.level:"error",synthetic:!0}}getType(t){return $T(t)?t.constructor.name:"Error"}getValue(t){if("name"in t&&typeof t.name=="string"){var n="'"+t.name+"' captured as exception";return"message"in t&&typeof t.message=="string"&&(n+=" with message: '"+t.message+"'"),n}if("message"in t&&typeof t.message=="string")return t.message;var r=this.getObjectClassName(t);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+UT(t)}isSeverityLevel(t){return yr(t)&&!Sb(t)&&l5.indexOf(t)>=0}getErrorPropertyFromObject(t){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var r=t[n];if(K3(r))return r}}getObjectClassName(t){try{var n=Object.getPrototypeOf(t);return n?n.constructor.name:void 0}catch{return}}},u5=class{match(t){return $T(t)}coerce(t,n){var r,s=t.constructor.name;return{type:s,value:s+" captured as exception with keys: "+UT(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}};class d5{match(t){return kb(t)}coerce(t,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}let f5=class{match(t){return hp(t,"PromiseRejectionEvent")}coerce(t,n){var r,s=this.getUnhandledRejectionReason(t);return kb(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(t){if(kb(t))return t;try{if("reason"in t)return t.reason;if("detail"in t&&"reason"in t.detail)return t.detail.reason}catch{}return t}};var BT=e=>{var t={k:function(n){if(me&&(fa.DEBUG||wt.POSTHOG_DEBUG)&&!Ue(me.console)&&me.console){for(var r=("__rrweb_original__"in me.console[n])?me.console[n].__rrweb_original__:me.console[n],s=arguments.length,i=new Array(s>1?s-1:0),o=1;o<s;o++)i[o-1]=arguments[o];r(e,...i)}},info:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];t.k("log",...r)},warn:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];t.k("warn",...r)},error:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];t.k("error",...r)},critical:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];console.error(e,...r)},uninitializedWarning:n=>{t.error("You must initialize PostHog before calling "+n)},createLogger:n=>BT(e+" "+n)};return t},Ge=BT("[PostHog.js]"),kr=Ge.createLogger,h5=kr("[ExternalScriptsLoader]"),FN=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return h5.warn(t+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=qe?.querySelectorAll("script");if(r){for(var s,i=function(){if(r[o].src===t){var f=r[o];return f.__posthog_loading_callback_fired?{v:n()}:(f.addEventListener("load",(h=>{f.__posthog_loading_callback_fired=!0,n(void 0,h)})),f.onerror=h=>n(h),{v:void 0})}},o=0;o<r.length;o++)if(s=i())return s.v}var u=()=>{if(!qe)return n("document not found");var f=qe.createElement("script");if(f.type="text/javascript",f.crossOrigin="anonymous",f.src=t,f.onload=g=>{f.__posthog_loading_callback_fired=!0,n(void 0,g)},f.onerror=g=>n(g),e.config.prepare_external_dependency_script&&(f=e.config.prepare_external_dependency_script(f)),!f)return n("prepare_external_dependency_script returned null");var h,p=qe.querySelectorAll("body > script");p.length>0?(h=p[0].parentNode)==null||h.insertBefore(f,p[0]):qe.body.appendChild(f)};qe!=null&&qe.body?u():qe?.addEventListener("DOMContentLoaded",u)};wt.__PosthogExtensions__=wt.__PosthogExtensions__||{},wt.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{var r="/static/"+t+".js?v="+e.version;if(t==="remote-config"&&(r="/array/"+e.config.token+"/config.js"),t==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}var i=e.requestRouter.endpointFor("assets",r);FN(e,i,n)},wt.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var r=e.requestRouter.endpointFor("api",t);FN(e,r,n)};var mp={};function vo(e,t,n){if(Rn(e)){if(MN&&e.forEach===MN)e.forEach(t,n);else if("length"in e&&e.length===+e.length){for(var r=0,s=e.length;r<s;r++)if(r in e&&t.call(n,e[r],r)===mp)return}}}function Cn(e,t,n){if(!An(e)){if(Rn(e))return vo(e,t,n);if(U3(e)){for(var r of e.entries())if(t.call(n,r[1],r[0])===mp)return}else for(var s in e)if(zT.call(e,s)&&t.call(n,e[s],s)===mp)return}}var Qn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return vo(n,(function(s){for(var i in s)s[i]!==void 0&&(e[i]=s[i])})),e},yu=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return vo(n,(function(s){vo(s,(function(i){e.push(i)}))})),e};function Jm(e){for(var t=Object.keys(e),n=t.length,r=new Array(n);n--;)r[n]=[t[n],e[t[n]]];return r}var UN=function(e){try{return e()}catch{return}},m5=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return e.apply(this,n)}catch(s){Ge.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ge.critical(s)}}},iw=function(e){var t={};return Cn(e,(function(n,r){(yr(n)&&n.length>0||Fi(n))&&(t[r]=n)})),t};function p5(e,t){return n=e,r=i=>yr(i)&&!ja(t)?i.slice(0,t):i,s=new Set,(function i(o,u){return o!==Object(o)?r?r(o,u):o:s.has(o)?void 0:(s.add(o),Rn(o)?(f=[],vo(o,(h=>{f.push(i(h))}))):(f={},Cn(o,((h,p)=>{s.has(h)||(f[p]=i(h,p))}))),f);var f})(n);var n,r,s}var g5=["herokuapp.com","vercel.app","netlify.app"];function v5(e){var t=e?.hostname;if(!yr(t))return!1;var n=t.split(".").slice(-2).join(".");for(var r of g5)if(n===r)return!1;return!0}function qT(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n]}function dr(e,t,n,r){var{capture:s=!1,passive:i=!0}=r??{};e?.addEventListener(t,n,{capture:s,passive:i})}var HT="$people_distinct_id",Xd="__alias",Qd="__timers",BN="$autocapture_disabled_server_side",Eb="$heatmaps_enabled_server_side",qN="$exception_capture_enabled_server_side",jb="$error_tracking_suppression_rules",HN="$error_tracking_capture_extension_exceptions",VN="$web_vitals_enabled_server_side",VT="$dead_clicks_enabled_server_side",KN="$web_vitals_allowed_metrics",nx="$session_recording_remote_config",pp="$sesid",KT="$session_is_sampled",zc="$enabled_feature_flags",Jd="$early_access_features",Cb="$feature_flag_details",ef="$stored_person_properties",cl="$stored_group_properties",Tb="$surveys",xm="$surveys_activated",gp="$flag_call_reported",ha="$user_state",Ab="$client_session_props",Rb="$capture_rate_limit",Mb="$initial_campaign_params",Ob="$initial_referrer_info",vp="$initial_person_info",yp="$epp",GT="__POSTHOG_TOOLBAR__",Od="$posthog_cookieless",y5=[HT,Xd,"__cmpns",Qd,"$session_recording_enabled_server_side",Eb,pp,zc,jb,ha,Jd,Cb,cl,ef,Tb,gp,Ab,Rb,Mb,Ob,yp,vp];function GN(e){return e instanceof Element&&(e.id===GT||!(e.closest==null||!e.closest(".toolbar-global-fade-container")))}function sg(e){return!!e&&e.nodeType===1}function yo(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function YT(e){return!!e&&e.nodeType===3}function WT(e){return!!e&&e.nodeType===11}function aw(e){return e?ng(e).split(/\s+/):[]}function YN(e){var t=me?.location.href;return!!(t&&e&&e.some((n=>t.match(n))))}function xp(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 aw(t)}function ZT(e){return An(e)?null:ng(e).split(/(\s+)/).filter((t=>jf(t))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ig(e){var t="";return Ib(e)&&!tA(e)&&e.childNodes&&e.childNodes.length&&Cn(e.childNodes,(function(n){var r;YT(n)&&n.textContent&&(t+=(r=ZT(n.textContent))!==null&&r!==void 0?r:"")})),ng(t)}function XT(e){return Ue(e.target)?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var ow=["a","button","form","input","select","textarea","label"];function QT(e,t){if(Ue(t))return!0;var n,r=function(i){if(t.some((o=>i.matches(o))))return{v:!0}};for(var s of e)if(n=r(s))return n.v;return!1}function JT(e){var t=e.parentNode;return!(!t||!sg(t))&&t}var WN=[".ph-no-rageclick",".ph-no-capture"],lw=e=>!e||yo(e,"html")||!sg(e),eA=(e,t)=>{if(!me||lw(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[e],s=e;s.parentNode&&!yo(s,"body");)if(WT(s.parentNode))r.push(s.parentNode.host),s=s.parentNode.host;else{var i=JT(s);if(!i)break;if(t||ow.indexOf(i.tagName.toLowerCase())>-1)n=!0;else{var o=me.getComputedStyle(i);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(i),s=i}return{parentIsUsefulElement:n,targetElementList:r}};function x5(e,t,n,r,s){var i,o,u,f;if(n===void 0&&(n=void 0),!me||lw(e)||(i=n)!=null&&i.url_allowlist&&!YN(n.url_allowlist)||(o=n)!=null&&o.url_ignorelist&&YN(n.url_ignorelist))return!1;if((u=n)!=null&&u.dom_event_allowlist){var h=n.dom_event_allowlist;if(h&&!h.some((S=>t.type===S)))return!1}var{parentIsUsefulElement:p,targetElementList:g}=eA(e,r);if(!(function(S,w){var N=w?.element_allowlist;if(Ue(N))return!0;var k,j=function(C){if(N.some((M=>C.tagName.toLowerCase()===M)))return{v:!0}};for(var E of S)if(k=j(E))return k.v;return!1})(g,n)||!QT(g,(f=n)==null?void 0:f.css_selector_allowlist))return!1;var v=me.getComputedStyle(e);if(v&&v.getPropertyValue("cursor")==="pointer"&&t.type==="click")return!0;var y=e.tagName.toLowerCase();switch(y){case"html":return!1;case"form":return(s||["submit"]).indexOf(t.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(t.type)>=0;default:return p?(s||["click"]).indexOf(t.type)>=0:(s||["click"]).indexOf(t.type)>=0&&(ow.indexOf(y)>-1||e.getAttribute("contenteditable")==="true")}}function Ib(e){for(var t=e;t.parentNode&&!yo(t,"body");t=t.parentNode){var n=xp(t);if(Bt(n,"ph-sensitive")||Bt(n,"ph-no-capture"))return!1}if(Bt(xp(e),"ph-include"))return!0;var r=e.type||"";if(yr(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var s=e.name||e.id||"";return!(yr(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function tA(e){return!!(yo(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||yo(e,"select")||yo(e,"textarea")||e.getAttribute("contenteditable")==="true")}var nA="(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})",b5=new RegExp("^(?:"+nA+")$"),w5=new RegExp(nA),rA="\\d{3}-?\\d{2}-?\\d{4}",_5=new RegExp("^("+rA+")$"),S5=new RegExp("("+rA+")");function jf(e,t){return t===void 0&&(t=!0),!(An(e)||yr(e)&&(e=ng(e),(t?b5:w5).test((e||"").replace(/[- ]/g,""))||(t?_5:S5).test(e)))}function sA(e){var t=ig(e);return jf(t=(t+" "+iA(e)).trim())?t:""}function iA(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Cn(e.childNodes,(function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var s=ig(n);t=(t+" "+s).trim(),n.childNodes&&n.childNodes.length&&(t=(t+" "+iA(n)).trim())}catch(i){Ge.error("[AutoCapture]",i)}})),t}function k5(e){return(function(t){var n=t.map((r=>{var s,i,o="";if(r.tag_name&&(o+=r.tag_name),r.attr_class)for(var u of(r.attr_class.sort(),r.attr_class))o+="."+u.replace(/"/g,"");var f=We({},r.text?{text:r.text}:{},{"nth-child":(s=r.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=r.nth_of_type)!==null&&i!==void 0?i:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),h={};return Jm(f).sort(((p,g)=>{var[v]=p,[y]=g;return v.localeCompare(y)})).forEach((p=>{var[g,v]=p;return h[ZN(g.toString())]=ZN(v.toString())})),o+=":",o+=Jm(h).map((p=>{var[g,v]=p;return g+'="'+v+'"'})).join("")}));return n.join(";")})((function(t){return t.map((n=>{var r,s,i={text:(r=n.$el_text)==null?void 0:r.slice(0,400),tag_name:n.tag_name,href:(s=n.attr__href)==null?void 0:s.slice(0,2048),attr_class:N5(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return Jm(n).filter((o=>{var[u]=o;return u.indexOf("attr__")===0})).forEach((o=>{var[u,f]=o;return i.attributes[u]=f})),i}))})(e))}function ZN(e){return e.replace(/"|\\"/g,'\\"')}function N5(e){var t=e.attr__class;return t?Rn(t)?t:aw(t):void 0}class aA{constructor(){this.clicks=[]}isRageClick(t,n,r){var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(t-s.x)+Math.abs(n-s.y)<30&&r-s.timestamp<1e3){if(this.clicks.push({x:t,y:n,timestamp:r}),this.clicks.length===3)return!0}else this.clicks=[{x:t,y:n,timestamp:r}];return!1}}var rx="$copy_autocapture",pa=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),bp=e=>{var t=qe?.createElement("a");return Ue(t)?null:(t.href=e,t)},E5=function(e,t){var n,r;t===void 0&&(t="&");var s=[];return Cn(e,(function(i,o){Ue(i)||Ue(o)||o==="undefined"||(n=encodeURIComponent((u=>u instanceof File)(i)?i.name:i.toString()),r=encodeURIComponent(o),s[s.length]=r+"="+n)})),s.join(t)},wp=function(e,t){for(var n,r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;s<r.length;s++){var i=r[s].split("=");if(i[0]===t){n=i;break}}if(!Rn(n)||n.length<2)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{Ge.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Yf=function(e,t,n){if(!e||!t||!t.length)return e;for(var r=e.split("#"),s=r[0]||"",i=r[1],o=s.split("?"),u=o[1],f=o[0],h=(u||"").split("&"),p=[],g=0;g<h.length;g++){var v=h[g].split("=");Rn(v)&&(t.includes(v[0])?p.push(v[0]+"="+n):p.push(h[g]))}var y=f;return u!=null&&(y+="?"+p.join("&")),i!=null&&(y+="#"+i),y},_p=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},XN=kr("[AutoCapture]");function sx(e,t){return t.length>e?t.slice(0,e)+"...":t}function j5(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!sg(t));return t}function C5(e,t,n,r){var s=e.tagName.toLowerCase(),i={tag_name:s};ow.indexOf(s)>-1&&!n&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=sx(1024,sA(e)):i.$el_text=sx(1024,ig(e)));var o=xp(e);o.length>0&&(i.classes=o.filter((function(p){return p!==""}))),Cn(e.attributes,(function(p){var g;if((!tA(e)||["name","id","class","aria-label"].indexOf(p.name)!==-1)&&(r==null||!r.includes(p.name))&&!t&&jf(p.value)&&(g=p.name,!yr(g)||g.substring(0,10)!=="_ngcontent"&&g.substring(0,7)!=="_nghost")){var v=p.value;p.name==="class"&&(v=aw(v).join(" ")),i["attr__"+p.name]=sx(1024,v)}}));for(var u=1,f=1,h=e;h=j5(h);)u++,h.tagName===e.tagName&&f++;return i.nth_child=u,i.nth_of_type=f,i}function T5(e,t){for(var n,r,{e:s,maskAllElementAttributes:i,maskAllText:o,elementAttributeIgnoreList:u,elementsChainAsString:f}=t,h=[e],p=e;p.parentNode&&!yo(p,"body");)WT(p.parentNode)?(h.push(p.parentNode.host),p=p.parentNode.host):(h.push(p.parentNode),p=p.parentNode);var g,v=[],y={},S=!1,w=!1;if(Cn(h,(C=>{var M=Ib(C);C.tagName.toLowerCase()==="a"&&(S=C.getAttribute("href"),S=M&&S&&jf(S)&&S),Bt(xp(C),"ph-no-capture")&&(w=!0),v.push(C5(C,i,o,u));var A=(function(O){if(!Ib(O))return{};var I={};return Cn(O.attributes,(function(G){if(G.name&&G.name.indexOf("data-ph-capture-attribute")===0){var z=G.name.replace("data-ph-capture-attribute-",""),W=G.value;z&&W&&jf(W)&&(I[z]=W)}})),I})(C);Qn(y,A)})),w)return{props:{},explicitNoCapture:w};if(o||(e.tagName.toLowerCase()==="a"||e.tagName.toLowerCase()==="button"?v[0].$el_text=sA(e):v[0].$el_text=ig(e)),S){var N,k;v[0].attr__href=S;var j=(N=bp(S))==null?void 0:N.host,E=me==null||(k=me.location)==null?void 0:k.host;j&&E&&j!==E&&(g=S)}return{props:Qn({$event_type:s.type,$ce_version:1},f?{}:{$elements:v},{$elements_chain:k5(v)},(n=v[0])!=null&&n.$el_text?{$el_text:(r=v[0])==null?void 0:r.$el_text}:{},g&&s.type==="click"?{$external_click_url:g}:{},y)}}class A5{constructor(t){this.P=!1,this.T=null,this.rageclicks=new aA,this.R=!1,this.instance=t,this.I=null}get C(){var t,n,r=$r(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(t=r.url_allowlist)==null?void 0:t.map((s=>new RegExp(s))),r.url_ignorelist=(n=r.url_ignorelist)==null?void 0:n.map((s=>new RegExp(s))),r}O(){if(this.isBrowserSupported()){if(me&&qe){var t=r=>{r=r||me?.event;try{this.F(r)}catch(s){XN.error("Failed to capture event",s)}};if(dr(qe,"submit",t,{capture:!0}),dr(qe,"change",t,{capture:!0}),dr(qe,"click",t,{capture:!0}),this.C.capture_copied_text){var n=r=>{r=r||me?.event,this.F(r,rx)};dr(qe,"copy",n,{capture:!0}),dr(qe,"cut",n,{capture:!0})}}}else XN.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.O(),this.P=!0)}onRemoteConfig(t){t.elementsChainAsString&&(this.R=t.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[BN]:!!t.autocapture_opt_out}),this.T=!!t.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(t){this.I=t}getElementSelectors(t){var n,r=[];return(n=this.I)==null||n.forEach((s=>{var i=qe?.querySelectorAll(s);i?.forEach((o=>{t===o&&r.push(s)}))})),r}get isEnabled(){var t,n,r=(t=this.instance.persistence)==null?void 0:t.props[BN],s=this.T;if(ja(s)&&!go(r)&&!this.instance.M())return!1;var i=(n=this.T)!==null&&n!==void 0?n:!!r;return!!this.instance.config.autocapture&&!i}F(t,n){if(n===void 0&&(n="$autocapture"),this.isEnabled){var r,s=XT(t);YT(s)&&(s=s.parentNode||null),n==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(t.clientX,t.clientY,new Date().getTime())&&(function(v,y){if(!me||lw(v))return!1;var S,w;if((S=go(y)?!!y&&WN:(w=y?.css_selector_ignorelist)!==null&&w!==void 0?w:WN)===!1)return!1;var{targetElementList:N}=eA(v,!1);return!QT(N,S)})(s,this.instance.config.rageclick)&&this.F(t,"$rageclick");var i=n===rx;if(s&&x5(s,t,this.C,i,i?["copy","cut"]:void 0)){var{props:o,explicitNoCapture:u}=T5(s,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.C.element_attribute_ignorelist,elementsChainAsString:this.R});if(u)return!1;var f=this.getElementSelectors(s);if(f&&f.length>0&&(o.$element_selectors=f),n===rx){var h,p=ZT(me==null||(h=me.getSelection())==null?void 0:h.toString()),g=t.type||"clipboard";if(!p)return!1;o.$selected_content=p,o.$copy_type=g}return this.instance.capture(n,o),!0}}}isBrowserSupported(){return po(qe?.querySelectorAll)}}Math.trunc||(Math.trunc=function(e){return e<0?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return Fi(e)&&isFinite(e)&&Math.floor(e)===e});var QN="0123456789abcdef";let R5=class Lb{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,r,s){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(s)||t<0||n<0||r<0||s<0||t>0xffffffffffff||n>4095||r>1073741823||s>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=t/Math.pow(2,40),i[1]=t/Math.pow(2,32),i[2]=t/Math.pow(2,24),i[3]=t/Math.pow(2,16),i[4]=t/Math.pow(2,8),i[5]=t,i[6]=112|n>>>8,i[7]=n,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new Lb(i)}toString(){for(var t="",n=0;n<this.bytes.length;n++)t=t+QN.charAt(this.bytes[n]>>>4)+QN.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new Lb(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;n<16;n++){var r=this.bytes[n]-t.bytes[n];if(r!==0)return Math.sign(r)}return 0}},M5=class{constructor(){this.A=0,this.D=0,this.j=new O5}generate(){var t=this.generateOrAbort();if(Ue(t)){this.A=0;var n=this.generateOrAbort();if(Ue(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.A)this.A=t,this.L();else{if(!(t+1e4>this.A))return;this.D++,this.D>4398046511103&&(this.A++,this.L())}return R5.fromFieldsV7(this.A,Math.trunc(this.D/Math.pow(2,30)),this.D&Math.pow(2,30)-1,this.j.nextUint32())}L(){this.D=1024*this.j.nextUint32()+(1023&this.j.nextUint32())}};var JN,oA=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;t<e.length;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};me&&!Ue(me.crypto)&&crypto.getRandomValues&&(oA=e=>crypto.getRandomValues(e));let O5=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(oA(this.N),this.U=0),this.N[this.U++]}};var mo=()=>I5().toString(),I5=()=>(JN||(JN=new M5)).generate(),Id="",L5=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function D5(e,t){if(t){var n=(function(s,i){if(i===void 0&&(i=qe),Id)return Id;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var o=s.split("."),u=Math.min(o.length,8),f="dmn_chk_"+mo();!Id&&u--;){var h=o.slice(u).join("."),p=f+"=1;domain=."+h+";path=/";i.cookie=p+";max-age=3",i.cookie.includes(f)&&(i.cookie=p+";max-age=0",Id=h)}return Id})(e);if(!n){var r=(s=>{var i=s.match(L5);return i?i[0]:""})(e);r!==n&&Ge.info("Warning: cookie subdomain discovery mismatch",r,n),n=r}return n?"; domain=."+n:""}return""}var Di={H:()=>!!qe,B:function(e){Ge.error("cookieStore error: "+e)},q:function(e){if(qe){try{for(var t=e+"=",n=qe.cookie.split(";").filter((i=>i.length)),r=0;r<n.length;r++){for(var s=n[r];s.charAt(0)==" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return decodeURIComponent(s.substring(t.length,s.length))}}catch{}return null}},W:function(e){var t;try{t=JSON.parse(Di.q(e))||{}}catch{}return t},G:function(e,t,n,r,s){if(qe)try{var i="",o="",u=D5(qe.location.hostname,r);if(n){var f=new Date;f.setTime(f.getTime()+24*n*60*60*1e3),i="; expires="+f.toUTCString()}s&&(o="; secure");var h=e+"="+encodeURIComponent(JSON.stringify(t))+i+"; SameSite=Lax; path=/"+u+o;return h.length>3686.4&&Ge.warn("cookieStore warning: large cookie, len="+h.length),qe.cookie=h,h}catch{return}},V:function(e,t){if(qe!=null&&qe.cookie)try{Di.G(e,"",-1,t)}catch{return}}},ix=null,qn={H:function(){if(!ja(ix))return ix;var e=!0;if(Ue(me))e=!1;else try{var t="__mplssupport__";qn.G(t,"xyz"),qn.q(t)!=='"xyz"'&&(e=!1),qn.V(t)}catch{e=!1}return e||Ge.error("localStorage unsupported; falling back to cookie store"),ix=e,e},B:function(e){Ge.error("localStorage error: "+e)},q:function(e){try{return me?.localStorage.getItem(e)}catch(t){qn.B(t)}return null},W:function(e){try{return JSON.parse(qn.q(e))||{}}catch{}return null},G:function(e,t){try{me?.localStorage.setItem(e,JSON.stringify(t))}catch(n){qn.B(n)}},V:function(e){try{me?.localStorage.removeItem(e)}catch(t){qn.B(t)}}},P5=["distinct_id",pp,KT,yp,vp],bm=We({},qn,{W:function(e){try{var t={};try{t=Di.W(e)||{}}catch{}var n=Qn(t,JSON.parse(qn.q(e)||"{}"));return qn.G(e,n),n}catch{}return null},G:function(e,t,n,r,s,i){try{qn.G(e,t,void 0,void 0,i);var o={};P5.forEach((u=>{t[u]&&(o[u]=t[u])})),Object.keys(o).length&&Di.G(e,o,n,r,s,i)}catch(u){qn.B(u)}},V:function(e,t){try{me?.localStorage.removeItem(e),Di.V(e,t)}catch(n){qn.B(n)}}}),wm={},z5={H:function(){return!0},B:function(e){Ge.error("memoryStorage error: "+e)},q:function(e){return wm[e]||null},W:function(e){return wm[e]||null},G:function(e,t){wm[e]=t},V:function(e){delete wm[e]}},nl=null,Ar={H:function(){if(!ja(nl))return nl;if(nl=!0,Ue(me))nl=!1;else try{var e="__support__";Ar.G(e,"xyz"),Ar.q(e)!=='"xyz"'&&(nl=!1),Ar.V(e)}catch{nl=!1}return nl},B:function(e){Ge.error("sessionStorage error: ",e)},q:function(e){try{return me?.sessionStorage.getItem(e)}catch(t){Ar.B(t)}return null},W:function(e){try{return JSON.parse(Ar.q(e))||null}catch{}return null},G:function(e,t){try{me?.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){Ar.B(n)}},V:function(e){try{me?.sessionStorage.removeItem(e)}catch(t){Ar.B(t)}}},ma=(function(e){return e[e.PENDING=-1]="PENDING",e[e.DENIED=0]="DENIED",e[e.GRANTED=1]="GRANTED",e})({});class $5{constructor(t){this._instance=t}get C(){return this._instance.config}get consent(){return this.J()?ma.DENIED:this.K}isOptedOut(){return this.C.cookieless_mode==="always"||this.consent===ma.DENIED||this.consent===ma.PENDING&&(this.C.opt_out_capturing_by_default||this.C.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===ma.DENIED}optInOut(t){this.Y.G(this.X,t?1:0,this.C.cookie_expiration,this.C.cross_subdomain_cookie,this.C.secure_cookie)}reset(){this.Y.V(this.X,this.C.cross_subdomain_cookie)}get X(){var{token:t,opt_out_capturing_cookie_prefix:n,consent_persistence_name:r}=this._instance.config;return r||(n?n+t:"__ph_opt_in_out_"+t)}get K(){var t=this.Y.q(this.X);return ex(t)?ma.GRANTED:Bt(H3,t)?ma.DENIED:ma.PENDING}get Y(){if(!this.Z){var t=this.C.opt_out_capturing_persistence_type;this.Z=t==="localStorage"?qn:Di;var n=t==="localStorage"?Di:qn;n.q(this.X)&&(this.Z.q(this.X)||this.optInOut(ex(n.q(this.X))),n.V(this.X,this.C.cross_subdomain_cookie))}return this.Z}J(){return!!this.C.respect_dnt&&!!qT([Ls?.doNotTrack,Ls?.msDoNotTrack,wt.doNotTrack],(t=>ex(t)))}}var _m=kr("[Dead Clicks]"),F5=()=>!0,U5=e=>{var t,n=!((t=e.instance.persistence)==null||!t.get_property(VT)),r=e.instance.config.capture_dead_clicks;return go(r)?r:n};let lA=class{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(t,n,r){this.instance=t,this.isEnabled=n,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(t){this.instance.persistence&&this.instance.persistence.register({[VT]:t?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(t){var n,r;(n=wt.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&t(),(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(s=>{s?_m.error("failed to load script",s):t()}))}et(){var t;if(qe){if(!this.tt&&(t=wt.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture){var n=$r(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.tt=wt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.tt.start(qe),_m.info("starting...")}}else _m.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,_m.info("stopping..."))}};var Ld=kr("[ExceptionAutocapture]");let B5=class{constructor(t){var n,r,s;this.rt=()=>{var i;if(me&&this.isEnabled&&(i=wt.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var o=wt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,u=wt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,f=wt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.C.capture_unhandled_errors&&(this.st=o(this.captureException.bind(this))),!this.nt&&this.C.capture_unhandled_rejections&&(this.nt=u(this.captureException.bind(this))),!this.ot&&this.C.capture_console_errors&&(this.ot=f(this.captureException.bind(this)))}catch(h){Ld.error("failed to start",h),this.lt()}}},this._instance=t,this.ut=!((n=this._instance.persistence)==null||!n.props[qN]),this.C=this.ht(),this.dt=new V3({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,h:Ld}),this.startIfEnabled()}ht(){var t=this._instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return $r(t)?n=We({},n,t):(Ue(t)?this.ut:t)&&(n=We({},n,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.C.capture_console_errors||this.C.capture_unhandled_errors||this.C.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(Ld.info("enabled"),this.it(this.rt))}it(t){var n,r;(n=wt.__PosthogExtensions__)!=null&&n.errorWrappingFunctions&&t(),(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",(s=>{if(s)return Ld.error("failed to load script",s);t()}))}lt(){var t,n,r;(t=this.st)==null||t.call(this),this.st=void 0,(n=this.nt)==null||n.call(this),this.nt=void 0,(r=this.ot)==null||r.call(this),this.ot=void 0}onRemoteConfig(t){var n=t.autocaptureExceptions;this.ut=!!n||!1,this.C=this.ht(),this._instance.persistence&&this._instance.persistence.register({[qN]:this.ut}),this.startIfEnabled()}captureException(t){var n,r,s=(n=t==null||(r=t.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&n!==void 0?n:"Exception";this.dt.consumeRateLimit(s)?Ld.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(t)}};function eE(e,t,n){try{if(!(t in e))return()=>{};var r=e[t],s=n(r);return po(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=s,()=>{e[t]=r}}catch{return()=>{}}}let q5=class{constructor(t){var n;this._instance=t,this.vt=(me==null||(n=me.location)==null?void 0:n.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ge.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ct&&this.ct(),this.ct=void 0,Ge.info("History API monitoring stopped")}monitorHistoryChanges(){var t,n;if(me&&me.history){var r=this;(t=me.history.pushState)!=null&&t.__posthog_wrapped__||eE(me.history,"pushState",(s=>function(i,o,u){s.call(this,i,o,u),r.ft("pushState")})),(n=me.history.replaceState)!=null&&n.__posthog_wrapped__||eE(me.history,"replaceState",(s=>function(i,o,u){s.call(this,i,o,u),r.ft("replaceState")})),this.gt()}}ft(t){try{var n,r=me==null||(n=me.location)==null?void 0:n.pathname;if(!r)return;r!==this.vt&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:t}),this.vt=r}catch(s){Ge.error("Error capturing "+t+" pageview",s)}}gt(){if(!this.ct){var t=()=>{this.ft("popstate")};dr(me,"popstate",t),this.ct=()=>{me&&me.removeEventListener("popstate",t)}}}};var ax=kr("[SegmentIntegration]");function H5(e,t){var n=e.config.segment;if(!n)return t();(function(r,s){var i=r.config.segment;if(!i)return s();var o=f=>{var h=()=>f.anonymousId()||mo();r.config.get_device_id=h,f.id()&&(r.register({distinct_id:f.id(),$device_id:h()}),r.persistence.set_property(ha,"identified")),s()},u=i.user();"then"in u&&po(u.then)?u.then((f=>o(f))):o(u)})(e,(()=>{n.register((r=>{Promise&&Promise.resolve||ax.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,o)=>{if(!o)return i;i.event.userId||i.event.anonymousId===r.get_distinct_id()||(ax.info("No userId set, resetting PostHog"),r.reset()),i.event.userId&&i.event.userId!==r.get_distinct_id()&&(ax.info("UserId set, identifying with PostHog"),r.identify(i.event.userId));var u=r.calculateEventProperties(o,i.event.properties);return i.event.properties=Object.assign({},u,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(e)).then((()=>{t()}))}))}var cA="posthog-js";function uA(e,t){var{organization:n,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:o=!0}=t===void 0?{}:t;return u=>{var f,h,p,g,v;if(!(i==="*"||i.includes(u.level))||!e.__loaded)return u;u.tags||(u.tags={});var y=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());u.tags["PostHog Person URL"]=y,e.sessionRecordingStarted()&&(u.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var S=((f=u.exception)==null?void 0:f.values)||[],w=S.map((k=>We({},k,{stacktrace:k.stacktrace?We({},k.stacktrace,{type:"raw",frames:(k.stacktrace.frames||[]).map((j=>We({},j,{platform:"web:javascript"})))}):void 0}))),N={$exception_message:((h=S[0])==null?void 0:h.value)||u.message,$exception_type:(p=S[0])==null?void 0:p.type,$exception_level:u.level,$exception_list:w,$sentry_event_id:u.event_id,$sentry_exception:u.exception,$sentry_exception_message:((g=S[0])==null?void 0:g.value)||u.message,$sentry_exception_type:(v=S[0])==null?void 0:v.type,$sentry_tags:u.tags};return n&&r&&(N.$sentry_url=(s||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+u.event_id),o&&e.exceptions.sendExceptionEvent(N),u}}class V5{constructor(t,n,r,s,i,o){this.name=cA,this.setupOnce=function(u){u(uA(t,{organization:n,projectId:r,prefix:s,severityAllowList:i,sendExceptionsToPostHog:o==null||o}))}}}var K5=me!=null&&me.location?_p(me.location.hash,"__posthog")||_p(location.hash,"state"):null,tE="_postHogToolbarParams",nE=kr("[Toolbar]"),ao=(function(e){return e[e.UNINITIALIZED=0]="UNINITIALIZED",e[e.LOADING=1]="LOADING",e[e.LOADED=2]="LOADED",e})(ao||{});class G5{constructor(t){this.instance=t}_t(t){wt.ph_toolbar_state=t}yt(){var t;return(t=wt.ph_toolbar_state)!==null&&t!==void 0?t:ao.UNINITIALIZED}maybeLoadToolbar(t,n,r){if(t===void 0&&(t=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),!me||!qe)return!1;t=t??me.location,r=r??me.history;try{if(!n){try{me.localStorage.setItem("test","test"),me.localStorage.removeItem("test")}catch{return!1}n=me?.localStorage}var s,i=K5||_p(t.hash,"__posthog")||_p(t.hash,"state"),o=i?UN((()=>JSON.parse(atob(decodeURIComponent(i)))))||UN((()=>JSON.parse(decodeURIComponent(i)))):null;return o&&o.action==="ph_authorize"?((s=o).source="url",s&&Object.keys(s).length>0&&(o.desiredHash?t.hash=o.desiredHash:r?r.replaceState(r.state,"",t.pathname+t.search):t.hash="")):((s=JSON.parse(n.getItem(tE)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}bt(t){var n=wt.ph_load_toolbar||wt.ph_load_editor;!An(n)&&po(n)?n(t,this.instance):nE.warn("No toolbar load function found")}loadToolbar(t){var n=!(qe==null||!qe.getElementById(GT));if(!me||n)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=We({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(me.localStorage.setItem(tE,JSON.stringify(We({},s,{source:void 0}))),this.yt()===ao.LOADED)this.bt(s);else if(this.yt()===ao.UNINITIALIZED){var i;this._t(ao.LOADING),(i=wt.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",(o=>{if(o)return nE.error("[Toolbar] Failed to load",o),void this._t(ao.UNINITIALIZED);this._t(ao.LOADED),this.bt(s)})),dr(me,"turbolinks:load",(()=>{this._t(ao.UNINITIALIZED),this.loadToolbar(s)}))}return!0}wt(t){return this.loadToolbar(t)}maybeLoadEditor(t,n,r){return t===void 0&&(t=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(t,n,r)}}var Y5=kr("[TracingHeaders]");class W5{constructor(t){this.xt=void 0,this.St=void 0,this.rt=()=>{var n,r;Ue(this.xt)&&((n=wt.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),Ue(this.St)&&((r=wt.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=t}it(t){var n,r;(n=wt.__PosthogExtensions__)!=null&&n.tracingHeadersPatchFns&&t(),(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",(s=>{if(s)return Y5.error("failed to load script",s);t()}))}startIfEnabledOrStop(){var t,n;this._instance.config.__add_tracing_headers?this.it(this.rt):((t=this.xt)==null||t.call(this),(n=this.St)==null||n.call(this),this.xt=void 0,this.St=void 0)}}var Js="Mobile",Sp="iOS",Mi="Android",Cf="Tablet",dA=Mi+" "+Cf,fA="iPad",hA="Apple",mA=hA+" Watch",Tf="Safari",su="BlackBerry",pA="Samsung",gA=pA+"Browser",vA=pA+" Internet",yl="Chrome",Z5=yl+" OS",yA=yl+" "+Sp,cw="Internet Explorer",xA=cw+" "+Js,uw="Opera",X5=uw+" Mini",dw="Edge",bA="Microsoft "+dw,Gc="Firefox",wA=Gc+" "+Sp,Af="Nintendo",Rf="PlayStation",Yc="Xbox",_A=Mi+" "+Js,SA=Js+" "+Tf,tf="Windows",Db=tf+" Phone",rE="Nokia",Pb="Ouya",kA="Generic",Q5=kA+" "+Js.toLowerCase(),NA=kA+" "+Cf.toLowerCase(),zb="Konqueror",Zr="(\\d+(\\.\\d+)?)",ox=new RegExp("Version/"+Zr),J5=new RegExp(Yc,"i"),eP=new RegExp(Rf+" \\w+","i"),tP=new RegExp(Af+" \\w+","i"),fw=new RegExp(su+"|PlayBook|BB10","i"),nP={"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"},rP=(e,t)=>t&&Bt(t,hA)||(function(n){return Bt(n,Tf)&&!Bt(n,yl)&&!Bt(n,Mi)})(e),EA=function(e,t){return t=t||"",Bt(e," OPR/")&&Bt(e,"Mini")?X5:Bt(e," OPR/")?uw:fw.test(e)?su:Bt(e,"IE"+Js)||Bt(e,"WPDesktop")?xA:Bt(e,gA)?vA:Bt(e,dw)||Bt(e,"Edg/")?bA:Bt(e,"FBIOS")?"Facebook "+Js:Bt(e,"UCWEB")||Bt(e,"UCBrowser")?"UC Browser":Bt(e,"CriOS")?yA:Bt(e,"CrMo")||Bt(e,yl)?yl:Bt(e,Mi)&&Bt(e,Tf)?_A:Bt(e,"FxiOS")?wA:Bt(e.toLowerCase(),zb.toLowerCase())?zb:rP(e,t)?Bt(e,Js)?SA:Tf:Bt(e,Gc)?Gc:Bt(e,"MSIE")||Bt(e,"Trident/")?cw:Bt(e,"Gecko")?Gc:""},sP={[xA]:[new RegExp("rv:"+Zr)],[bA]:[new RegExp(dw+"?\\/"+Zr)],[yl]:[new RegExp("("+yl+"|CrMo)\\/"+Zr)],[yA]:[new RegExp("CriOS\\/"+Zr)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Zr)],[Tf]:[ox],[SA]:[ox],[uw]:[new RegExp("(Opera|OPR)\\/"+Zr)],[Gc]:[new RegExp(Gc+"\\/"+Zr)],[wA]:[new RegExp("FxiOS\\/"+Zr)],[zb]:[new RegExp("Konqueror[:/]?"+Zr,"i")],[su]:[new RegExp(su+" "+Zr),ox],[_A]:[new RegExp("android\\s"+Zr,"i")],[vA]:[new RegExp(gA+"\\/"+Zr)],[cw]:[new RegExp("(rv:|MSIE )"+Zr)],Mozilla:[new RegExp("rv:"+Zr)]},iP=function(e,t){var n=EA(e,t),r=sP[n];if(Ue(r))return null;for(var s=0;s<r.length;s++){var i=r[s],o=e.match(i);if(o)return parseFloat(o[o.length-2])}return null},sE=[[new RegExp(Yc+"; "+Yc+" (.*?)[);]","i"),e=>[Yc,e&&e[1]||""]],[new RegExp(Af,"i"),[Af,""]],[new RegExp(Rf,"i"),[Rf,""]],[fw,[su,""]],[new RegExp(tf,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[Db,""];if(new RegExp(Js).test(t)&&!/IEMobile\b/.test(t))return[tf+" "+Js,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var r=n[1],s=nP[r]||"";return/arm/i.test(t)&&(s="RT"),[tf,s]}return[tf,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>{if(e&&e[3]){var t=[e[3],e[4],e[5]||"0"];return[Sp,t.join(".")]}return[Sp,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=Ue(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Mi+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Mi+")","i"),e=>{if(e&&e[2]){var t=[e[2],e[3],e[4]||"0"];return[Mi,t.join(".")]}return[Mi,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];if(e&&e[1]){var n=[e[1],e[2],e[3]||"0"];t[1]=n.join(".")}return t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Z5,""]],[/Linux|debian/i,["Linux",""]]],iE=function(e){return tP.test(e)?Af:eP.test(e)?Rf:J5.test(e)?Yc:new RegExp(Pb,"i").test(e)?Pb:new RegExp("("+Db+"|WPDesktop)","i").test(e)?Db:/iPad/.test(e)?fA:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?mA:fw.test(e)?su:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(rE,"i").test(e)?rE:/(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(Js).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)?Mi:dA:Mi:new RegExp("(pda|"+Js+")","i").test(e)?Q5:new RegExp(Cf,"i").test(e)&&!new RegExp(Cf+" pc","i").test(e)?NA:""},Sm="https?://(.*)",xu=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],aP=yu(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],xu),Wf="<masked>",oP=["li_fat_id"];function jA(e,t,n){if(!qe)return{};var r,s=t?yu([],xu,n||[]):[],i=CA(Yf(qe.URL,s,Wf),e),o=(r={},Cn(oP,(function(u){var f=Di.q(u);r[u]=f||null})),r);return Qn(o,i)}function CA(e,t){var n=aP.concat(t||[]),r={};return Cn(n,(function(s){var i=wp(e,s);r[s]=i||null})),r}function TA(e){var t=(function(i){return i?i.search(Sm+"google.([^/?]*)")===0?"google":i.search(Sm+"bing.com")===0?"bing":i.search(Sm+"yahoo.com")===0?"yahoo":i.search(Sm+"duckduckgo.com")===0?"duckduckgo":null:null})(e),n=t!="yahoo"?"q":"p",r={};if(!ja(t)){r.$search_engine=t;var s=qe?wp(qe.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function aE(){return navigator.language||navigator.userLanguage}function AA(){return qe?.referrer||"$direct"}function RA(e,t){var n=e?yu([],xu,t||[]):[],r=ps?.href.substring(0,1e3);return{r:AA().substring(0,1e3),u:r?Yf(r,n,Wf):void 0}}function MA(e){var t,{r:n,u:r}=e,s={$referrer:n,$referring_domain:n==null?void 0:n=="$direct"?"$direct":(t=bp(n))==null?void 0:t.host};if(r){s.$current_url=r;var i=bp(r);s.$host=i?.host,s.$pathname=i?.pathname;var o=CA(r);Qn(s,o)}if(n){var u=TA(n);Qn(s,u)}return s}function OA(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function lP(){try{return new Date().getTimezoneOffset()}catch{return}}function cP(e,t){if(!ms)return{};var n,r,s,i=e?yu([],xu,t||[]):[],[o,u]=(function(f){for(var h=0;h<sE.length;h++){var[p,g]=sE[h],v=p.exec(f),y=v&&(po(g)?g(v,f):g);if(y)return y}return["",""]})(ms);return Qn(iw({$os:o,$os_version:u,$browser:EA(ms,navigator.vendor),$device:iE(ms),$device_type:(r=ms,s=iE(r),s===fA||s===dA||s==="Kobo"||s==="Kindle Fire"||s===NA?Cf:s===Af||s===Yc||s===Rf||s===Pb?"Console":s===mA?"Wearable":s?Js:"Desktop"),$timezone:OA(),$timezone_offset:lP()}),{$current_url:Yf(ps?.href,i,Wf),$host:ps?.host,$pathname:ps?.pathname,$raw_user_agent:ms.length>1e3?ms.substring(0,997)+"...":ms,$browser_version:iP(ms,navigator.vendor),$browser_language:aE(),$browser_language_prefix:(n=aE(),typeof n=="string"?n.split("-")[0]:void 0),$screen_height:me?.screen.height,$screen_width:me?.screen.width,$viewport_height:me?.innerHeight,$viewport_width:me?.innerWidth,$lib:"web",$lib_version:fa.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var to=kr("[Web Vitals]"),oE=9e5;class uP{constructor(t){var n;this.Et=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.$t=()=>{clearTimeout(this.kt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((r,s)=>We({},r,{["$web_vitals_"+s.name+"_event"]:We({},s),["$web_vitals_"+s.name+"_value"]:s.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.Pt=r=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(Ue(i))to.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var o=this.Tt();Ue(o)||(An(r?.name)||An(r?.value)?to.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?to.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==o&&(this.$t(),this.kt=setTimeout(this.$t,this.flushToCaptureTimeoutMs)),Ue(this.N.url)&&(this.N.url=o),this.N.firstMetricTimestamp=Ue(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(We({},r,{$current_url:o,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.$t()))}},this.rt=()=>{var r,s,i,o,u=wt.__PosthogExtensions__;Ue(u)||Ue(u.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:s,onFCP:i,onINP:o}=u.postHogWebVitalsCallbacks),r&&s&&i&&o?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.Pt.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.Pt.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.Pt.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&o(this.Pt.bind(this)),this.P=!0):to.error("web vitals callbacks not loaded - not starting")},this._instance=t,this.Et=!((n=this._instance.persistence)==null||!n.props[VN]),this.startIfEnabled()}get allowedMetrics(){var t,n,r=$r(this._instance.config.capture_performance)?(t=this._instance.config.capture_performance)==null?void 0:t.web_vitals_allowed_metrics:void 0;return Ue(r)?((n=this._instance.persistence)==null?void 0:n.props[KN])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return($r(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get Rt(){var t=$r(this._instance.config.capture_performance)&&Fi(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:oE;return 0<t&&t<=6e4?oE:t}get isEnabled(){var t=ps?.protocol;if(t!=="http:"&&t!=="https:")return to.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=$r(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:go(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return go(n)?n:this.Et}startIfEnabled(){this.isEnabled&&!this.P&&(to.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(t){var n=$r(t.capturePerformance)&&!!t.capturePerformance.web_vitals,r=$r(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[VN]:n}),this._instance.persistence.register({[KN]:r})),this.Et=n,this.startIfEnabled()}it(t){var n,r;(n=wt.__PosthogExtensions__)!=null&&n.postHogWebVitalsCallbacks&&t(),(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"web-vitals",(s=>{s?to.error("failed to load script",s):t()}))}Tt(){var t=me?me.location.href:void 0;if(t){var n=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,s=n?yu([],xu,r||[]):[];return Yf(t,s,Wf)}to.error("Could not determine current URL")}}var dP=kr("[Heatmaps]");function lE(e){return $r(e)&&"clientX"in e&&"clientY"in e&&Fi(e.clientX)&&Fi(e.clientY)}class fP{constructor(t){var n;this.rageclicks=new aA,this.Et=!1,this.P=!1,this.It=null,this.instance=t,this.Et=!((n=this.instance.persistence)==null||!n.props[Eb])}get flushIntervalMilliseconds(){var t=5e3;return $r(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(t=this.instance.config.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return Ue(this.instance.config.capture_heatmaps)?Ue(this.instance.config.enable_heatmaps)?this.Et:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;dP.info("starting..."),this.Ct(),this.Ot()}else{var t;clearInterval((t=this.It)!==null&&t!==void 0?t:void 0),this.Ft(),this.getAndClearBuffer()}}onRemoteConfig(t){var n=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Eb]:n}),this.Et=n,this.startIfEnabled()}getAndClearBuffer(){var t=this.N;return this.N=void 0,t}Mt(t){this.At(t.originalEvent,"deadclick")}Ot(){this.It&&clearInterval(this.It),this.It=(function(t){return t?.visibilityState==="visible"})(qe)?setInterval(this.Dt.bind(this),this.flushIntervalMilliseconds):null}Ct(){me&&qe&&(this.jt=this.Dt.bind(this),dr(me,"beforeunload",this.jt),this.Lt=t=>this.At(t||me?.event),dr(qe,"click",this.Lt,{capture:!0}),this.Nt=t=>this.Ut(t||me?.event),dr(qe,"mousemove",this.Nt,{capture:!0}),this.zt=new lA(this.instance,F5,this.Mt.bind(this)),this.zt.startIfEnabled(),this.Ht=this.Ot.bind(this),dr(qe,"visibilitychange",this.Ht),this.P=!0)}Ft(){var t;me&&qe&&(this.jt&&me.removeEventListener("beforeunload",this.jt),this.Lt&&qe.removeEventListener("click",this.Lt,{capture:!0}),this.Nt&&qe.removeEventListener("mousemove",this.Nt,{capture:!0}),this.Ht&&qe.removeEventListener("visibilitychange",this.Ht),clearTimeout(this.Bt),(t=this.zt)==null||t.stop(),this.P=!1)}qt(t,n){var r=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),o=(function(u,f,h){for(var p=u;p&&sg(p)&&!yo(p,"body");){if(p===h)return!1;if(Bt(f,me?.getComputedStyle(p).position))return!0;p=JT(p)}return!1})(XT(t),["fixed","sticky"],i);return{x:t.clientX+(o?0:s),y:t.clientY+(o?0:r),target_fixed:o,type:n}}At(t,n){var r;if(n===void 0&&(n="click"),!GN(t.target)&&lE(t)){var s=this.qt(t,n);(r=this.rageclicks)!=null&&r.isRageClick(t.clientX,t.clientY,new Date().getTime())&&this.Wt(We({},s,{type:"rageclick"})),this.Wt(s)}}Ut(t){!GN(t.target)&&lE(t)&&(clearTimeout(this.Bt),this.Bt=setTimeout((()=>{this.Wt(this.qt(t,"mousemove"))}),500))}Wt(t){if(me){var n=me.location.href,r=this.instance.config.mask_personal_data_properties,s=this.instance.config.custom_personal_data_properties,i=r?yu([],xu,s||[]):[],o=Yf(n,i,Wf);this.N=this.N||{},this.N[o]||(this.N[o]=[]),this.N[o].push(t)}}Dt(){this.N&&!Pc(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class hP{constructor(t){this._instance=t}doPageView(t,n){var r,s=this.Gt(t,n);return this.Vt={pathname:(r=me?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:t},this._instance.scrollManager.resetContext(),s}doPageLeave(t){var n;return this.Gt(t,(n=this.Vt)==null?void 0:n.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this.Vt)==null?void 0:t.pageViewId}}Gt(t,n){var r=this.Vt;if(!r)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:u,maxScrollY:f,maxContentHeight:h,lastContentY:p,maxContentY:g}=i;if(!(Ue(o)||Ue(u)||Ue(f)||Ue(h)||Ue(p)||Ue(g))){o=Math.ceil(o),u=Math.ceil(u),f=Math.ceil(f),h=Math.ceil(h),p=Math.ceil(p),g=Math.ceil(g);var v=o<=1?1:Ri(u/o,0,1,Ge),y=o<=1?1:Ri(f/o,0,1,Ge),S=h<=1?1:Ri(p/h,0,1,Ge),w=h<=1?1:Ri(g/h,0,1,Ge);s=Qn(s,{$prev_pageview_last_scroll:u,$prev_pageview_last_scroll_percentage:v,$prev_pageview_max_scroll:f,$prev_pageview_max_scroll_percentage:y,$prev_pageview_last_content:p,$prev_pageview_last_content_percentage:S,$prev_pageview_max_content:g,$prev_pageview_max_content_percentage:w})}}return r.pathname&&(s.$prev_pageview_pathname=r.pathname),r.timestamp&&(s.$prev_pageview_duration=(t.getTime()-r.timestamp.getTime())/1e3),s}}var ei=Uint8Array,vs=Uint16Array,iu=Uint32Array,hw=new ei([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]),mw=new ei([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]),cE=new ei([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),IA=function(e,t){for(var n=new vs(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];var s=new iu(n[30]);for(r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)s[i]=i-n[r]<<5|r;return[n,s]},LA=IA(hw,2),mP=LA[0],$b=LA[1];mP[28]=258,$b[258]=28;for(var uE=IA(mw,0)[1],DA=new vs(32768),Mn=0;Mn<32768;++Mn){var rl=(43690&Mn)>>>1|(21845&Mn)<<1;rl=(61680&(rl=(52428&rl)>>>2|(13107&rl)<<2))>>>4|(3855&rl)<<4,DA[Mn]=((65280&rl)>>>8|(255&rl)<<8)>>>1}var hf=function(e,t,n){for(var r=e.length,s=0,i=new vs(t);s<r;++s)++i[e[s]-1];var o,u=new vs(t);for(s=0;s<t;++s)u[s]=u[s-1]+i[s-1]<<1;for(o=new vs(r),s=0;s<r;++s)o[s]=DA[u[e[s]-1]++]>>>15-e[s];return o},xl=new ei(288);for(Mn=0;Mn<144;++Mn)xl[Mn]=8;for(Mn=144;Mn<256;++Mn)xl[Mn]=9;for(Mn=256;Mn<280;++Mn)xl[Mn]=7;for(Mn=280;Mn<288;++Mn)xl[Mn]=8;var kp=new ei(32);for(Mn=0;Mn<32;++Mn)kp[Mn]=5;var pP=hf(xl,9),gP=hf(kp,5),PA=function(e){return(e/8>>0)+(7&e&&1)},zA=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var r=new(e instanceof vs?vs:e instanceof iu?iu:ei)(n-t);return r.set(e.subarray(t,n)),r},la=function(e,t,n){n<<=7&t;var r=t/8>>0;e[r]|=n,e[r+1]|=n>>>8},Dd=function(e,t,n){n<<=7&t;var r=t/8>>0;e[r]|=n,e[r+1]|=n>>>8,e[r+2]|=n>>>16},lx=function(e,t){for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var s=n.length,i=n.slice();if(!s)return[new ei(0),0];if(s==1){var o=new ei(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(M,A){return M.f-A.f})),n.push({s:-1,f:25001});var u=n[0],f=n[1],h=0,p=1,g=2;for(n[0]={s:-1,f:u.f+f.f,l:u,r:f};p!=s-1;)u=n[n[h].f<n[g].f?h++:g++],f=n[h!=p&&n[h].f<n[g].f?h++:g++],n[p++]={s:-1,f:u.f+f.f,l:u,r:f};var v=i[0].s;for(r=1;r<s;++r)i[r].s>v&&(v=i[r].s);var y=new vs(v+1),S=Fb(n[p-1],y,0);if(S>t){r=0;var w=0,N=S-t,k=1<<N;for(i.sort((function(M,A){return y[A.s]-y[M.s]||M.f-A.f}));r<s;++r){var j=i[r].s;if(!(y[j]>t))break;w+=k-(1<<S-y[j]),y[j]=t}for(w>>>=N;w>0;){var E=i[r].s;y[E]<t?w-=1<<t-y[E]++-1:++r}for(;r>=0&&w;--r){var C=i[r].s;y[C]==t&&(--y[C],++w)}S=t}return[new ei(y),S]},Fb=function(e,t,n){return e.s==-1?Math.max(Fb(e.l,t,n+1),Fb(e.r,t,n+1)):t[e.s]=n},dE=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new vs(++t),r=0,s=e[0],i=1,o=function(f){n[r++]=f},u=1;u<=t;++u)if(e[u]==s&&u!=t)++i;else{if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0)}for(;i--;)o(s);i=1,s=e[u]}return[n.subarray(0,r),t]},Pd=function(e,t){for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},Ub=function(e,t,n){var r=n.length,s=PA(t+2);e[s]=255&r,e[s+1]=r>>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var i=0;i<r;++i)e[s+i+4]=n[i];return 8*(s+4+r)},fE=function(e,t,n,r,s,i,o,u,f,h,p){la(t,p++,n),++s[256];for(var g=lx(s,15),v=g[0],y=g[1],S=lx(i,15),w=S[0],N=S[1],k=dE(v),j=k[0],E=k[1],C=dE(w),M=C[0],A=C[1],O=new vs(19),I=0;I<j.length;++I)O[31&j[I]]++;for(I=0;I<M.length;++I)O[31&M[I]]++;for(var G=lx(O,7),z=G[0],W=G[1],$=19;$>4&&!z[cE[$-1]];--$);var B,K,H,R,q=h+5<<3,F=Pd(s,xl)+Pd(i,kp)+o,U=Pd(s,v)+Pd(i,w)+o+14+3*$+Pd(O,z)+(2*O[16]+3*O[17]+7*O[18]);if(q<=F&&q<=U)return Ub(t,p,e.subarray(f,f+h));if(la(t,p,1+(U<F)),p+=2,U<F){B=hf(v,y),K=v,H=hf(w,N),R=w;var D=hf(z,W);for(la(t,p,E-257),la(t,p+5,A-1),la(t,p+10,$-4),p+=14,I=0;I<$;++I)la(t,p+3*I,z[cE[I]]);p+=3*$;for(var Q=[j,M],re=0;re<2;++re){var L=Q[re];for(I=0;I<L.length;++I){var we=31&L[I];la(t,p,D[we]),p+=z[we],we>15&&(la(t,p,L[I]>>>5&127),p+=L[I]>>>12)}}}else B=pP,K=xl,H=gP,R=kp;for(I=0;I<u;++I)if(r[I]>255){we=r[I]>>>18&31,Dd(t,p,B[we+257]),p+=K[we+257],we>7&&(la(t,p,r[I]>>>23&31),p+=hw[we]);var De=31&r[I];Dd(t,p,H[De]),p+=R[De],De>3&&(Dd(t,p,r[I]>>>5&8191),p+=mw[De])}else Dd(t,p,B[r[I]]),p+=K[r[I]];return Dd(t,p,B[256]),p+K[256]},vP=new iu([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),yP=(function(){for(var e=new iu(256),t=0;t<256;++t){for(var n=t,r=9;--r;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e})(),xP=function(e,t,n,r,s){return(function(i,o,u,f,h,p){var g=i.length,v=new ei(f+g+5*(1+Math.floor(g/7e3))+h),y=v.subarray(f,v.length-h),S=0;if(!o||g<8)for(var w=0;w<=g;w+=65535){var N=w+65535;N<g?S=Ub(y,S,i.subarray(w,N)):(y[w]=p,S=Ub(y,S,i.subarray(w,g)))}else{for(var k=vP[o-1],j=k>>>13,E=8191&k,C=(1<<u)-1,M=new vs(32768),A=new vs(C+1),O=Math.ceil(u/3),I=2*O,G=function(ft){return(i[ft]^i[ft+1]<<O^i[ft+2]<<I)&C},z=new iu(25e3),W=new vs(288),$=new vs(32),B=0,K=0,H=(w=0,0),R=0,q=0;w<g;++w){var F=G(w),U=32767&w,D=A[F];if(M[U]=D,A[F]=U,R<=w){var Q=g-w;if((B>7e3||H>24576)&&Q>423){S=fE(i,y,0,z,W,$,K,H,q,w-q,S),H=B=K=0,q=w;for(var re=0;re<286;++re)W[re]=0;for(re=0;re<30;++re)$[re]=0}var L=2,we=0,De=E,Oe=U-D&32767;if(Q>2&&F==G(w-Oe))for(var oe=Math.min(j,Q)-1,Pe=Math.min(32767,w),nt=Math.min(258,Q);Oe<=Pe&&--De&&U!=D;){if(i[w+L]==i[w+L-Oe]){for(var he=0;he<nt&&i[w+he]==i[w+he-Oe];++he);if(he>L){if(L=he,we=Oe,he>oe)break;var de=Math.min(Oe,he-2),ee=0;for(re=0;re<de;++re){var pe=w-Oe+re+32768&32767,Se=pe-M[pe]+32768&32767;Se>ee&&(ee=Se,D=pe)}}}Oe+=(U=D)-(D=M[U])+32768&32767}if(we){z[H++]=268435456|$b[L]<<18|uE[we];var Xe=31&$b[L],He=31&uE[we];K+=hw[Xe]+mw[He],++W[257+Xe],++$[He],R=w+L,++B}else z[H++]=i[w],++W[i[w]]}}S=fE(i,y,p,z,W,$,K,H,q,w-q,S)}return zA(v,0,f+PA(S)+h)})(e,t.level==null?6:t.level,t.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(e.length)))):12+t.mem,n,r,!0)},cx=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function bP(e,t){t===void 0&&(t={});var n=(function(){var u=4294967295;return{p:function(f){for(var h=u,p=0;p<f.length;++p)h=yP[255&h^f[p]]^h>>>8;u=h},d:function(){return 4294967295^u}}})(),r=e.length;n.p(e);var s,i=xP(e,t,10+((s=t).filename&&s.filename.length+1||0),8),o=i.length;return(function(u,f){var h=f.filename;if(u[0]=31,u[1]=139,u[2]=8,u[8]=f.level<2?4:f.level==9?2:0,u[9]=3,f.mtime!=0&&cx(u,4,Math.floor(new Date(f.mtime||Date.now())/1e3)),h){u[3]=8;for(var p=0;p<=h.length;++p)u[p+10]=h.charCodeAt(p)}})(i,t),cx(i,o-8,n.d()),cx(i,o-4,r),i}var wP=function(e){var t,n,r,s,i="";for(t=n=0,r=(e=(e+"").replace(/\r\n/g,`
27
27
  `).replace(/\r/g,`
28
28
  `)).length,s=0;s<r;s++){var o=e.charCodeAt(s),u=null;o<128?n++:u=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),ja(u)||(n>t&&(i+=e.substring(t,n)),i+=u,t=n=s+1)}return n>t&&(i+=e.substring(t,e.length)),i},_P=!!wb||!!bb,hE="text/plain",Np=function(e,t,n){var r;n===void 0&&(n=!0);var[s,i]=e.split("?"),o=We({},t),u=(r=i?.split("&").map((h=>{var p,[g,v]=h.split("="),y=n&&(p=o[g])!==null&&p!==void 0?p:v;return delete o[g],g+"="+y})))!==null&&r!==void 0?r:[],f=E5(o);return f&&u.push(f),s+"?"+u.join("&")},nf=(e,t)=>JSON.stringify(e,((n,r)=>typeof r=="bigint"?r.toString():r),t),ux=e=>{var{data:t,compression:n}=e;if(t){if(n===pa.GZipJS){var r=bP((function(f,h){var p=f.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(f);for(var g=new ei(f.length+(f.length>>>1)),v=0,y=function(k){g[v++]=k},S=0;S<p;++S){if(v+5>g.length){var w=new ei(v+8+(p-S<<1));w.set(g),g=w}var N=f.charCodeAt(S);N<128||h?y(N):N<2048?(y(192|N>>>6),y(128|63&N)):N>55295&&N<57344?(y(240|(N=65536+(1047552&N)|1023&f.charCodeAt(++S))>>>18),y(128|N>>>12&63),y(128|N>>>6&63),y(128|63&N)):(y(224|N>>>12),y(128|N>>>6&63),y(128|63&N))}return zA(g,0,v)})(nf(t)),{mtime:0}),s=new Blob([r],{type:hE});return{contentType:hE,body:s,estimatedSize:s.size}}if(n===pa.Base64){var i=(function(f){var h,p,g,v,y,S="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",w=0,N=0,k="",j=[];if(!f)return f;f=wP(f);do h=(y=f.charCodeAt(w++)<<16|f.charCodeAt(w++)<<8|f.charCodeAt(w++))>>18&63,p=y>>12&63,g=y>>6&63,v=63&y,j[N++]=S.charAt(h)+S.charAt(p)+S.charAt(g)+S.charAt(v);while(w<f.length);switch(k=j.join(""),f.length%3){case 1:k=k.slice(0,-2)+"==";break;case 2:k=k.slice(0,-1)+"="}return k})(nf(t)),o=(f=>"data="+encodeURIComponent(typeof f=="string"?f:nf(f)))(i);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var u=nf(t);return{contentType:"application/json",body:u,estimatedSize:new Blob([u]).size}}},ep=[];bb&&ep.push({transport:"fetch",method:e=>{var t,n,{contentType:r,body:s,estimatedSize:i}=(t=ux(e))!==null&&t!==void 0?t:{},o=new Headers;Cn(e.headers,(function(p,g){o.append(g,p)})),r&&o.append("Content-Type",r);var u=e.url,f=null;if(IN){var h=new IN;f={signal:h.signal,timeout:setTimeout((()=>h.abort()),e.timeout)}}bb(u,We({method:e?.method||"GET",headers:o,keepalive:e.method==="POST"&&(i||0)<52428.8,body:s,signal:(n=f)==null?void 0:n.signal},e.fetchOptions)).then((p=>p.text().then((g=>{var v={statusCode:p.status,text:g};if(p.status===200)try{v.json=JSON.parse(g)}catch(y){Ge.error(y)}e.callback==null||e.callback(v)})))).catch((p=>{Ge.error(p),e.callback==null||e.callback({statusCode:0,text:p})})).finally((()=>f?clearTimeout(f.timeout):null))}}),wb&&ep.push({transport:"XHR",method:e=>{var t,n=new wb;n.open(e.method||"GET",e.url,!0);var{contentType:r,body:s}=(t=ux(e))!==null&&t!==void 0?t:{};Cn(e.headers,(function(i,o){n.setRequestHeader(o,i)})),r&&n.setRequestHeader("Content-Type",r),e.timeout&&(n.timeout=e.timeout),e.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var i={statusCode:n.status,text:n.responseText};if(n.status===200)try{i.json=JSON.parse(n.responseText)}catch{}e.callback==null||e.callback(i)}},n.send(s)}}),Ls!=null&&Ls.sendBeacon&&ep.push({transport:"sendBeacon",method:e=>{var t=Np(e.url,{beacon:"1"});try{var n,{contentType:r,body:s}=(n=ux(e))!==null&&n!==void 0?n:{},i=typeof s=="string"?new Blob([s],{type:r}):s;Ls.sendBeacon(t,i)}catch{}}});var au=function(e,t){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}};function mE(e,t,n){return nf({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}var $A={exact:(e,t)=>t.some((n=>e.some((r=>n===r)))),is_not:(e,t)=>t.every((n=>e.every((r=>n!==r)))),regex:(e,t)=>t.some((n=>e.some((r=>au(n,r))))),not_regex:(e,t)=>t.every((n=>e.every((r=>!au(n,r))))),icontains:(e,t)=>t.map(km).some((n=>e.map(km).some((r=>n.includes(r))))),not_icontains:(e,t)=>t.map(km).every((n=>e.map(km).every((r=>!n.includes(r)))))},km=e=>e.toLowerCase(),dx=kr("[Error tracking]");let SP=class{constructor(t){var n,r;this.Jt=[],this.Kt=new n5([new r5,new f5,new i5,new s5,new u5,new c5,new o5,new d5],[X3,e5]),this._instance=t,this.Jt=(n=(r=this._instance.persistence)==null?void 0:r.get_property(jb))!==null&&n!==void 0?n:[]}onRemoteConfig(t){var n,r,s,i=(n=(r=t.errorTracking)==null?void 0:r.suppressionRules)!==null&&n!==void 0?n:[],o=(s=t.errorTracking)==null?void 0:s.captureExtensionExceptions;this.Jt=i,this._instance.persistence&&this._instance.persistence.register({[jb]:this.Jt,[HN]:o})}get Yt(){var t,n=!!this._instance.get_property(HN),r=this._instance.config.error_tracking.captureExtensionExceptions;return(t=r??n)!==null&&t!==void 0&&t}buildProperties(t,n){return this.Kt.buildFromUnknown(t,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(t){var n=t.$exception_list;if(this.Xt(n)){if(this.Qt(n))return void dx.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(n))return void dx.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(n))return void dx.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",t,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(t){if(t.length===0)return!1;var n=t.reduce(((r,s)=>{var{type:i,value:o}=s;return yr(i)&&i.length>0&&r.$exception_types.push(i),yr(o)&&o.length>0&&r.$exception_values.push(o),r}),{$exception_types:[],$exception_values:[]});return this.Jt.some((r=>{var s=r.values.map((i=>{var o,u=$A[i.operator],f=Rn(i.value)?i.value:[i.value],h=(o=n[i.key])!==null&&o!==void 0?o:[];return f.length>0&&u(f,h)}));return r.type==="OR"?s.some(Boolean):s.every(Boolean)}))}Zt(t){return t.flatMap((n=>{var r,s;return(r=(s=n.stacktrace)==null?void 0:s.frames)!==null&&r!==void 0?r:[]})).some((n=>n.filename&&n.filename.startsWith("chrome-extension://")))}ti(t){if(t.length>0){var n,r,s,i,o=(n=(r=t[0].stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[],u=o[o.length-1];return(s=u==null||(i=u.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&s!==void 0&&s}return!1}Xt(t){return!An(t)&&Rn(t)}};var hi=kr("[FeatureFlags]"),fx="$active_feature_flags",bc="$override_feature_flags",pE="$feature_flag_payloads",zd="$override_feature_flag_payloads",gE="$feature_flag_request_id",vE=e=>{var t={};for(var[n,r]of Jm(e||{}))r&&(t[n]=r);return t},kP=e=>{var t=e.flags;return t?(e.featureFlags=Object.fromEntries(Object.keys(t).map((n=>{var r;return[n,(r=t[n].variant)!==null&&r!==void 0?r:t[n].enabled]}))),e.featureFlagPayloads=Object.fromEntries(Object.keys(t).filter((n=>t[n].enabled)).filter((n=>{var r;return(r=t[n].metadata)==null?void 0:r.payload})).map((n=>{var r;return[n,(r=t[n].metadata)==null?void 0:r.payload]})))):hi.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),e},NP=(function(e){return e.FeatureFlags="feature_flags",e.Recordings="recordings",e})({});class EP{constructor(t){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=t,this.featureFlagEventHandlers=[]}li(){var t=this._instance.config.evaluation_environments;return t!=null&&t.length?t.filter((n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||hi.error("Invalid evaluation environment found:",n,"Expected non-empty string"),r})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var t=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.di({disableFlags:t})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this._instance.get_property(Cb),n=this._instance.get_property(bc),r=this._instance.get_property(zd);if(!r&&!n)return t||{};var s=Qn({},t||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(n||{})])];for(var o of i){var u,f,h=s[o],p=n?.[o],g=Ue(p)?(u=h?.enabled)!==null&&u!==void 0&&u:!!p,v=Ue(p)?h.variant:typeof p=="string"?p:void 0,y=r?.[o],S=We({},h,{enabled:g,variant:g?v??h?.variant:void 0});g!==h?.enabled&&(S.original_enabled=h?.enabled),v!==h?.variant&&(S.original_variant=h?.variant),y&&(S.metadata=We({},h?.metadata,{payload:y,original_payload:h==null||(f=h.metadata)==null?void 0:f.payload})),s[o]=S}return this.ii||(hi.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:r,finalDetails:s}),this.ii=!0),s}getFlagVariants(){var t=this._instance.get_property(zc),n=this._instance.get_property(bc);if(!n)return t||{};for(var r=Qn({},t),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.ii||(hi.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:n,finalFlags:r}),this.ii=!0),r}getFlagPayloads(){var t=this._instance.get_property(pE),n=this._instance.get_property(zd);if(!n)return t||{};for(var r=Qn({},t||{}),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.ii||(hi.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:n,finalPayloads:r}),this.ii=!0),r}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.di()}),5))}vi(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this.si=t}di(t){var n;if(this.vi(),!this._instance.M())if(this.ri)this.ni=!0;else{var r={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:We({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(ef)||{}),group_properties:this._instance.get_property(cl)};(t!=null&&t.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0),this.ui()&&(r.evaluation_environments=this.li());var s=this._instance.config.__preview_remote_config,i=s?"/flags/?v=2":"/flags/?v=2&config=true",o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",u=this._instance.requestRouter.endpointFor("api",i+o);s&&(r.timezone=OA()),this.ri=!0,this._instance.ci({method:"POST",url:u,data:r,compression:this._instance.config.disable_compression?void 0:pa.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:f=>{var h,p,g=!0;if(f.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),g=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((p=f.json)!==null&&p!==void 0?p:{})),!r.disable_flags||this.ni)if(this.ai=!g,f.json&&(h=f.json.quotaLimited)!=null&&h.includes(NP.FeatureFlags))hi.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.");else{var v;r.disable_flags||this.receivedFeatureFlags((v=f.json)!==null&&v!==void 0?v:{},g),this.ni&&(this.ni=!1,this.di())}}})}}getFeatureFlag(t,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[t],s=""+r,i=this._instance.get_property(gE)||void 0,o=this._instance.get_property(gp)||{};if((n.send_event||!("send_event"in n))&&(!(t in o)||!o[t].includes(s))){var u,f,h,p,g,v,y,S,w;Rn(o[t])?o[t].push(s):o[t]=[s],(u=this._instance.persistence)==null||u.register({[gp]:o});var N=this.getFeatureFlagDetails(t),k={$feature_flag:t,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(t)||null,$feature_flag_request_id:i,$feature_flag_bootstrapped_response:((f=this._instance.config.bootstrap)==null||(f=f.featureFlags)==null?void 0:f[t])||null,$feature_flag_bootstrapped_payload:((h=this._instance.config.bootstrap)==null||(h=h.featureFlagPayloads)==null?void 0:h[t])||null,$used_bootstrap_value:!this.ai};Ue(N==null||(p=N.metadata)==null?void 0:p.version)||(k.$feature_flag_version=N.metadata.version);var j,E=(g=N==null||(v=N.reason)==null?void 0:v.description)!==null&&g!==void 0?g:N==null||(y=N.reason)==null?void 0:y.code;E&&(k.$feature_flag_reason=E),N!=null&&(S=N.metadata)!=null&&S.id&&(k.$feature_flag_id=N.metadata.id),Ue(N?.original_variant)&&Ue(N?.original_enabled)||(k.$feature_flag_original_response=Ue(N.original_variant)?N.original_enabled:N.original_variant),N!=null&&(w=N.metadata)!=null&&w.original_payload&&(k.$feature_flag_original_payload=N==null||(j=N.metadata)==null?void 0:j.original_payload),this._instance.capture("$feature_flag_called",k)}return r}hi.warn('getFeatureFlag for key "'+t+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){return this.getFlagPayloads()[t]}getRemoteConfigPayload(t,n){var r=this._instance.config.token,s={distinct_id:this._instance.get_distinct_id(),token:r};this.ui()&&(s.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("api","/flags/?v=2&config=true"),data:s,compression:this._instance.config.disable_compression?void 0:pa.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var o,u=(o=i.json)==null?void 0:o.featureFlagPayloads;n(u?.[t]||void 0)}})}isFeatureEnabled(t,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(t,n);return Ue(r)?void 0:!!r}hi.warn('isFeatureEnabled for key "'+t+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((n=>n!==t))}receivedFeatureFlags(t,n){if(this._instance.persistence){this.ei=!0;var r=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(o,u,f,h,p){f===void 0&&(f={}),h===void 0&&(h={}),p===void 0&&(p={});var g=kP(o),v=g.flags,y=g.featureFlags,S=g.featureFlagPayloads;if(y){var w=o.requestId;if(Rn(y)){hi.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var N={};if(y)for(var k=0;k<y.length;k++)N[y[k]]=!0;u&&u.register({[fx]:y,[zc]:N})}else{var j=y,E=S,C=v;o.errorsWhileComputingFlags&&(j=We({},f,j),E=We({},h,E),C=We({},p,C)),u&&u.register(We({[fx]:Object.keys(vE(j)),[zc]:j||{},[pE]:E||{},[Cb]:C||{}},w?{[gE]:w}:{}))}}})(t,this._instance.persistence,r,s,i),this.pi(n)}}override(t,n){n===void 0&&(n=!1),hi.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:n})}overrideFeatureFlags(t){if(!this._instance.__loaded||!this._instance.persistence)return hi.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(t===!1)return this._instance.persistence.unregister(bc),this._instance.persistence.unregister(zd),void this.pi();if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var n,r=t;if(this.ii=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(bc);else if(r.flags)if(Rn(r.flags)){for(var s={},i=0;i<r.flags.length;i++)s[r.flags[i]]=!0;this._instance.persistence.register({[bc]:s})}else this._instance.persistence.register({[bc]:r.flags})}return"payloads"in r&&(r.payloads===!1?this._instance.persistence.unregister(zd):r.payloads&&this._instance.persistence.register({[zd]:r.payloads})),void this.pi()}this.pi()}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ei){var{flags:n,flagVariants:r}=this.gi();t(n,r)}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,n,r){var s,i=(this._instance.get_property(Jd)||[]).find((h=>h.flagKey===t)),o={["$feature_enrollment/"+t]:n},u={$feature_flag:t,$feature_enrollment:n,$set:o};i&&(u.$early_access_feature_name=i.name),r&&(u.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",u),this.setPersonPropertiesForFlags(o,!1);var f=We({},this.getFlagVariants(),{[t]:n});(s=this._instance.persistence)==null||s.register({[fx]:Object.keys(vE(f)),[zc]:f}),this.pi()}getEarlyAccessFeatures(t,n,r){n===void 0&&(n=!1);var s=this._instance.get_property(Jd),i=r?"&"+r.map((o=>"stage="+o)).join("&"):"";if(s&&!n)return t(s);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:o=>{var u,f;if(o.json){var h=o.json.earlyAccessFeatures;return(u=this._instance.persistence)==null||u.unregister(Jd),(f=this._instance.persistence)==null||f.register({[Jd]:h}),t(h)}}})}gi(){var t=this.getFlags(),n=this.getFlagVariants();return{flags:t.filter((r=>n[r])),flagVariants:Object.keys(n).filter((r=>n[r])).reduce(((r,s)=>(r[s]=n[s],r)),{})}}pi(t){var{flags:n,flagVariants:r}=this.gi();this.featureFlagEventHandlers.forEach((s=>s(n,r,{errorsLoading:t})))}setPersonPropertiesForFlags(t,n){n===void 0&&(n=!0);var r=this._instance.get_property(ef)||{};this._instance.register({[ef]:We({},r,t)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(ef)}setGroupPropertiesForFlags(t,n){n===void 0&&(n=!0);var r=this._instance.get_property(cl)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((s=>{r[s]=We({},r[s],t[s]),delete t[s]})),this._instance.register({[cl]:We({},r,t)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var n=this._instance.get_property(cl)||{};this._instance.register({[cl]:We({},n,{[t]:{}})})}else this._instance.unregister(cl)}reset(){this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.$anon_distinct_id=void 0,this.vi(),this.ii=!1}}var jP=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class hx{constructor(t,n){this.C=t,this.props={},this.mi=!1,this.yi=(r=>{var s="";return r.token&&(s=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+s+"_posthog"})(t),this.Y=this.bi(t),this.load(),t.debug&&Ge.info("Persistence loaded",t.persistence,We({},this.props)),this.update_config(t,t,n),this.save()}isDisabled(){return!!this.wi}bi(t){jP.indexOf(t.persistence.toLowerCase())===-1&&(Ge.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=t.persistence.toLowerCase();return n==="localstorage"&&qn.H()?qn:n==="localstorage+cookie"&&bm.H()?bm:n==="sessionstorage"&&Ar.H()?Ar:n==="memory"?z5:n==="cookie"?Di:bm.H()?bm:Di}properties(){var t={};return Cn(this.props,(function(n,r){if(r===zc&&$r(n))for(var s=Object.keys(n),i=0;i<s.length;i++)t["$feature/"+s[i]]=n[s[i]];else u=r,f=!1,(ja(o=y5)?f:ON&&o.indexOf===ON?o.indexOf(u)!=-1:(Cn(o,(function(h){if(f||(f=h===u))return mp})),f))||(t[r]=n);var o,u,f})),t}load(){if(!this.wi){var t=this.Y.W(this.yi);t&&(this.props=Qn({},t))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.Si,this.Ei,this.C.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(t,n,r){if($r(t)){Ue(n)&&(n="None"),this.xi=Ue(r)?this.$i:r;var s=!1;if(Cn(t,((i,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=i,s=!0)})),s)return this.save(),!0}return!1}register(t,n){if($r(t)){this.xi=Ue(n)?this.$i:n;var r=!1;if(Cn(t,((s,i)=>{t.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,r=!0)})),r)return this.save(),!0}return!1}unregister(t){t in this.props&&(delete this.props[t],this.save())}update_campaign_params(){if(!this.mi){var t=jA(this.C.custom_campaign_params,this.C.mask_personal_data_properties,this.C.custom_personal_data_properties);Pc(iw(t))||this.register(t),this.mi=!0}}update_search_keyword(){var t;this.register((t=qe?.referrer)?TA(t):{})}update_referrer_info(){var t;this.register_once({$referrer:AA(),$referring_domain:qe!=null&&qe.referrer&&((t=bp(qe.referrer))==null?void 0:t.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Mb]||this.props[Ob]||this.register_once({[vp]:RA(this.C.mask_personal_data_properties,this.C.custom_personal_data_properties)},void 0)}get_initial_props(){var t={};Cn([Ob,Mb],(o=>{var u=this.props[o];u&&Cn(u,(function(f,h){t["$initial_"+_b(h)]=f}))}));var n,r,s=this.props[vp];if(s){var i=(n=MA(s),r={},Cn(n,(function(o,u){r["$initial_"+_b(u)]=o})),r);Qn(t,i)}return t}safe_merge(t){return Cn(this.props,(function(n,r){r in t||(t[r]=n)})),t}update_config(t,n,r){if(this.$i=this.xi=t.cookie_expiration,this.set_disabled(t.disable_persistence||!!r),this.set_cross_subdomain(t.cross_subdomain_cookie),this.set_secure(t.secure_cookie),t.persistence!==n.persistence){var s=this.bi(t),i=this.props;this.clear(),this.Y=s,this.props=i,this.save()}}set_disabled(t){this.wi=t,this.wi?this.remove():this.save()}set_cross_subdomain(t){t!==this.Si&&(this.Si=t,this.remove(),this.save())}set_secure(t){t!==this.Ei&&(this.Ei=t,this.remove(),this.save())}set_event_timer(t,n){var r=this.props[Qd]||{};r[t]=n,this.props[Qd]=r,this.save()}remove_event_timer(t){var n=(this.props[Qd]||{})[t];return Ue(n)||(delete this.props[Qd][t],this.save()),n}get_property(t){return this.props[t]}set_property(t,n){this.props[t]=n,this.save()}}(function(e){return e.Button="button",e.Tab="tab",e.Selector="selector",e})({});(function(e){return e.TopLeft="top_left",e.TopRight="top_right",e.TopCenter="top_center",e.MiddleLeft="middle_left",e.MiddleRight="middle_right",e.MiddleCenter="middle_center",e.Left="left",e.Center="center",e.Right="right",e.NextToTrigger="next_to_trigger",e})({});var mx=(function(e){return e.Popover="popover",e.API="api",e.Widget="widget",e.ExternalSurvey="external_survey",e})({});(function(e){return e.Open="open",e.MultipleChoice="multiple_choice",e.SingleChoice="single_choice",e.Rating="rating",e.Link="link",e})({});(function(e){return e.NextQuestion="next_question",e.End="end",e.ResponseBased="response_based",e.SpecificQuestion="specific_question",e})({});(function(e){return e.Once="once",e.Recurring="recurring",e.Always="always",e})({});var tp=(function(e){return e.SHOWN="survey shown",e.DISMISSED="survey dismissed",e.SENT="survey sent",e})({}),yE=(function(e){return e.SURVEY_ID="$survey_id",e.SURVEY_NAME="$survey_name",e.SURVEY_RESPONSE="$survey_response",e.SURVEY_ITERATION="$survey_iteration",e.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",e.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",e.SURVEY_SUBMISSION_ID="$survey_submission_id",e.SURVEY_QUESTIONS="$survey_questions",e.SURVEY_COMPLETED="$survey_completed",e})({}),FA=(function(e){return e.Popover="popover",e.Inline="inline",e})({});class pw{constructor(){this.ki={},this.ki={}}on(t,n){return this.ki[t]||(this.ki[t]=[]),this.ki[t].push(n),()=>{this.ki[t]=this.ki[t].filter((r=>r!==n))}}emit(t,n){for(var r of this.ki[t]||[])r(n);for(var s of this.ki["*"]||[])s(t,n)}}class fl{constructor(t){this.Pi=new pw,this.Ti=(n,r)=>this.Ri(n,r)&&this.Ii(n,r)&&this.Ci(n,r),this.Ri=(n,r)=>r==null||!r.event||n?.event===r?.event,this._instance=t,this.Oi=new Set,this.Fi=new Set}init(){var t;if(!Ue((t=this._instance)==null?void 0:t.Mi)){var n;(n=this._instance)==null||n.Mi(((r,s)=>{this.on(r,s)}))}}register(t){var n,r;if(!Ue((n=this._instance)==null?void 0:n.Mi)&&(t.forEach((o=>{var u,f;(u=this.Fi)==null||u.add(o),(f=o.steps)==null||f.forEach((h=>{var p;(p=this.Oi)==null||p.add(h?.event||"")}))})),(r=this._instance)!=null&&r.autocapture)){var s,i=new Set;t.forEach((o=>{var u;(u=o.steps)==null||u.forEach((f=>{f!=null&&f.selector&&i.add(f?.selector)}))})),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(t,n){var r;n!=null&&t.length!=0&&(this.Oi.has(t)||this.Oi.has(n?.event))&&this.Fi&&((r=this.Fi)==null?void 0:r.size)>0&&this.Fi.forEach((s=>{this.Ai(n,s)&&this.Pi.emit("actionCaptured",s.name)}))}Di(t){this.onAction("actionCaptured",(n=>t(n)))}Ai(t,n){if(n?.steps==null)return!1;for(var r of n.steps)if(this.Ti(t,r))return!0;return!1}onAction(t,n){return this.Pi.on(t,n)}Ii(t,n){if(n!=null&&n.url){var r,s=t==null||(r=t.properties)==null?void 0:r.$current_url;if(!s||typeof s!="string"||!fl.ji(s,n?.url,n?.url_matching||"contains"))return!1}return!0}static ji(t,n,r){switch(r){case"regex":return!!me&&au(t,n);case"exact":return n===t;case"contains":var s=fl.Li(n).replace(/_/g,".").replace(/%/g,".*");return au(t,s);default:return!1}}static Li(t){return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}Ci(t,n){if((n!=null&&n.href||n!=null&&n.tag_name||n!=null&&n.text)&&!this.Ni(t).some((i=>!(n!=null&&n.href&&!fl.ji(i.href||"",n?.href,n?.href_matching||"exact"))&&(n==null||!n.tag_name||i.tag_name===n?.tag_name)&&!(n!=null&&n.text&&!fl.ji(i.text||"",n?.text,n?.text_matching||"exact")&&!fl.ji(i.$el_text||"",n?.text,n?.text_matching||"exact")))))return!1;if(n!=null&&n.selector){var r,s=t==null||(r=t.properties)==null?void 0:r.$element_selectors;if(!s||!s.includes(n?.selector))return!1}return!0}Ni(t){return t?.properties.$elements==null?[]:t?.properties.$elements}}var yn=kr("[Surveys]"),Bb="seenSurvey_",CP=(e,t)=>{var n="$survey_"+t+"/"+e.id;return e.current_iteration&&e.current_iteration>0&&(n="$survey_"+t+"/"+e.id+"/"+e.current_iteration),n},xE=e=>{var t=""+Bb+e.id;return e.current_iteration&&e.current_iteration>0&&(t=""+Bb+e.id+"_"+e.current_iteration),t},TP=[mx.Popover,mx.Widget,mx.API],AP={ignoreConditions:!1,ignoreDelay:!1,displayType:FA.Popover};class RP{constructor(t){this._instance=t,this.Ui=new Map,this.zi=new Map}register(t){var n;Ue((n=this._instance)==null?void 0:n.Mi)||(this.Hi(t),this.Bi(t))}Bi(t){var n=t.filter((r=>{var s,i;return((s=r.conditions)==null?void 0:s.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0}));n.length!==0&&(this.qi==null&&(this.qi=new fl(this._instance),this.qi.init(),this.qi.Di((r=>{this.onAction(r)}))),n.forEach((r=>{var s,i,o,u,f;r.conditions&&(s=r.conditions)!=null&&s.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((u=this.qi)==null||u.register(r.conditions.actions.values),(f=r.conditions)==null||(f=f.actions)==null||(f=f.values)==null||f.forEach((h=>{if(h&&h.name){var p=this.zi.get(h.name);p&&p.push(r.id),this.zi.set(h.name,p||[r.id])}})))})))}Hi(t){var n;t.filter((r=>{var s,i;return((s=r.conditions)==null?void 0:s.events)&&((i=r.conditions)==null||(i=i.events)==null||(i=i.values)==null?void 0:i.length)>0})).length!==0&&((n=this._instance)==null||n.Mi(((r,s)=>{this.onEvent(r,s)})),t.forEach((r=>{var s;(s=r.conditions)==null||(s=s.events)==null||(s=s.values)==null||s.forEach((i=>{if(i&&i.name){var o=this.Ui.get(i.name);o&&o.push(r.id),this.Ui.set(i.name,o||[r.id])}}))})))}onEvent(t,n){var r,s,i=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[xm])||[];if(tp.SHOWN===t&&n&&i.length>0){var o;yn.info("survey event matched, removing survey from activated surveys",{event:t,eventPayload:n,existingActivatedSurveys:i});var u=n==null||(o=n.properties)==null?void 0:o.$survey_id;if(u){var f=i.indexOf(u);f>=0&&(i.splice(f,1),this.Wi(i))}}else if(this.Ui.has(t)){yn.info("survey event name matched",{event:t,eventPayload:n,surveys:this.Ui.get(t)});var h=[];(s=this._instance)==null||s.getSurveys((g=>{h=g.filter((v=>{var y;return(y=this.Ui.get(t))==null?void 0:y.includes(v.id)}))}));var p=h.filter((g=>{var v,y=(v=g.conditions)==null||(v=v.events)==null||(v=v.values)==null?void 0:v.find((S=>S.name===t));return!!y&&(!y.propertyFilters||Object.entries(y.propertyFilters).every((S=>{var w,[N,k]=S,j=n==null||(w=n.properties)==null?void 0:w[N];if(Ue(j)||ja(j))return!1;var E=[String(j)],C=$A[k.operator];return C?C(k.values,E):(yn.warn("Unknown property comparison operator: "+k.operator),!1)})))}));this.Wi(i.concat(p.map((g=>g.id))||[]))}}onAction(t){var n,r=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[xm])||[];this.zi.has(t)&&this.Wi(r.concat(this.zi.get(t)||[]))}Wi(t){var n;yn.info("updating activated surveys",{activatedSurveys:t}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[xm]:[...new Set(t)]})}getSurveys(){var t,n=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[xm];return n||[]}getEventToSurveys(){return this.Ui}Gi(){return this.qi}}class MP{constructor(t){this.Vi=void 0,this._surveyManager=null,this.Ji=!1,this.Ki=!1,this.Yi=[],this._instance=t,this._surveyEventReceiver=null}onRemoteConfig(t){if(!this._instance.config.disable_surveys){var n=t.surveys;if(An(n))return yn.warn("Flags not loaded yet. Not loading surveys.");var r=Rn(n);this.Vi=r?n.length>0:n,yn.info("flags response received, isSurveysEnabled: "+this.Vi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var t=[],n=0;n<localStorage.length;n++){var r=localStorage.key(n);(r!=null&&r.startsWith(Bb)||r!=null&&r.startsWith("inProgressSurvey_"))&&t.push(r)}t.forEach((s=>localStorage.removeItem(s)))}loadIfEnabled(){if(!this._surveyManager)if(this.Ki)yn.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)yn.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())yn.info("Not loading surveys in cookieless mode without consent.");else{var t=wt?.__PosthogExtensions__;if(t){if(!Ue(this.Vi)||this._instance.config.advanced_enable_surveys){var n=this.Vi||this._instance.config.advanced_enable_surveys;this.Ki=!0;try{var r=t.generateSurveys;if(r)return void this.Xi(r,n);var s=t.loadExternalDependency;if(!s)return void this.Qi("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",(i=>{i||!t.generateSurveys?this.Qi("Could not load surveys script",i):this.Xi(t.generateSurveys,n)}))}catch(i){throw this.Qi("Error initializing surveys",i),i}finally{this.Ki=!1}}}else yn.error("PostHog Extensions not found.")}}Xi(t,n){this._surveyManager=t(this._instance,n),this._surveyEventReceiver=new RP(this._instance),yn.info("Surveys loaded successfully"),this.Zi({isLoaded:!0})}Qi(t,n){yn.error(t,n),this.Zi({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Yi.push(t),this._surveyManager&&this.Zi({isLoaded:!0}),()=>{this.Yi=this.Yi.filter((n=>n!==t))}}getSurveys(t,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return yn.info("Disabled. Not loading surveys."),t([]);var r=this._instance.get_property(Tb);if(r&&!n)return t(r,{isLoaded:!0});if(this.Ji)return t([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.Ji=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var i;this.Ji=!1;var o=s.statusCode;if(o!==200||!s.json){var u="Surveys API could not be loaded, status: "+o;return yn.error(u),t([],{isLoaded:!1,error:u})}var f,h=s.json.surveys||[],p=h.filter((g=>(function(v){return!(!v.start_date||v.end_date)})(g)&&((function(v){var y;return!((y=v.conditions)==null||(y=y.events)==null||(y=y.values)==null||!y.length)})(g)||(function(v){var y;return!((y=v.conditions)==null||(y=y.actions)==null||(y=y.values)==null||!y.length)})(g))));return p.length>0&&((f=this._surveyEventReceiver)==null||f.register(p)),(i=this._instance.persistence)==null||i.register({[Tb]:h}),t(h,{isLoaded:!0})}})}catch(s){throw this.Ji=!1,s}}Zi(t){for(var n of this.Yi)try{if(!t.isLoaded)return n([],t);this.getSurveys(n)}catch(r){yn.error("Error in survey callback",r)}}getActiveMatchingSurveys(t,n){if(n===void 0&&(n=!1),!An(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,n);yn.warn("init was not called")}te(t){var n=null;return this.getSurveys((r=>{var s;n=(s=r.find((i=>i.id===t)))!==null&&s!==void 0?s:null})),n}ie(t){if(An(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof t=="string"?this.te(t):t;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(An(this._surveyManager))return yn.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.ie(t);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(t,n){return An(this._surveyManager)?(yn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((s=>{var i,o=(i=s.find((f=>f.id===t)))!==null&&i!==void 0?i:null;if(o){var u=this.ie(o);r({visible:u.eligible,disabledReason:u.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),n)}))}renderSurvey(t,n){var r;if(An(this._surveyManager))yn.warn("init was not called");else{var s=typeof t=="string"?this.te(t):t;if(s!=null&&s.id)if(TP.includes(s.type)){var i=qe?.querySelector(n);if(i)return(r=s.appearance)!=null&&r.surveyPopupDelaySeconds?(yn.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,u;yn.info("Rendering survey "+s.id+" with delay of "+((o=s.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(u=this._surveyManager)==null||u.renderSurvey(s,i),yn.info("Survey "+s.id+" rendered")}),1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,i);yn.warn("Survey element not found")}else yn.warn("Surveys of type "+s.type+" cannot be rendered in the app");else yn.warn("Survey not found")}}displaySurvey(t,n){var r;if(An(this._surveyManager))yn.warn("init was not called");else{var s=this.te(t);if(s){var i=s;if((r=s.appearance)!=null&&r.surveyPopupDelaySeconds&&n.ignoreDelay&&(i=We({},s,{appearance:We({},s.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var o=this.canRenderSurvey(s);if(!o.visible)return void yn.warn("Survey is not eligible to be displayed: ",o.disabledReason)}n.displayType!==FA.Inline?this._surveyManager.handlePopoverSurvey(i):this.renderSurvey(i,n.selector)}else yn.warn("Survey not found")}}}var bE=kr("[RateLimiter]");class OP{constructor(t){var n,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var i=s.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach((o=>{bE.info((o||"events")+" is quota limited."),this.serverLimits[o]=new Date().getTime()+6e4}))}catch(o){return void bE.warn('could not rate limit - continuing. Error: "'+o?.message+'"',{text:i})}},this.instance=t,this.captureEventsPerSecond=((n=t.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=t.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(t){var n,r,s;t===void 0&&(t=!1);var i=new Date().getTime(),o=(n=(r=this.instance.persistence)==null?void 0:r.get_property(Rb))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:i};o.tokens+=(i-o.last)/1e3*this.captureEventsPerSecond,o.last=i,o.tokens>this.captureEventsBurstLimit&&(o.tokens=this.captureEventsBurstLimit);var u=o.tokens<1;return u||t||(o.tokens=Math.max(0,o.tokens-1)),!u||this.lastEventRateLimited||t||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(s=this.instance.persistence)==null||s.set_property(Rb,o),{isRateLimited:u,remainingTokens:o.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var sl=kr("[RemoteConfig]");class IP{constructor(t){this._instance=t}get remoteConfig(){var t;return(t=wt._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.config}ee(t){var n,r;(n=wt.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>t(this.remoteConfig))):(sl.error("PostHog Extensions not found. Cannot load remote config."),t())}re(t){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{t(n.json)}})}load(){try{if(this.remoteConfig)return sl.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.M())return void sl.warn("Remote config is disabled. Falling back to local config.");this.ee((t=>{if(!t)return sl.info("No config found after loading remote JS config. Falling back to JSON."),void this.re((n=>{this.fi(n)}));this.fi(t)}))}catch(t){sl.error("Error loading remote config",t)}}fi(t){t?this._instance.config.__preview_remote_config?(this._instance.fi(t),t.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):sl.info("__preview_remote_config is disabled. Logging config instead",t):sl.error("Failed to fetch remote config from PostHog.")}}var qb=3e3;class LP{constructor(t,n){this.se=!0,this.ne=[],this.oe=Ri(n?.flush_interval_ms||qb,250,5e3,Ge.createLogger("flush interval"),qb),this.ae=t}enqueue(t){this.ne.push(t),this.le||this.ue()}unload(){this.he();var t=this.ne.length>0?this.de():{},n=Object.values(t);[...n.filter((r=>r.url.indexOf("/e")===0)),...n.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.ae(We({},r,{transport:"sendBeacon"}))}))}enable(){this.se=!1,this.ue()}ue(){var t=this;this.se||(this.le=setTimeout((()=>{if(this.he(),this.ne.length>0){var n=this.de(),r=function(){var i=n[s],o=new Date().getTime();i.data&&Rn(i.data)&&Cn(i.data,(u=>{u.offset=Math.abs(u.timestamp-o),delete u.timestamp})),t.ae(i)};for(var s in n)r()}}),this.oe))}he(){clearTimeout(this.le),this.le=void 0}de(){var t={};return Cn(this.ne,(n=>{var r,s=n,i=(s?s.batchKey:null)||s.url;Ue(t[i])&&(t[i]=We({},s,{data:[]})),(r=t[i].data)==null||r.push(s.data)})),this.ne=[],t}}var DP=["retriesPerformedSoFar"];class PP{constructor(t){this.ve=!1,this.ce=3e3,this.ne=[],this._instance=t,this.ne=[],this.fe=!0,!Ue(me)&&"onLine"in me.navigator&&(this.fe=me.navigator.onLine,this.pe=()=>{this.fe=!0,this.Dt()},this.ge=()=>{this.fe=!1},dr(me,"online",this.pe),dr(me,"offline",this.ge))}get length(){return this.ne.length}retriableRequest(t){var{retriesPerformedSoFar:n}=t,r=DT(t,DP);Fi(n)&&n>0&&(r.url=Np(r.url,{retry_count:n})),this._instance.ci(We({},r,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(n??0)<10?this._e(We({retriesPerformedSoFar:n},r)):r.callback==null||r.callback(s)}}))}_e(t){var n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;var r=(function(o){var u=3e3*Math.pow(2,o),f=u/2,h=Math.min(18e5,u),p=(Math.random()-.5)*(h-f);return Math.ceil(h+p)})(n),s=Date.now()+r;this.ne.push({retryAt:s,requestOptions:t});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),Ge.warn(i),this.ve||(this.ve=!0,this.me())}me(){if(this.ye&&clearTimeout(this.ye),this.ne.length===0)return this.ve=!1,void(this.ye=void 0);this.ye=setTimeout((()=>{this.fe&&this.ne.length>0&&this.Dt(),this.me()}),this.ce)}Dt(){var t=Date.now(),n=[],r=this.ne.filter((i=>i.retryAt<t||(n.push(i),!1)));if(this.ne=n,r.length>0)for(var{requestOptions:s}of r)this.retriableRequest(s)}unload(){for(var{requestOptions:t}of(this.ye&&(clearTimeout(this.ye),this.ye=void 0),this.ve=!1,Ue(me)||(this.pe&&(me.removeEventListener("online",this.pe),this.pe=void 0),this.ge&&(me.removeEventListener("offline",this.ge),this.ge=void 0)),this.ne))try{this._instance.ci(We({},t,{transport:"sendBeacon"}))}catch(n){Ge.error(n)}this.ne=[]}}class zP{constructor(t){this.be=()=>{var n,r,s,i;this.we||(this.we={});var o=this.scrollElement(),u=this.scrollY(),f=o?Math.max(0,o.scrollHeight-o.clientHeight):0,h=u+(o?.clientHeight||0),p=o?.scrollHeight||0;this.we.lastScrollY=Math.ceil(u),this.we.maxScrollY=Math.max(u,(n=this.we.maxScrollY)!==null&&n!==void 0?n:0),this.we.maxScrollHeight=Math.max(f,(r=this.we.maxScrollHeight)!==null&&r!==void 0?r:0),this.we.lastContentY=h,this.we.maxContentY=Math.max(h,(s=this.we.maxContentY)!==null&&s!==void 0?s:0),this.we.maxContentHeight=Math.max(p,(i=this.we.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=t}getContext(){return this.we}resetContext(){var t=this.we;return setTimeout(this.be,0),t}startMeasuringScrollPosition(){dr(me,"scroll",this.be,{capture:!0}),dr(me,"scrollend",this.be,{capture:!0}),dr(me,"resize",this.be)}scrollElement(){if(!this._instance.config.scroll_root_selector)return me?.document.documentElement;var t=Rn(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of t){var r=me?.document.querySelector(n);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var t=this.scrollElement();return t&&t.scrollTop||0}return me&&(me.scrollY||me.pageYOffset||me.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var t=this.scrollElement();return t&&t.scrollLeft||0}return me&&(me.scrollX||me.pageXOffset||me.document.documentElement.scrollLeft)||0}}var $P=e=>RA(e?.config.mask_personal_data_properties,e?.config.custom_personal_data_properties);class wE{constructor(t,n,r,s){this.xe=i=>{var o=this.Se();if(!o||o.sessionId!==i){var u={sessionId:i,props:this.Ee(this._instance)};this.$e.register({[Ab]:u})}},this._instance=t,this.ke=n,this.$e=r,this.Ee=s||$P,this.ke.onSessionId(this.xe)}Se(){return this.$e.props[Ab]}getSetOnceProps(){var t,n=(t=this.Se())==null?void 0:t.props;return n?"r"in n?MA(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var t={};return Cn(iw(this.getSetOnceProps()),((n,r)=>{r==="$current_url"&&(r="url"),t["$session_entry_"+_b(r)]=n})),t}}var px=kr("[SessionId]");class _E{on(t,n){return this.Pe.on(t,n)}constructor(t,n,r){var s;if(this.Te=[],this.Re=void 0,this.Pe=new pw,this.Ie=(p,g)=>Math.abs(p-g)>this.sessionTimeoutMs,!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.C=t.config,this.$e=t.persistence,this.Ce=void 0,this.Oe=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Fe=n||mo,this.Me=r||mo;var i=this.C.persistence_name||this.C.token,o=this.C.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Ri(o,60,36e3,px.createLogger("session_idle_timeout_seconds"),1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Ae(),this.De="ph_"+i+"_window_id",this.je="ph_"+i+"_primary_window_exists",this.Le()){var u=Ar.W(this.De),f=Ar.W(this.je);u&&!f?this.Ce=u:Ar.V(this.De),Ar.G(this.je,!0)}if((s=this.C.bootstrap)!=null&&s.sessionID)try{var h=(p=>{var g=p.replace(/-/g,"");if(g.length!==32)throw new Error("Not a valid UUID");if(g[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(g.substring(0,12),16)})(this.C.bootstrap.sessionID);this.Ne(this.C.bootstrap.sessionID,new Date().getTime(),h)}catch(p){px.error("Invalid sessionID in bootstrap",p)}this.Ue()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return Ue(this.Te)&&(this.Te=[]),this.Te.push(t),this.Oe&&t(this.Oe,this.Ce),()=>{this.Te=this.Te.filter((n=>n!==t))}}Le(){return this.C.persistence!=="memory"&&!this.$e.wi&&Ar.H()}ze(t){t!==this.Ce&&(this.Ce=t,this.Le()&&Ar.G(this.De,t))}He(){return this.Ce?this.Ce:this.Le()?Ar.W(this.De):null}Ne(t,n,r){t===this.Oe&&n===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.Oe=t,this.$e.register({[pp]:[n,t,r]}))}Be(){if(this.Oe&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this.Oe,this._sessionStartTimestamp];var t=this.$e.props[pp];return Rn(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this.Ne(null,null,null)}destroy(){clearTimeout(this.qe),this.qe=void 0,this.Re&&me&&(me.removeEventListener("beforeunload",this.Re,{capture:!1}),this.Re=void 0),this.Te=[]}Ue(){this.Re=()=>{this.Le()&&Ar.V(this.je)},dr(me,"beforeunload",this.Re,{capture:!1})}checkAndGetSessionAndWindowId(t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),this.C.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[s,i,o]=this.Be(),u=this.He(),f=Fi(o)&&o>0&&Math.abs(r-o)>864e5,h=!1,p=!i,g=!t&&this.Ie(r,s);p||g||f?(i=this.Fe(),u=this.Me(),px.info("new session ID generated",{sessionId:i,windowId:u,changeReason:{noSessionId:p,activityTimeout:g,sessionPastMaximumLength:f}}),o=r,h=!0):u||(u=this.Me(),h=!0);var v=s===0||!t||f?r:s,y=o===0?new Date().getTime():o;return this.ze(u),this.Ne(i,v,y),t||this.Ae(),h&&this.Te.forEach((S=>S(i,u,h?{noSessionId:p,activityTimeout:g,sessionPastMaximumLength:f}:void 0))),{sessionId:i,windowId:u,sessionStartTimestamp:y,changeReason:h?{noSessionId:p,activityTimeout:g,sessionPastMaximumLength:f}:void 0,lastActivityTimestamp:s}}Ae(){clearTimeout(this.qe),this.qe=setTimeout((()=>{var[t]=this.Be();if(this.Ie(new Date().getTime(),t)){var n=this.Oe;this.resetSessionId(),this.Pe.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}}var FP=["$set_once","$set"],no=kr("[SiteApps]");class UP{constructor(t){this._instance=t,this.We=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Ge(t,n){if(n){var r=this.globalsForEvent(n);this.We.push(r),this.We.length>1e3&&(this.We=this.We.slice(10))}}get siteAppLoaders(){var t;return(t=wt._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}init(){if(this.isEnabled){var t=this._instance.Mi(this.Ge.bind(this));this.Ve=()=>{t(),this.We=[],this.Ve=void 0}}}globalsForEvent(t){var n,r,s,i,o,u,f;if(!t)throw new Error("Event payload is required");var h={},p=this._instance.get_property("$groups")||[],g=this._instance.get_property("$stored_group_properties")||{};for(var[v,y]of Object.entries(g))h[v]={id:p[v],type:v,properties:y};var{$set_once:S,$set:w}=t;return{event:We({},DT(t,FP),{properties:We({},t.properties,w?{$set:We({},(n=(r=t.properties)==null?void 0:r.$set)!==null&&n!==void 0?n:{},w)}:{},S?{$set_once:We({},(s=(i=t.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},S)}:{}),elements_chain:(o=(u=t.properties)==null?void 0:u.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(f=t.properties)==null?void 0:f.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:h}}setupSiteApp(t){var n=this.apps[t.id],r=()=>{var u;!n.errored&&this.We.length&&(no.info("Processing "+this.We.length+" events for site app with id "+t.id),this.We.forEach((f=>n.processEvent==null?void 0:n.processEvent(f))),n.processedBuffer=!0),Object.values(this.apps).every((f=>f.processedBuffer||f.errored))&&((u=this.Ve)==null||u.call(this))},s=!1,i=u=>{n.errored=!u,n.loaded=!0,no.info("Site app with id "+t.id+" "+(u?"loaded":"errored")),s&&r()};try{var{processEvent:o}=t.init({posthog:this._instance,callback:u=>{i(u)}});o&&(n.processEvent=o),s=!0}catch(u){no.error("Error while initializing PostHog app with config id "+t.id,u),i(!1)}if(s&&n.loaded)try{r()}catch(u){no.error("Error while processing buffered events PostHog app with config id "+t.id,u),n.errored=!0}}Je(){var t=this.siteAppLoaders||[];for(var n of t)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of t)this.setupSiteApp(r)}Ke(t){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(t);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(n)}catch(s){no.error("Error while processing event "+t.event+" for site app "+r.id,s)}}}onRemoteConfig(t){var n,r,s,i=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.Je(),void this._instance.on("eventCaptured",(h=>this.Ke(h)))):void no.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.Ve)==null||r.call(this),(s=t.siteApps)!=null&&s.length)if(this.isEnabled){var o=function(h){var p;wt["__$$ph_site_app_"+h]=i._instance,(p=wt.__PosthogExtensions__)==null||p.loadSiteApp==null||p.loadSiteApp(i._instance,f,(g=>{if(g)return no.error("Error while initializing PostHog app with config id "+h,g)}))};for(var{id:u,url:f}of t.siteApps)o(u)}else no.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var BP=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],SE=function(e,t){if(!e)return!1;var n=e.toLowerCase();return BP.concat(t||[]).some((r=>{var s=r.toLowerCase();return n.indexOf(s)!==-1}))},UA=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&SE(n,t))return!0;try{var r=e?.userAgentData;if(r!=null&&r.brands&&r.brands.some((s=>SE(s?.brand,t))))return!0}catch{}return!!e.webdriver},rf=(function(e){return e.US="us",e.EU="eu",e.CUSTOM="custom",e})({}),kE="i.posthog.com";class qP{constructor(t){this.Ye={},this.instance=t}get apiHost(){var t=this.instance.config.api_host.trim().replace(/\/$/,"");return t==="https://app.posthog.com"?"https://us.i.posthog.com":t}get uiHost(){var t,n=(t=this.instance.config.ui_host)==null?void 0:t.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+kE,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.Ye[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=rf.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=rf.EU:this.Ye[this.apiHost]=rf.CUSTOM),this.Ye[this.apiHost]}endpointFor(t,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),t==="ui")return this.uiHost+n;if(this.region===rf.CUSTOM)return this.apiHost+n;var r=kE+n;switch(t){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var HP={icontains:(e,t)=>!!me&&t.href.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>!!me&&t.href.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>!!me&&au(t.href,e),not_regex:(e,t)=>!!me&&!au(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class zr{constructor(t){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments((s=>{zr.Xe("retrieved web experiments from the server"),n.Qe=new Map,s.forEach((i=>{if(i.feature_flag_key){var o;n.Qe&&(zr.Xe("setting flag key ",i.feature_flag_key," to web experiment ",i),(o=n.Qe)==null||o.set(i.feature_flag_key,i));var u=n._instance.getFeatureFlag(i.feature_flag_key);yr(u)&&i.variants[u]&&n.Ze(i.name,u,i.variants[u].transforms)}else if(i.variants)for(var f in i.variants){var h=i.variants[f];zr.tr(h)&&n.Ze(i.name,f,h.transforms)}}))}),r)},this._instance=t,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(t){if(this._is_bot())zr.Xe("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(An(this.Qe))return this.Qe=new Map,this.loadIfEnabled(),void this.previewWebExperiment();zr.Xe("applying feature flags",t),t.forEach((n=>{var r;if(this.Qe&&(r=this.Qe)!=null&&r.has(n)){var s,i=this._instance.getFeatureFlag(n),o=(s=this.Qe)==null?void 0:s.get(n);i&&o!=null&&o.variants[i]&&this.Ze(o.name,i,o.variants[i].transforms)}}))}}previewWebExperiment(){var t=zr.getWindowLocation();if(t!=null&&t.search){var n=wp(t?.search,"__experiment_id"),r=wp(t?.search,"__experiment_variant");n&&r&&(zr.Xe("previewing web experiments "+n+" && "+r),this.getWebExperiments((s=>{this.ir(parseInt(n),r,s)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,n,r){if(this._instance.config.disable_web_experiments&&!r)return t([]);var s=this._instance.get_property("$web_experiments");if(s&&!n)return t(s);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return t([]);var o=i.json.experiments||[];return t(o)}})}ir(t,n,r){var s=r.filter((i=>i.id===t));s&&s.length>0&&(zr.Xe("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.Ze(s[0].name,n,s[0].variants[n].transforms))}static tr(t){return!An(t.conditions)&&zr.er(t)&&zr.rr(t)}static er(t){var n;if(An(t.conditions)||An((n=t.conditions)==null?void 0:n.url))return!0;var r,s,i,o=zr.getWindowLocation();return!!o&&((r=t.conditions)==null||!r.url||HP[(s=(i=t.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](t.conditions.url,o))}static getWindowLocation(){return me?.location}static rr(t){var n;if(An(t.conditions)||An((n=t.conditions)==null?void 0:n.utm))return!0;var r=jA();if(r.utm_source){var s,i,o,u,f,h,p,g,v=(s=t.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=t.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,y=(o=t.conditions)==null||(o=o.utm)==null||!o.utm_source||((u=t.conditions)==null||(u=u.utm)==null?void 0:u.utm_source)==r.utm_source,S=(f=t.conditions)==null||(f=f.utm)==null||!f.utm_medium||((h=t.conditions)==null||(h=h.utm)==null?void 0:h.utm_medium)==r.utm_medium,w=(p=t.conditions)==null||(p=p.utm)==null||!p.utm_term||((g=t.conditions)==null||(g=g.utm)==null?void 0:g.utm_term)==r.utm_term;return v&&S&&w&&y}return!1}static Xe(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];Ge.info("[WebExperiments] "+t,r)}Ze(t,n,r){this._is_bot()?zr.Xe("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?r.forEach((s=>{if(s.selector){var i;zr.Xe("applying transform of variant "+n+" for experiment "+t+" ",s);var o=(i=document)==null?void 0:i.querySelectorAll(s.selector);o?.forEach((u=>{var f=u;s.html&&(f.innerHTML=s.html),s.css&&f.setAttribute("style",s.css)}))}})):zr.Xe("Control variants leave the page unmodified.")}_is_bot(){return Ls&&this._instance?UA(Ls,this._instance.config.custom_blocked_useragents):void 0}}var VP=kr("[PostHog ExternalIntegrations]"),KP={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class GP{constructor(t){this._instance=t}it(t,n){var r;(r=wt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,t,(s=>{if(s)return VP.error("failed to load script",s);n()}))}startIfEnabledOrStop(){var t=this,n=function(o){var u,f,h;!s||(u=wt.__PosthogExtensions__)!=null&&(u=u.integrations)!=null&&u[o]||t.it(KP[o],(()=>{var p;(p=wt.__PosthogExtensions__)==null||(p=p.integrations)==null||(p=p[o])==null||p.start(t._instance)})),!s&&(f=wt.__PosthogExtensions__)!=null&&(f=f.integrations)!=null&&f[o]&&((h=wt.__PosthogExtensions__)==null||(h=h.integrations)==null||(h=h[o])==null||h.stop())};for(var[r,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;n(r)}}}var Hb="[SessionRecording]",$d=kr(Hb);class NE{get started(){var t;return!((t=this.sr)==null||!t.isStarted)}get status(){return this.sr?this.sr.status:this.nr&&!this.ar?"disabled":"lazy_loading"}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.nr=!1,this.lr=void 0,this._instance=t,!this._instance.sessionManager)throw $d.error("started without valid sessionManager"),new Error(Hb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Hb+' cannot be used with cookieless_mode="always"')}get ar(){var t,n=!((t=this._instance.get_property(nx))==null||!t.enabled),r=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return me&&n&&r&&!s}startIfEnabledOrStop(t){var n;if(!this.ar||(n=this.sr)==null||!n.isStarted){var r=!Ue(Object.assign)&&!Ue(Array.from);this.ar&&r?(this.ur(t),$d.info("starting")):this.stopRecording()}}ur(t){var n,r,s;this.ar&&(wt!=null&&(n=wt.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(r=wt.__PosthogExtensions__)!=null&&r.initSessionRecording?this.hr(t):(s=wt.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.dr,(i=>{if(i)return $d.error("could not load recorder",i);this.hr(t)})))}stopRecording(){var t,n;(t=this.lr)==null||t.call(this),this.lr=void 0,(n=this.sr)==null||n.stop()}vr(){var t;(t=this._instance.persistence)==null||t.unregister(KT)}cr(t){if(this._instance.persistence){var n,r,s=this._instance.persistence,i=()=>{var o=t.sessionRecording===!1?void 0:t.sessionRecording,u=o?.sampleRate,f=An(u)?null:parseFloat(u);An(f)&&this.vr();var h=o?.minimumDurationMilliseconds;s.register({[nx]:We({enabled:!!o},o,{networkPayloadCapture:We({capturePerformance:t.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:f,minimumDurationMilliseconds:Ue(h)?null:h,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};i(),(n=this.lr)==null||n.call(this),this.lr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(i)}}onRemoteConfig(t){"sessionRecording"in t?t.sessionRecording!==!1?(this.cr(t),this.nr=!0,this.startIfEnabledOrStop()):this.nr=!0:$d.info("skipping remote config with no sessionRecording",t)}log(t,n){var r;n===void 0&&(n="log"),(r=this.sr)!=null&&r.log?this.sr.log(t,n):$d.warn("log called before recorder was ready")}get dr(){var t,n,r=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(nx);return(r==null||(n=r.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}hr(t){var n,r;if((n=wt.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.sr||(this.sr=(r=wt.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.sr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.sr.start(t)}onRRwebEmit(t){var n;(n=this.sr)==null||n.onRRwebEmit==null||n.onRRwebEmit(t)}overrideLinkedFlag(){var t;(t=this.sr)==null||t.overrideLinkedFlag()}overrideSampling(){var t;(t=this.sr)==null||t.overrideSampling()}overrideTrigger(t){var n;(n=this.sr)==null||n.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.sr)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,n){var r;return!((r=this.sr)==null||!r.tryAddCustomEvent(t,n))}}var mf={},Vb=()=>{},Ac="posthog",BA=!_P&&ms?.indexOf("MSIE")===-1&&ms?.indexOf("Mozilla")===-1,EE=e=>{var t;return{api_host:"https://us.i.posthog.com",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:v5(qe?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:Vb,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:e!=="2025-05-24"||"history_change",capture_pageleave:"if_capture_pageview",defaults:e??"unset",debug:ps&&yr(ps?.search)&&ps.search.indexOf("__posthog_debug=true")!==-1||!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_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(me==null||(t=me.location)==null?void 0:t.protocol)==="https:",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,session_recording:{},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_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:n=>{var r="Bad HTTP status: "+n.statusCode+" "+n.text;Ge.error(r)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:qb},error_tracking:{},_onCapture:Vb,__preview_eager_load_replay:!1}},jE=e=>{var t={};Ue(e.process_person)||(t.person_profiles=e.process_person),Ue(e.xhr_headers)||(t.request_headers=e.xhr_headers),Ue(e.cookie_name)||(t.persistence_name=e.cookie_name),Ue(e.disable_cookie)||(t.disable_persistence=e.disable_cookie),Ue(e.store_google)||(t.save_campaign_params=e.store_google),Ue(e.verbose)||(t.debug=e.verbose);var n=Qn({},t,e);return Rn(e.property_blacklist)&&(Ue(e.property_denylist)?n.property_denylist=e.property_blacklist:Rn(e.property_denylist)?n.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ge.error("Invalid value for property_denylist config: "+e.property_denylist)),n};class YP{constructor(){this.__forceAllowLocalhost=!1}get pr(){return this.__forceAllowLocalhost}set pr(t){Ge.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class ag{get decideEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,n;return(t=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){this.webPerformance=new YP,this.gr=!1,this.version=fa.LIB_VERSION,this._r=new pw,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=EE(),this.SentryIntegration=V5,this.sentryIntegration=t=>(function(n,r){var s=uA(n,r);return{name:cA,processEvent:i=>s(i)}})(this,t),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.mr=!1,this.yr=null,this.br=null,this.wr=null,this.featureFlags=new EP(this),this.toolbar=new G5(this),this.scrollManager=new zP(this),this.pageViewManager=new hP(this),this.surveys=new MP(this),this.experiments=new zr(this),this.exceptions=new SP(this),this.rateLimiter=new OP(this),this.requestRouter=new qP(this),this.consent=new $5(this),this.externalIntegrations=new GP(this),this.people={set:(t,n,r)=>{var s=yr(t)?{[t]:n}:t;this.setPersonProperties(s),r?.({})},set_once:(t,n,r)=>{var s=yr(t)?{[t]:n}:t;this.setPersonProperties(void 0,s),r?.({})}},this.on("eventCaptured",(t=>Ge.info('send "'+t?.event+'"',t)))}init(t,n,r){if(r&&r!==Ac){var s,i=(s=mf[r])!==null&&s!==void 0?s:new ag;return i._init(t,n,r),mf[r]=i,mf[Ac][r]=i,i}return this._init(t,n,r)}_init(t,n,r){var s,i;if(n===void 0&&(n={}),Ue(t)||Sb(t))return Ge.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 console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},n.debug=this.Sr(n.debug),this.Er=n,this.$r=[],n.person_profiles&&(this.br=n.person_profiles),this.set_config(Qn({},EE(n.defaults),jE(n),{name:r,token:t})),this.config.on_xhr_error&&Ge.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:pa.GZipJS;var o=this.kr();this.persistence=new hx(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new hx(We({},this.config,{persistence:"sessionStorage"}),o);var u=We({},this.persistence.props),f=We({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Pr=new LP((E=>this.Tr(E)),this.config.request_queue_config),this.Rr=new PP(this),this.__request_queue=[];var h=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(h||(this.sessionManager=new _E(this),this.sessionPropsManager=new wE(this,this.sessionManager,this.persistence)),new W5(this).startIfEnabledOrStop(),this.siteApps=new UP(this),(s=this.siteApps)==null||s.init(),h||(this.sessionRecording=new NE(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new A5(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new fP(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new uP(this),this.exceptionObserver=new B5(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new lA(this,U5),this.deadClicksAutocapture.startIfEnabled(),this.historyAutocapture=new q5(this),this.historyAutocapture.startIfEnabled(),fa.DEBUG=fa.DEBUG||this.config.debug,fa.DEBUG&&Ge.info("Starting in debug mode",{this:this,config:n,thisC:We({},this.config),p:u,s:f}),((i=n.bootstrap)==null?void 0:i.distinctID)!==void 0){var p,g,v=this.config.get_device_id(mo()),y=(p=n.bootstrap)!=null&&p.isIdentifiedID?v:n.bootstrap.distinctID;this.persistence.set_property(ha,(g=n.bootstrap)!=null&&g.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:y})}if(this.Ir()){var S,w,N=Object.keys(((S=n.bootstrap)==null?void 0:S.featureFlags)||{}).filter((E=>{var C;return!((C=n.bootstrap)==null||(C=C.featureFlags)==null||!C[E])})).reduce(((E,C)=>{var M;return E[C]=((M=n.bootstrap)==null||(M=M.featureFlags)==null?void 0:M[C])||!1,E}),{}),k=Object.keys(((w=n.bootstrap)==null?void 0:w.featureFlagPayloads)||{}).filter((E=>N[E])).reduce(((E,C)=>{var M,A;return(M=n.bootstrap)!=null&&(M=M.featureFlagPayloads)!=null&&M[C]&&(E[C]=(A=n.bootstrap)==null||(A=A.featureFlagPayloads)==null?void 0:A[C]),E}),{});this.featureFlags.receivedFeatureFlags({featureFlags:N,featureFlagPayloads:k})}if(h)this.register_once({distinct_id:Od,$device_id:null},"");else if(!this.get_distinct_id()){var j=this.config.get_device_id(mo());this.register_once({distinct_id:j,$device_id:j},""),this.persistence.set_property(ha,"anonymous")}return dr(me,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?H5(this,(()=>this.Cr())):this.Cr(),po(this.config._onCapture)&&this.config._onCapture!==Vb&&(Ge.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(E=>this.config._onCapture(E.event,E)))),this.config.ip&&Ge.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}fi(t){var n,r,s,i,o,u,f,h;if(!qe||!qe.body)return Ge.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(t)}),500);this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=Bt(t.supportedCompression,pa.GZipJS)?pa.GZipJS:Bt(t.supportedCompression,pa.Base64)?pa.Base64:void 0),(n=t.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this.br?this.br:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(t),(s=this.sessionRecording)==null||s.onRemoteConfig(t),(i=this.autocapture)==null||i.onRemoteConfig(t),(o=this.heatmaps)==null||o.onRemoteConfig(t),this.surveys.onRemoteConfig(t),(u=this.webVitalsAutocapture)==null||u.onRemoteConfig(t),(f=this.exceptionObserver)==null||f.onRemoteConfig(t),this.exceptions.onRemoteConfig(t),(h=this.deadClicksAutocapture)==null||h.onRemoteConfig(t)}Cr(){try{this.config.loaded(this)}catch(t){Ge.critical("`loaded` function failed",t)}this.Or(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Fr()}),1),new IP(this).load(),this.featureFlags.flags()}Or(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.Pr)==null||t.enable())}_dom_loaded(){this.is_capturing()&&vo(this.__request_queue,(t=>this.Tr(t))),this.__request_queue=[],this.Or()}_handle_unload(){var t,n;this.config.request_batching?(this.Mr()&&this.capture("$pageleave"),(t=this.Pr)==null||t.unload(),(n=this.Rr)==null||n.unload()):this.Mr()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(t){this.__loaded&&(BA?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=Np(t.url,{ip:this.config.ip?1:0}),t.headers=We({},this.config.request_headers),t.compression=t.compression==="best-available"?this.compression:t.compression,t.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||this.config.fetch_options,(n=>{var r,s,i,o=We({},n);o.timeout=o.timeout||6e4,o.url=Np(o.url,{_:new Date().getTime().toString(),ver:fa.LIB_VERSION,compression:o.compression});var u=(r=o.transport)!==null&&r!==void 0?r:"fetch",f=ep.filter((p=>!o.disableTransport||!p.transport||!o.disableTransport.includes(p.transport))),h=(s=(i=qT(f,(p=>p.transport===u)))==null?void 0:i.method)!==null&&s!==void 0?s:f[0].method;if(!h)throw new Error("No available transport method");h(o)})(We({},t,{callback:n=>{var r,s;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((r=(s=this.config).on_request_error)==null||r.call(s,n)),t.callback==null||t.callback(n)}}))))}Tr(t){this.Rr?this.Rr.retriableRequest(t):this.ci(t)}_execute_array(t){var n,r=[],s=[],i=[];vo(t,(u=>{u&&(n=u[0],Rn(n)?i.push(u):po(u)?u.call(this):Rn(u)&&n==="alias"?r.push(u):Rn(u)&&n.indexOf("capture")!==-1&&po(this[n])?i.push(u):s.push(u))}));var o=function(u,f){vo(u,(function(h){if(Rn(h[0])){var p=f;Cn(h,(function(g){p=p[g[0]].apply(p,g.slice(1))}))}else this[h[0]].apply(this,h.slice(1))}),f)};o(r,this),o(s,this),o(i,this)}Ir(){var t,n;return((t=this.config.bootstrap)==null?void 0:t.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(t){this._execute_array([t])}capture(t,n,r){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Pr){if(this.is_capturing())if(!Ue(t)&&yr(t)){if(this.config.opt_out_useragent_filter||!this._is_bot()){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){n!=null&&n.$current_url&&!yr(n?.$current_url)&&(Ge.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&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 o=new Date,u=r?.timestamp||o,f=mo(),h={uuid:f,event:t,properties:this.calculateEventProperties(t,n||{},u,f)};i&&(h.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(h.$set=r?.$set);var p,g=this.Ar(r?.$set_once);if(g&&(h.$set_once=g),(h=p5(h,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=u,Ue(r?.timestamp)||(h.properties.$event_time_override_provided=!0,h.properties.$event_time_override_system_time=o),t===tp.DISMISSED||t===tp.SENT){var v=n?.[yE.SURVEY_ID],y=n?.[yE.SURVEY_ITERATION];p={id:v,current_iteration:y},localStorage.getItem(xE(p))||localStorage.setItem(xE(p),"true"),h.$set=We({},h.$set,{[CP({id:v,current_iteration:y},t===tp.SENT?"responded":"dismissed")]:!0})}var S=We({},h.properties.$set,h.$set);if(Pc(S)||this.setPersonPropertiesForFlags(S),!An(this.config.before_send)){var w=this.Dr(h);if(!w)return;h=w}this._r.emit("eventCaptured",h);var N={method:"POST",url:(s=r?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:h,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Tr(N):this.Pr.enqueue(N),h}Ge.critical("This capture call is ignored due to client rate limiting.")}}else Ge.error("No event name provided to posthog.capture")}else Ge.uninitializedWarning("posthog.capture")}Mi(t){return this.on("eventCaptured",(n=>t(n.event,n)))}calculateEventProperties(t,n,r,s,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=i?void 0:this.persistence.remove_event_timer(t),u=We({},n);if(u.token=this.config.token,u.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(u.$cookieless_mode=!0),t==="$snapshot"){var f=We({},this.persistence.properties(),this.sessionPersistence.properties());return u.distinct_id=f.distinct_id,(!yr(u.distinct_id)&&!Fi(u.distinct_id)||Sb(u.distinct_id))&&Ge.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),u}var h,p=cP(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:g,windowId:v}=this.sessionManager.checkAndGetSessionAndWindowId(i,r.getTime());u.$session_id=g,u.$window_id=v}this.sessionPropsManager&&Qn(u,this.sessionPropsManager.getSessionProps());try{var y;this.sessionRecording&&Qn(u,this.sessionRecording.sdkDebugProperties),u.$sdk_debug_retry_queue_size=(y=this.Rr)==null?void 0:y.length}catch(k){u.$sdk_debug_error_capturing_properties=String(k)}if(this.requestRouter.region===rf.CUSTOM&&(u.$lib_custom_api_host=this.config.api_host),h=t!=="$pageview"||i?t!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,s),u=Qn(u,h),t==="$pageview"&&qe&&(u.title=qe.title),!Ue(o)){var S=r.getTime()-o;u.$duration=parseFloat((S/1e3).toFixed(3))}ms&&this.config.opt_out_useragent_filter&&(u.$browser_type=this._is_bot()?"bot":"browser"),(u=Qn({},p,this.persistence.properties(),this.sessionPersistence.properties(),u)).$is_identified=this._isIdentified(),Rn(this.config.property_denylist)?Cn(this.config.property_denylist,(function(k){delete u[k]})):Ge.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var w=this.config.sanitize_properties;w&&(Ge.error("sanitize_properties is deprecated. Use before_send instead"),u=w(u,t));var N=this.jr();return u.$process_person_profile=N,N&&!i&&this.Lr("_calculate_event_properties"),u}Ar(t){var n;if(!this.persistence||!this.jr()||this.gr)return t;var r=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),i=Qn({},r,s||{},t||{}),o=this.config.sanitize_properties;return o&&(Ge.error("sanitize_properties is deprecated. Use before_send instead"),i=o(i,"$set_once")),this.gr=!0,Pc(i)?void 0:i}register(t,n){var r;(r=this.persistence)==null||r.register(t,n)}register_once(t,n,r){var s;(s=this.persistence)==null||s.register_once(t,n,r)}register_for_session(t){var n;(n=this.sessionPersistence)==null||n.register(t)}unregister(t){var n;(n=this.persistence)==null||n.unregister(t)}unregister_for_session(t){var n;(n=this.sessionPersistence)==null||n.unregister(t)}Nr(t,n){this.register({[t]:n})}getFeatureFlag(t,n){return this.featureFlags.getFeatureFlag(t,n)}getFeatureFlagPayload(t){var n=this.featureFlags.getFeatureFlagPayload(t);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(t,n){return this.featureFlags.isFeatureEnabled(t,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(t,n,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(t,n,r)}getEarlyAccessFeatures(t,n,r){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(t,n,r)}on(t,n){return this._r.on(t,n)}onFeatureFlags(t){return this.featureFlags.onFeatureFlags(t)}onSurveysLoaded(t){return this.surveys.onSurveysLoaded(t)}onSessionId(t){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(t))!==null&&n!==void 0?n:()=>{}}getSurveys(t,n){n===void 0&&(n=!1),this.surveys.getSurveys(t,n)}getActiveMatchingSurveys(t,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(t,n)}renderSurvey(t,n){this.surveys.renderSurvey(t,n)}displaySurvey(t,n){n===void 0&&(n=AP),this.surveys.displaySurvey(t,n)}canRenderSurvey(t){return this.surveys.canRenderSurvey(t)}canRenderSurveyAsync(t,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(t,n)}identify(t,n,r){if(!this.__loaded||!this.persistence)return Ge.uninitializedWarning("posthog.identify");if(Fi(t)&&(t=t.toString(),Ge.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),t)if(["distinct_id","distinctid"].includes(t.toLowerCase()))Ge.critical('The string "'+t+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(t!==Od){if(this.Lr("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:t}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}t!==s&&t!==this.get_property(Xd)&&(this.unregister(Xd),this.register({distinct_id:t}));var o=(this.persistence.get_property(ha)||"anonymous")==="anonymous";t!==s&&o?(this.persistence.set_property(ha,"identified"),this.setPersonPropertiesForFlags(We({},r||{},n||{}),!1),this.capture("$identify",{distinct_id:t,$anon_distinct_id:s},{$set:n||{},$set_once:r||{}}),this.wr=mE(t,n,r),this.featureFlags.setAnonymousDistinctId(s)):(n||r)&&this.setPersonProperties(n,r),t!==s&&(this.reloadFeatureFlags(),this.unregister(gp))}}else Ge.critical('The string "'+Od+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else Ge.error("Unique user id has not been set in posthog.identify")}setPersonProperties(t,n){if((t||n)&&this.Lr("posthog.setPersonProperties")){var r=mE(this.get_distinct_id(),t,n);this.wr!==r?(this.setPersonPropertiesForFlags(We({},n||{},t||{})),this.capture("$set",{$set:t||{},$set_once:n||{}}),this.wr=r):Ge.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(t,n,r){if(t&&n){if(this.Lr("posthog.group")){var s=this.getGroups();s[t]!==n&&this.resetGroupPropertiesForFlags(t),this.register({$groups:We({},s,{[t]:n})}),r&&(this.capture("$groupidentify",{$group_type:t,$group_key:n,$group_set:r}),this.setGroupPropertiesForFlags({[t]:r})),s[t]===n||r||this.reloadFeatureFlags()}}else Ge.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(t,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(t,n){n===void 0&&(n=!0),this.Lr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(t,n)}resetGroupPropertiesForFlags(t){this.featureFlags.resetGroupPropertiesForFlags(t)}reset(t){var n,r,s,i;if(Ge.info("reset"),!this.__loaded)return Ge.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(s=this.persistence)==null||s.set_property(ha,"anonymous"),(i=this.sessionManager)==null||i.resetSessionId(),this.wr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:Od,$device_id:null},"");else{var u=this.config.get_device_id(mo());this.register_once({distinct_id:u,$device_id:t?u:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,n;return(t=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(t!=null&&t.withTimestamp&&r){var i,o=(i=t.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return s}alias(t,n){return t===this.get_property(HT)?(Ge.critical("Attempting to create alias for existing People user - aborting."),-2):this.Lr("posthog.alias")?(Ue(n)&&(n=this.get_distinct_id()),t!==n?(this.Nr(Xd,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(Ge.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n=We({},this.config);if($r(t)){var r,s,i,o,u;Qn(this.config,jE(t));var f=this.kr();(r=this.persistence)==null||r.update_config(this.config,n,f),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new hx(We({},this.config,{persistence:"sessionStorage"}),f);var h=this.Sr(this.config.debug);go(h)&&(this.config.debug=h),go(this.config.debug)&&(this.config.debug?(fa.DEBUG=!0,qn.H()&&qn.G("ph_debug","true"),Ge.info("set_config",{config:t,oldConfig:n,newConfig:We({},this.config)})):(fa.DEBUG=!1,qn.H()&&qn.V("ph_debug"))),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),this.surveys.loadIfEnabled(),this.Ur(),(u=this.externalIntegrations)==null||u.startIfEnabledOrStop()}}startSessionRecording(t){var n=t===!0,r={sampling:n||!(t==null||!t.sampling),linked_flag:n||!(t==null||!t.linked_flag),url_trigger:n||!(t==null||!t.url_trigger),event_trigger:n||!(t==null||!t.event_trigger)};if(Object.values(r).some(Boolean)){var s,i,o,u,f;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),r.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),r.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),r.url_trigger&&((u=this.sessionRecording)==null||u.overrideTrigger("url")),r.event_trigger&&((f=this.sessionRecording)==null||f.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!((t=this.sessionRecording)==null||!t.started)}captureException(t,n){var r=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(t,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(We({},s,n))}loadToolbar(t){return this.toolbar.loadToolbar(t)}get_property(t){var n;return(n=this.persistence)==null?void 0:n.props[t]}getSessionProperty(t){var n;return(n=this.sessionPersistence)==null?void 0:n.props[t]}toString(){var t,n=(t=this.config.name)!==null&&t!==void 0?t:Ac;return n!==Ac&&(n=Ac+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)==null?void 0:t.get_property(ha))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(ha))==="identified"}jr(){var t,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Pc(this.getGroups())&&((t=this.persistence)==null||(t=t.props)==null||!t[Xd])&&((n=this.persistence)==null||(n=n.props)==null||!n[yp]))}Mr(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.jr()||this.Lr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Lr(t){return this.config.person_profiles==="never"?(Ge.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Nr(yp,!0),!0)}kr(){if(this.config.cookieless_mode==="always")return!0;var t=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||t&&!!n}Ur(){var t,n,r,s,i=this.kr();return((t=this.persistence)==null?void 0:t.wi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((n=this.sessionPersistence)==null?void 0:n.wi)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(t){if(this.config.cookieless_mode!=="always"){var n,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),this.sessionManager=new _E(this),this.persistence&&(this.sessionPropsManager=new wE(this,this.sessionManager,this.persistence)),this.sessionRecording=new NE(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Ur(),this.Or(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(Ue(t?.captureEventName)||t!=null&&t.captureEventName)&&this.capture((r=t?.captureEventName)!==null&&r!==void 0?r:"$opt_in",t?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Fr()}else Ge.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var t,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Ur(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:Od,$device_id:null}),(t=this.sessionManager)==null||t.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.Fr())):Ge.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var t=this.consent.consent;return t===ma.GRANTED?"granted":t===ma.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Ur()}_is_bot(){return Ls?UA(Ls,this.config.custom_blocked_useragents):void 0}Fr(){qe&&(qe.visibilityState==="visible"?this.mr||(this.mr=!0,this.capture("$pageview",{title:qe.title},{send_instantly:!0}),this.yr&&(qe.removeEventListener("visibilitychange",this.yr),this.yr=null)):this.yr||(this.yr=this.Fr.bind(this),dr(qe,"visibilitychange",this.yr)))}debug(t){t===!1?(me?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(me?.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}))}M(){var t,n,r,s,i,o,u,f=this.Er||{};return"advanced_disable_flags"in f?!!f.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ge.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):(r="advanced_disable_decide",s=!1,i=Ge,o=(n="advanced_disable_flags")in(t=f)&&!Ue(t[n]),u=r in t&&!Ue(t[r]),o?t[n]:u?(i&&i.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),t[r]):s)}Dr(t){if(An(this.config.before_send))return t;var n=Rn(this.config.before_send)?this.config.before_send:[this.config.before_send],r=t;for(var s of n){if(r=s(r),An(r)){var i="Event '"+t.event+"' was rejected in beforeSend function";return B3(t.event)?Ge.warn(i+". This can cause unexpected behavior."):Ge.info(i),null}r.properties&&!Pc(r.properties)||Ge.warn("Event '"+t.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var t;return(t=this.pageViewManager.Vt)==null?void 0:t.pageViewId}captureTraceFeedback(t,n){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:n})}captureTraceMetric(t,n,r){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:n,$ai_metric_value:String(r)})}Sr(t){var n=go(t)&&!t,r=qn.H()&&qn.q("ph_debug")==="true";return!n&&(!!r||t)}}(function(e,t){for(var n=0;n<t.length;n++)e.prototype[t[n]]=m5(e.prototype[t[n]])})(ag,["identify"]);var CE,np=(CE=mf[Ac]=new ag,(function(){function e(){e.done||(e.done=!0,BA=!1,Cn(mf,(function(t){t._dom_loaded()})))}qe!=null&&qe.addEventListener?qe.readyState==="complete"?e():dr(qe,"DOMContentLoaded",e,{capture:!1}):me&&Ge.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),CE);const qA=b.createContext(void 0);function HA(){return typeof window>"u"?null:window.__DEXTO_ANALYTICS__??null}function WP(){return typeof window>"u"?{app:"dexto-webui"}:{app:"dexto-webui",app_version:HA()?.appVersion??"unknown",browser:navigator.userAgent.split(" ").pop()?.split("/")[0],browser_version:navigator.userAgent.split(" ").pop()?.split("/")[1],os:navigator.platform,screen_width:window.screen.width,screen_height:window.screen.height}}function ZP({children:e}){const[t,n]=b.useState(!1),[r,s]=b.useState(!1);b.useEffect(()=>{const o=HA();if(!o){n(!1),s(!0);return}try{np.init(o.posthogKey,{api_host:o.posthogHost,person_profiles:"identified_only",loaded:u=>{u.identify(o.distinctId),n(!0),s(!0)},autocapture:!1,capture_pageview:!1,disable_session_recording:!0,disable_surveys:!0,opt_out_capturing_by_default:!1})}catch(u){console.error("Failed to initialize analytics:",u),n(!1),s(!0)}return()=>{try{np.reset()}catch{}}},[]);const i=(o,u)=>{if(!(!t||!r))try{np.capture(o,{...WP(),...u})}catch(f){console.error("Failed to capture analytics event:",f)}};return l.jsx(qA.Provider,{value:{capture:i,enabled:t,isReady:r},children:e})}function XP(){const e=b.useContext(qA);if(!e)throw new Error("useAnalyticsContext must be used within an AnalyticsProvider");return e}function bu(){const{capture:e,enabled:t,isReady:n}=XP(),r=b.useRef({}),s=b.useCallback(N=>{if(t)try{const k=N.sessionId;r.current[k]=(r.current[k]||0)+1,e("dexto_message_sent",{source:"webui",...N,messageCount:r.current[k]})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),i=b.useCallback(N=>{if(t)try{e("dexto_session_created",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),o=b.useCallback(N=>{if(t)try{e("dexto_session_switched",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),u=b.useCallback(N=>{if(t)try{r.current[N.sessionId]=0,e("dexto_session_reset",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),f=b.useCallback(N=>{if(t)try{e("dexto_agent_switched",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),h=b.useCallback(N=>{if(t)try{e("dexto_tool_called",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),p=b.useCallback(N=>{if(t)try{e("dexto_tool_result",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),g=b.useCallback(N=>{if(t)try{e("dexto_llm_switched",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),v=b.useCallback(N=>{if(t)try{e("dexto_file_attached",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),y=b.useCallback(N=>{if(t)try{e("dexto_image_attached",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),S=b.useCallback(N=>{if(t)try{e("dexto_mcp_server_connected",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]),w=b.useCallback(N=>{if(t)try{e("dexto_file_rejected",{source:"webui",...N})}catch(k){console.warn("Analytics tracking failed:",k)}},[e,t]);return{capture:e,enabled:t,isReady:n,trackMessageSent:s,trackSessionCreated:i,trackSessionSwitched:o,trackSessionReset:u,trackAgentSwitched:f,trackToolCalled:h,trackToolResult:p,trackLLMSwitched:g,trackFileAttached:v,trackImageAttached:y,trackMCPServerConnected:S,trackFileRejected:w}}function QP(){return typeof window>"u"?!1:!!window.__DEXTO_ANALYTICS__}function JP(){return typeof window>"u"?{app:"dexto-webui"}:{app:"dexto-webui",app_version:window.__DEXTO_ANALYTICS__?.appVersion??"unknown"}}function TE(e){if(QP())try{np.capture("dexto_llm_tokens_consumed",{...JP(),source:"webui",...e})}catch{}}const AE=1e3;class ez{constructor(){this.middlewares=[],this.handlers=new Map,this.history=[],this._isReplaying=!1}use(t){return this.middlewares.includes(t)||this.middlewares.push(t),this}removeMiddleware(t){const n=this.middlewares.indexOf(t);return n!==-1&&this.middlewares.splice(n,1),this}on(t,n){let r=this.handlers.get(t);return r||(r=new Set,this.handlers.set(t,r)),r.add(n),{unsubscribe:()=>{r?.delete(n),r?.size===0&&this.handlers.delete(t)}}}once(t,n){const r=i=>{s.unsubscribe(),n(i)},s=this.on(t,r);return s}off(t){this.handlers.delete(t)}dispatch(t){this.addToHistory(t),this.buildMiddlewareChain(r=>{this.notifyHandlers(r)})(t)}getHistory(t){return t?this.history.filter(t):[...this.history]}getHistoryBySession(t){return this.history.filter(n=>"sessionId"in n&&n.sessionId===t)}clearHistory(){this.history=[]}replay(t){this._isReplaying=!0;try{for(const n of t)this.dispatch(n)}finally{this._isReplaying=!1}}get isReplaying(){return this._isReplaying}setReplaying(t){this._isReplaying=t}get handlerCount(){let t=0;for(const n of this.handlers.values())t+=n.size;return t}get middlewareCount(){return this.middlewares.length}buildMiddlewareChain(t){let n=t;for(let r=this.middlewares.length-1;r>=0;r--){const s=this.middlewares[r],i=n;n=o=>{s(o,i)}}return n}notifyHandlers(t){const n=this.handlers.get(t.name);if(n)for(const s of n)try{s(t)}catch(i){console.error(`[EventBus] Handler error for ${t.name}:`,i)}const r=this.handlers.get("*");if(r)for(const s of r)try{s(t)}catch(i){console.error("[EventBus] Wildcard handler error:",i)}}addToHistory(t){this.history.push(t),this.history.length>AE&&(this.history=this.history.slice(-AE))}}const VA=new ez,tz={"llm:thinking":{color:"#3b82f6",label:"LLM"},"llm:chunk":{color:"#3b82f6",label:"LLM"},"llm:response":{color:"#22c55e",label:"LLM"},"llm:tool-call":{color:"#f59e0b",label:"Tool"},"llm:tool-result":{color:"#f59e0b",label:"Tool"},"llm:error":{color:"#ef4444",label:"Error"},"llm:unsupported-input":{color:"#ef4444",label:"Error"},"approval:request":{color:"#8b5cf6",label:"Approval"},"approval:response":{color:"#8b5cf6",label:"Approval"},"session:title-updated":{color:"#06b6d4",label:"Session"},"context:compacted":{color:"#64748b",label:"Context"},"context:pruned":{color:"#64748b",label:"Context"},"message:queued":{color:"#ec4899",label:"Queue"},"message:dequeued":{color:"#ec4899",label:"Queue"},"run:complete":{color:"#22c55e",label:"Run"},"connection:status":{color:"#64748b",label:"Connection"}};function nz(e){switch(e.name){case"llm:thinking":return`session=${e.sessionId}`;case"llm:chunk":return`${e.chunkType}: "${e.content.slice(0,30)}${e.content.length>30?"...":""}"`;case"llm:response":return`tokens=${e.tokenUsage?.totalTokens??"?"}, model=${e.model??"?"}`;case"llm:tool-call":return`${e.toolName}(${JSON.stringify(e.args).slice(0,50)}...)`;case"llm:tool-result":return`${e.toolName}: ${e.success?"success":"failed"}`;case"llm:error":return e.error?.message??"Unknown error";case"approval:request":{const t="metadata"in e&&e.metadata&&"toolName"in e.metadata?e.metadata.toolName:"unknown";return`${e.type}: ${t}`}case"approval:response":return`${e.approvalId}: ${e.status}`;case"session:title-updated":return`"${e.title}"`;case"run:complete":return`reason=${e.finishReason}, steps=${e.stepCount}`;case"message:dequeued":return`count=${e.count}`;case"connection:status":return e.status;default:return""}}const rz={enabled:!1,verbose:!1,exclude:["llm:chunk"]};let wc={...rz};const RE=(e,t)=>{if(t(e),!wc.enabled||wc.include&&!wc.include.includes(e.name)||!wc.include&&wc.exclude.includes(e.name))return;const n=tz[e.name]??{color:"#9ca3af",label:"Event"},r=nz(e),s="sessionId"in e?e.sessionId:void 0,i=s?` [${s.slice(0,8)}]`:"";console.log(`%c[${n.label}]%c ${e.name}${i}${r?` - ${r}`:""}`,`color: ${n.color}; font-weight: bold`,"color: inherit"),wc.verbose&&console.log(" Payload:",e)},ME=e=>{let t;const n=new Set,r=(h,p)=>{const g=typeof h=="function"?h(t):h;if(!Object.is(g,t)){const v=t;t=p??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(y=>y(t,v))}},s=()=>t,u={setState:r,getState:s,getInitialState:()=>f,subscribe:h=>(n.add(h),()=>n.delete(h))},f=t=e(r,s,u);return u},sz=(e=>e?ME(e):ME),iz=e=>e;function az(e,t=iz){const n=ct.useSyncExternalStore(e.subscribe,ct.useCallback(()=>t(e.getState()),[e,t]),ct.useCallback(()=>t(e.getInitialState()),[e,t]));return ct.useDebugValue(n),n}const OE=e=>{const t=sz(e),n=r=>az(t,r);return Object.assign(n,t),n},Ca=(e=>e?OE(e):OE),oz={currentSessionId:null,isWelcomeState:!0,isCreatingSession:!1,isSwitchingSession:!1,isReplayingHistory:!1,isLoadingHistory:!1},_a=Ca()((e,t)=>({...oz,setCurrentSession:n=>{e({currentSessionId:n,isWelcomeState:n===null})},setWelcomeState:n=>{e({isWelcomeState:n,...n?{currentSessionId:null}:{}})},setCreatingSession:n=>{e({isCreatingSession:n})},setSwitchingSession:n=>{e({isSwitchingSession:n})},setReplayingHistory:n=>{e({isReplayingHistory:n})},setLoadingHistory:n=>{e({isLoadingHistory:n})},returnToWelcome:()=>{e({currentSessionId:null,isWelcomeState:!0,isCreatingSession:!1,isSwitchingSession:!1,isReplayingHistory:!1,isLoadingHistory:!1})},beginSessionCreation:()=>{e({isCreatingSession:!0,isWelcomeState:!1})},completeSessionCreation:n=>{e({currentSessionId:n,isCreatingSession:!1,isWelcomeState:!1})},cancelSessionCreation:()=>{e({isCreatingSession:!1,isWelcomeState:t().currentSessionId===null})},isSessionOperationPending:()=>{const n=t();return n.isCreatingSession||n.isSwitchingSession||n.isLoadingHistory},shouldSuppressNotifications:()=>{const n=t();return n.isReplayingHistory||n.isSwitchingSession||n.isLoadingHistory}}));function lz(){return`toast-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}const cz=5,KA=Ca()((e,t)=>({toasts:[],maxToasts:cz,addToast:n=>{const r={...n,id:lz(),timestamp:Date.now()};e(s=>{const i=[...s.toasts,r];return i.length>s.maxToasts?{toasts:i.slice(i.length-s.maxToasts)}:{toasts:i}})},removeToast:n=>{e(r=>({toasts:r.toasts.filter(s=>s.id!==n)}))},clearAll:()=>{e({toasts:[]})}}));function uz(e,t){switch(e.name){case"llm:error":{if(t)return null;const n="sessionId"in e?e.sessionId:void 0;return{title:"Error in background session",description:e.error?.message||"An error occurred",intent:"danger",sessionId:n}}case"llm:response":{const n="sessionId"in e?e.sessionId:void 0;return t?null:{title:"Response Ready",description:"Agent completed in background session",intent:"info",sessionId:n}}default:return null}}const IE=(e,t)=>{t(e);const{shouldSuppressNotifications:n,currentSessionId:r}=_a.getState(),{addToast:s}=KA.getState();if(n())return;const o=("sessionId"in e?e.sessionId:void 0)===r,u=uz(e,o);u&&s(u)},dz=Ca()((e,t)=>({events:[],maxEvents:1e3,addEvent:n=>{const r=`evt-${Date.now()}-${Math.random().toString(36).substring(2,9)}`;e(s=>{const i=[...s.events,{...n,id:r}];return i.length>s.maxEvents?{events:i.slice(-s.maxEvents)}:{events:i}})},clearEvents:()=>{e({events:[]})},clearSessionEvents:n=>{e(r=>({events:r.events.filter(s=>s.sessionId!==n)}))},setMaxEvents:n=>{e(r=>r.events.length>n?{maxEvents:n,events:r.events.slice(-n)}:{maxEvents:n})},getEventsBySession:n=>t().events.filter(r=>r.sessionId===n),getEventsByCategory:n=>t().events.filter(r=>r.category===n),getRecentEvents:n=>t().events.slice(-n)})),fz={"llm:thinking":{category:"agent",getDescription:()=>"Agent started processing"},"llm:chunk":{category:"agent",getDescription:e=>{if(e.name==="llm:chunk"){const t=e.content?.slice(0,50)||"";return`Streaming ${e.chunkType}: "${t}${t.length>=50?"...":""}"`}return"Content chunk received"}},"llm:response":{category:"agent",getDescription:e=>{if(e.name==="llm:response"){const t=e.tokenUsage?.totalTokens;return t?`Response complete (${t} tokens)`:"Response complete"}return"Response complete"}},"llm:tool-call":{category:"tool",getDescription:e=>e.name==="llm:tool-call"?`Calling tool: ${e.toolName}`:"Tool call"},"llm:tool-result":{category:"tool",getDescription:e=>{if(e.name==="llm:tool-result"){const t=e.success?"succeeded":"failed";return`Tool ${e.toolName} ${t}`}return"Tool result"}},"llm:error":{category:"system",getDescription:e=>e.name==="llm:error"?`Error: ${e.error?.message||"Unknown error"}`:"Error occurred"},"approval:request":{category:"approval",getDescription:e=>e.name==="approval:request"?e.type==="tool_confirmation"&&"toolName"in e.metadata?`Approval requested for ${e.metadata.toolName}`:e.type==="command_confirmation"&&"toolName"in e.metadata?`Command approval requested for ${e.metadata.toolName}`:`Approval requested (${e.type})`:"Approval requested"},"approval:response":{category:"approval",getDescription:e=>e.name==="approval:response"?`Approval ${e.status==="approved"?"granted":e.status==="denied"?"denied":"cancelled"}`:"Approval response"},"run:complete":{category:"agent",getDescription:e=>e.name==="run:complete"?`Run complete (${e.finishReason})`:"Run complete"},"session:title-updated":{category:"system",getDescription:e=>e.name==="session:title-updated"?`Session title: "${e.title}"`:"Session title updated"},"message:dequeued":{category:"user",getDescription:()=>"Queued message processed"},"message:queued":{category:"user",getDescription:e=>e.name==="message:queued"?`Message queued at position ${e.position}`:"Message queued"},"context:compacted":{category:"system",getDescription:e=>e.name==="context:compacted"?`Context compacted: ${e.originalTokens} → ${e.compactedTokens} tokens`:"Context compacted"},"context:pruned":{category:"system",getDescription:e=>e.name==="context:pruned"?`Context pruned: ${e.prunedCount} messages, saved ${e.savedTokens} tokens`:"Context pruned"},"connection:status":{category:"system",getDescription:e=>e.name==="connection:status"?`Connection ${e.status}`:"Connection status changed"}},LE=(e,t)=>{t(e);const{addEvent:n}=dz.getState(),r=fz[e.name];n(r?{name:e.name,category:r.category,description:r.getDescription(e),timestamp:Date.now(),sessionId:"sessionId"in e?e.sessionId:void 0,metadata:{...e}}:{name:e.name,category:"system",description:`Unknown event: ${e.name}`,timestamp:Date.now(),sessionId:"sessionId"in e?e.sessionId:void 0,metadata:{...e}})},Kb={messages:[],streamingMessage:null,processing:!1,error:null,loadingHistory:!1};function ca(e,t){const n=e.get(t);return n||{...Kb}}function og(){return`msg-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}const un=Ca()((e,t)=>({sessions:new Map,addMessage:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,messages:[...o.messages,r]}),{sessions:i}})},updateMessage:(n,r,s)=>{e(i=>{const o=new Map(i.sessions),u=o.get(n);if(!u)return i;const f=u.messages.findIndex(p=>p.id===r);if(f===-1)return i;const h=[...u.messages];return h[f]={...h[f],...s},o.set(n,{...u,messages:h}),{sessions:o}})},removeMessage:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=i.get(n);return o?(i.set(n,{...o,messages:o.messages.filter(u=>u.id!==r)}),{sessions:i}):s})},clearMessages:n=>{e(r=>{const s=new Map(r.sessions),i=s.get(n);return i?(s.set(n,{...i,messages:[],streamingMessage:null}),{sessions:s}):r})},setMessages:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,messages:r}),{sessions:i}})},initFromHistory:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,messages:r,processing:!1,error:null,streamingMessage:null}),{sessions:i}})},setStreamingMessage:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,streamingMessage:r}),{sessions:i}})},appendToStreamingMessage:(n,r,s="text")=>{e(i=>{const o=new Map(i.sessions),u=ca(o,n);if(!u.streamingMessage)return i;const f=u.streamingMessage;let h;if(s==="reasoning")h={...f,reasoning:(f.reasoning||"")+r};else{const p=typeof f.content=="string"?f.content:"";h={...f,content:p+r}}return o.set(n,{...u,streamingMessage:h}),{sessions:o}})},finalizeStreamingMessage:(n,r={})=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);if(!o.streamingMessage)return s;const u={...o.streamingMessage,...r},f=o.messages??[];return i.set(n,{...o,messages:[...f,u],streamingMessage:null}),{sessions:i}})},setProcessing:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,processing:r}),{sessions:i}})},setError:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,error:r}),{sessions:i}})},setLoadingHistory:(n,r)=>{e(s=>{const i=new Map(s.sessions),o=ca(i,n);return i.set(n,{...o,loadingHistory:r}),{sessions:i}})},initSession:n=>{e(r=>{if(r.sessions.has(n))return r;const s=new Map(r.sessions);return s.set(n,{...Kb}),{sessions:s}})},removeSession:n=>{e(r=>{const s=new Map(r.sessions);return s.delete(n),{sessions:s}})},getSessionState:n=>t().sessions.get(n)??{...Kb},getMessages:n=>t().getSessionState(n).messages,getMessage:(n,r)=>t().getMessages(n).find(s=>s.id===r),getMessageByToolCallId:(n,r)=>t().getMessages(n).find(s=>s.toolCallId===r)})),hz={status:"idle",connectionStatus:"disconnected",lastHeartbeat:null,activeSessionId:null,currentToolName:null,connectionError:null,reconnectAttempts:0},Ui=Ca()((e,t)=>({...hz,setStatus:(n,r)=>{e({status:n,activeSessionId:r??(n==="idle"?null:t().activeSessionId),currentToolName:n==="executing_tool"?t().currentToolName:null})},setThinking:n=>{e({status:"thinking",activeSessionId:n,currentToolName:null})},setExecutingTool:(n,r)=>{e({status:"executing_tool",activeSessionId:n,currentToolName:r})},setAwaitingApproval:n=>{e({status:"awaiting_approval",activeSessionId:n,currentToolName:null})},setIdle:()=>{e({status:"idle",activeSessionId:null,currentToolName:null})},setConnectionStatus:n=>{e({connectionStatus:n})},setConnected:()=>{e({connectionStatus:"connected",connectionError:null,reconnectAttempts:0,lastHeartbeat:Date.now()})},setDisconnected:n=>{e({connectionStatus:"disconnected",connectionError:n??null})},setReconnecting:()=>{e({connectionStatus:"reconnecting"})},updateHeartbeat:()=>{e({lastHeartbeat:Date.now()})},incrementReconnectAttempts:()=>{e(n=>({reconnectAttempts:n.reconnectAttempts+1}))},resetReconnectAttempts:()=>{e({reconnectAttempts:0})},isBusy:()=>t().status!=="idle",isConnected:()=>t().connectionStatus==="connected",isActiveForSession:n=>{const r=t();return r.status!=="idle"&&r.activeSessionId===n},getHeartbeatAge:()=>{const{lastHeartbeat:n}=t();return n===null?null:Date.now()-n}}));var Zt;(function(e){e.assertEqual=s=>{};function t(s){}e.assertIs=t;function n(s){throw new Error}e.assertNever=n,e.arrayToEnum=s=>{const i={};for(const o of s)i[o]=o;return i},e.getValidEnumValues=s=>{const i=e.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),o={};for(const u of i)o[u]=s[u];return e.objectValues(o)},e.objectValues=s=>e.objectKeys(s).map(function(i){return s[i]}),e.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const o in s)Object.prototype.hasOwnProperty.call(s,o)&&i.push(o);return i},e.find=(s,i)=>{for(const o of s)if(i(o))return o},e.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(Zt||(Zt={}));var DE;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(DE||(DE={}));const Ye=Zt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),uo=e=>{switch(typeof e){case"undefined":return Ye.undefined;case"string":return Ye.string;case"number":return Number.isNaN(e)?Ye.nan:Ye.number;case"boolean":return Ye.boolean;case"function":return Ye.function;case"bigint":return Ye.bigint;case"symbol":return Ye.symbol;case"object":return Array.isArray(e)?Ye.array:e===null?Ye.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ye.promise:typeof Map<"u"&&e instanceof Map?Ye.map:typeof Set<"u"&&e instanceof Set?Ye.set:typeof Date<"u"&&e instanceof Date?Ye.date:Ye.object;default:return Ye.unknown}},Ae=Zt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Sa extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){const n=t||function(i){return i.message},r={_errors:[]},s=i=>{for(const o of i.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let u=r,f=0;for(;f<o.path.length;){const h=o.path[f];f===o.path.length-1?(u[h]=u[h]||{_errors:[]},u[h]._errors.push(n(o))):u[h]=u[h]||{_errors:[]},u=u[h],f++}}};return s(this),r}static assert(t){if(!(t instanceof Sa))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Zt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(t(s))}else r.push(t(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Sa.create=e=>new Sa(e);const Gb=(e,t)=>{let n;switch(e.code){case Ae.invalid_type:e.received===Ye.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Ae.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Zt.jsonStringifyReplacer)}`;break;case Ae.unrecognized_keys:n=`Unrecognized key(s) in object: ${Zt.joinValues(e.keys,", ")}`;break;case Ae.invalid_union:n="Invalid input";break;case Ae.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Zt.joinValues(e.options)}`;break;case Ae.invalid_enum_value:n=`Invalid enum value. Expected ${Zt.joinValues(e.options)}, received '${e.received}'`;break;case Ae.invalid_arguments:n="Invalid function arguments";break;case Ae.invalid_return_type:n="Invalid function return type";break;case Ae.invalid_date:n="Invalid date";break;case Ae.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Zt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Ae.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case Ae.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case Ae.custom:n="Invalid input";break;case Ae.invalid_intersection_types:n="Intersection results could not be merged";break;case Ae.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Ae.not_finite:n="Number must be finite";break;default:n=t.defaultError,Zt.assertNever(e)}return{message:n}};let mz=Gb;function pz(){return mz}const gz=e=>{const{data:t,path:n,errorMaps:r,issueData:s}=e,i=[...n,...s.path||[]],o={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let u="";const f=r.filter(h=>!!h).slice().reverse();for(const h of f)u=h(o,{data:t,defaultError:u}).message;return{...s,path:i,message:u}};function Be(e,t){const n=pz(),r=gz({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Gb?void 0:Gb].filter(s=>!!s)});e.common.issues.push(r)}class rs{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const s of n){if(s.status==="aborted")return bt;s.status==="dirty"&&t.dirty(),r.push(s.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const s of n){const i=await s.key,o=await s.value;r.push({key:i,value:o})}return rs.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const s of n){const{key:i,value:o}=s;if(i.status==="aborted"||o.status==="aborted")return bt;i.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(r[i.value]=o.value)}return{status:t.value,value:r}}}const bt=Object.freeze({status:"aborted"}),sf=e=>({status:"dirty",value:e}),ii=e=>({status:"valid",value:e}),PE=e=>e.status==="aborted",zE=e=>e.status==="dirty",ou=e=>e.status==="valid",Ep=e=>typeof Promise<"u"&&e instanceof Promise;var at;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(at||(at={}));class Bi{constructor(t,n,r,s){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $E=(e,t)=>{if(ou(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Sa(e.common.issues);return this._error=n,this._error}}};function Mt(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:s}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(o,u)=>{const{message:f}=e;return o.code==="invalid_enum_value"?{message:f??u.defaultError}:typeof u.data>"u"?{message:f??r??u.defaultError}:o.code!=="invalid_type"?{message:u.defaultError}:{message:f??n??u.defaultError}},description:s}}class Ht{get description(){return this._def.description}_getType(t){return uo(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:uo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new rs,ctx:{common:t.parent.common,data:t.data,parsedType:uo(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(Ep(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:uo(t)},s=this._parseSync({data:t,path:r.path,parent:r});return $E(r,s)}"~validate"(t){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:uo(t)};if(!this["~standard"].async)try{const r=this._parseSync({data:t,path:[],parent:n});return ou(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>ou(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:uo(t)},s=this._parse({data:t,path:r.path,parent:r}),i=await(Ep(s)?s:Promise.resolve(s));return $E(r,i)}refine(t,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const o=t(s),u=()=>i.addIssue({code:Ae.custom,...r(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(f=>f?!0:(u(),!1)):o?!0:(u(),!1)})}refinement(t,n){return this._refinement((r,s)=>t(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(t){return new kl({schema:this,typeName:_t.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return ba.create(this,this._def)}nullable(){return Nl.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pi.create(this)}promise(){return Mp.create(this,this._def)}or(t){return Cp.create([this,t],this._def)}and(t){return Tp.create(this,t,this._def)}transform(t){return new kl({...Mt(this._def),schema:this,typeName:_t.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new Op({...Mt(this._def),innerType:this,defaultValue:n,typeName:_t.ZodDefault})}brand(){return new ZA({typeName:_t.ZodBranded,type:this,...Mt(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new Ip({...Mt(this._def),innerType:this,catchValue:n,typeName:_t.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return vw.create(this,t)}readonly(){return Lp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const vz=/^c[^\s-]{8,}$/i,yz=/^[0-9a-z]+$/,xz=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bz=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wz=/^[a-z0-9_-]{21}$/i,_z=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Sz=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,kz=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Nz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let gx;const Ez=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,jz=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Cz=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Tz=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Az=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Rz=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,GA="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Mz=new RegExp(`^${GA}$`);function YA(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Oz(e){return new RegExp(`^${YA(e)}$`)}function Iz(e){let t=`${GA}T${YA(e)}`;const n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Lz(e,t){return!!((t==="v4"||!t)&&Ez.test(e)||(t==="v6"||!t)&&Cz.test(e))}function Dz(e,t){if(!_z.test(e))return!1;try{const[n]=e.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||t&&s.alg!==t)}catch{return!1}}function Pz(e,t){return!!((t==="v4"||!t)&&jz.test(e)||(t==="v6"||!t)&&Tz.test(e))}class Oi extends Ht{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ye.string){const i=this._getOrReturnCtx(t);return Be(i,{code:Ae.invalid_type,expected:Ye.string,received:i.parsedType}),bt}const r=new rs;let s;for(const i of this._def.checks)if(i.kind==="min")t.data.length<i.value&&(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")t.data.length>i.value&&(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const o=t.data.length>i.value,u=t.data.length<i.value;(o||u)&&(s=this._getOrReturnCtx(t,s),o?Be(s,{code:Ae.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):u&&Be(s,{code:Ae.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")kz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"email",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")gx||(gx=new RegExp(Nz,"u")),gx.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"emoji",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")bz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"uuid",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")wz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"nanoid",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")vz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"cuid",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")yz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"cuid2",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")xz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"ulid",code:Ae.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),Be(s,{validation:"url",code:Ae.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"regex",code:Ae.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?t.data=t.data.trim():i.kind==="includes"?t.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?t.data=t.data.toLowerCase():i.kind==="toUpperCase"?t.data=t.data.toUpperCase():i.kind==="startsWith"?t.data.startsWith(i.value)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?t.data.endsWith(i.value)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Iz(i).test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?Mz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Oz(i).test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Sz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"duration",code:Ae.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Lz(t.data,i.version)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"ip",code:Ae.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?Dz(t.data,i.alg)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"jwt",code:Ae.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Pz(t.data,i.version)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"cidr",code:Ae.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Az.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"base64",code:Ae.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Rz.test(t.data)||(s=this._getOrReturnCtx(t,s),Be(s,{validation:"base64url",code:Ae.invalid_string,message:i.message}),r.dirty()):Zt.assertNever(i);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(s=>t.test(s),{validation:n,code:Ae.invalid_string,...at.errToObj(r)})}_addCheck(t){return new Oi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...at.errToObj(t)})}url(t){return this._addCheck({kind:"url",...at.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...at.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...at.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...at.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...at.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...at.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...at.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...at.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...at.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...at.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...at.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...at.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...at.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...at.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...at.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...at.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...at.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...at.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...at.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...at.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...at.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...at.errToObj(n)})}nonempty(t){return this.min(1,at.errToObj(t))}trim(){return new Oi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Oi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Oi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}Oi.create=e=>new Oi({checks:[],typeName:_t.ZodString,coerce:e?.coerce??!1,...Mt(e)});function zz(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(e.toFixed(s).replace(".","")),o=Number.parseInt(t.toFixed(s).replace(".",""));return i%o/10**s}class bl extends Ht{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==Ye.number){const i=this._getOrReturnCtx(t);return Be(i,{code:Ae.invalid_type,expected:Ye.number,received:i.parsedType}),bt}let r;const s=new rs;for(const i of this._def.checks)i.kind==="int"?Zt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?zz(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.not_finite,message:i.message}),s.dirty()):Zt.assertNever(i);return{status:s.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,at.toString(n))}gt(t,n){return this.setLimit("min",t,!1,at.toString(n))}lte(t,n){return this.setLimit("max",t,!0,at.toString(n))}lt(t,n){return this.setLimit("max",t,!1,at.toString(n))}setLimit(t,n,r,s){return new bl({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:at.toString(s)}]})}_addCheck(t){return new bl({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:at.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:at.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:at.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:at.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:at.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:at.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:at.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:at.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:at.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Zt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}}bl.create=e=>new bl({checks:[],typeName:_t.ZodNumber,coerce:e?.coerce||!1,...Mt(e)});class wl extends Ht{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==Ye.bigint)return this._getInvalidInput(t);let r;const s=new rs;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.data<i.value:t.data<=i.value)&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?t.data>i.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Be(r,{code:Ae.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):Zt.assertNever(i);return{status:s.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Be(n,{code:Ae.invalid_type,expected:Ye.bigint,received:n.parsedType}),bt}gte(t,n){return this.setLimit("min",t,!0,at.toString(n))}gt(t,n){return this.setLimit("min",t,!1,at.toString(n))}lte(t,n){return this.setLimit("max",t,!0,at.toString(n))}lt(t,n){return this.setLimit("max",t,!1,at.toString(n))}setLimit(t,n,r,s){return new wl({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:at.toString(s)}]})}_addCheck(t){return new wl({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:at.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:at.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:at.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:at.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:at.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}}wl.create=e=>new wl({checks:[],typeName:_t.ZodBigInt,coerce:e?.coerce??!1,...Mt(e)});class jp extends Ht{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ye.boolean){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.boolean,received:r.parsedType}),bt}return ii(t.data)}}jp.create=e=>new jp({typeName:_t.ZodBoolean,coerce:e?.coerce||!1,...Mt(e)});class lu extends Ht{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ye.date){const i=this._getOrReturnCtx(t);return Be(i,{code:Ae.invalid_type,expected:Ye.date,received:i.parsedType}),bt}if(Number.isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Be(i,{code:Ae.invalid_date}),bt}const r=new rs;let s;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()<i.value&&(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?t.data.getTime()>i.value&&(s=this._getOrReturnCtx(t,s),Be(s,{code:Ae.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):Zt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new lu({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:at.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:at.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}}lu.create=e=>new lu({checks:[],coerce:e?.coerce||!1,typeName:_t.ZodDate,...Mt(e)});class FE extends Ht{_parse(t){if(this._getType(t)!==Ye.symbol){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.symbol,received:r.parsedType}),bt}return ii(t.data)}}FE.create=e=>new FE({typeName:_t.ZodSymbol,...Mt(e)});class Yb extends Ht{_parse(t){if(this._getType(t)!==Ye.undefined){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.undefined,received:r.parsedType}),bt}return ii(t.data)}}Yb.create=e=>new Yb({typeName:_t.ZodUndefined,...Mt(e)});class Wb extends Ht{_parse(t){if(this._getType(t)!==Ye.null){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.null,received:r.parsedType}),bt}return ii(t.data)}}Wb.create=e=>new Wb({typeName:_t.ZodNull,...Mt(e)});class UE extends Ht{constructor(){super(...arguments),this._any=!0}_parse(t){return ii(t.data)}}UE.create=e=>new UE({typeName:_t.ZodAny,...Mt(e)});class BE extends Ht{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ii(t.data)}}BE.create=e=>new BE({typeName:_t.ZodUnknown,...Mt(e)});class No extends Ht{_parse(t){const n=this._getOrReturnCtx(t);return Be(n,{code:Ae.invalid_type,expected:Ye.never,received:n.parsedType}),bt}}No.create=e=>new No({typeName:_t.ZodNever,...Mt(e)});class qE extends Ht{_parse(t){if(this._getType(t)!==Ye.undefined){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.void,received:r.parsedType}),bt}return ii(t.data)}}qE.create=e=>new qE({typeName:_t.ZodVoid,...Mt(e)});class Pi extends Ht{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),s=this._def;if(n.parsedType!==Ye.array)return Be(n,{code:Ae.invalid_type,expected:Ye.array,received:n.parsedType}),bt;if(s.exactLength!==null){const o=n.data.length>s.exactLength.value,u=n.data.length<s.exactLength.value;(o||u)&&(Be(n,{code:o?Ae.too_big:Ae.too_small,minimum:u?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(Be(n,{code:Ae.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(Be(n,{code:Ae.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,u)=>s.type._parseAsync(new Bi(n,o,n.path,u)))).then(o=>rs.mergeArray(r,o));const i=[...n.data].map((o,u)=>s.type._parseSync(new Bi(n,o,n.path,u)));return rs.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Pi({...this._def,minLength:{value:t,message:at.toString(n)}})}max(t,n){return new Pi({...this._def,maxLength:{value:t,message:at.toString(n)}})}length(t,n){return new Pi({...this._def,exactLength:{value:t,message:at.toString(n)}})}nonempty(t){return this.min(1,t)}}Pi.create=(e,t)=>new Pi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_t.ZodArray,...Mt(t)});function Rc(e){if(e instanceof ur){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ba.create(Rc(r))}return new ur({...e._def,shape:()=>t})}else return e instanceof Pi?new Pi({...e._def,type:Rc(e.element)}):e instanceof ba?ba.create(Rc(e.unwrap())):e instanceof Nl?Nl.create(Rc(e.unwrap())):e instanceof _l?_l.create(e.items.map(t=>Rc(t))):e}class ur extends Ht{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=Zt.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==Ye.object){const h=this._getOrReturnCtx(t);return Be(h,{code:Ae.invalid_type,expected:Ye.object,received:h.parsedType}),bt}const{status:r,ctx:s}=this._processInputParams(t),{shape:i,keys:o}=this._getCached(),u=[];if(!(this._def.catchall instanceof No&&this._def.unknownKeys==="strip"))for(const h in s.data)o.includes(h)||u.push(h);const f=[];for(const h of o){const p=i[h],g=s.data[h];f.push({key:{status:"valid",value:h},value:p._parse(new Bi(s,g,s.path,h)),alwaysSet:h in s.data})}if(this._def.catchall instanceof No){const h=this._def.unknownKeys;if(h==="passthrough")for(const p of u)f.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(h==="strict")u.length>0&&(Be(s,{code:Ae.unrecognized_keys,keys:u}),r.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const h=this._def.catchall;for(const p of u){const g=s.data[p];f.push({key:{status:"valid",value:p},value:h._parse(new Bi(s,g,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const h=[];for(const p of f){const g=await p.key,v=await p.value;h.push({key:g,value:v,alwaysSet:p.alwaysSet})}return h}).then(h=>rs.mergeObjectSync(r,h)):rs.mergeObjectSync(r,f)}get shape(){return this._def.shape()}strict(t){return at.errToObj,new ur({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{const s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:at.errToObj(t).message??s}:{message:s}}}:{}})}strip(){return new ur({...this._def,unknownKeys:"strip"})}passthrough(){return new ur({...this._def,unknownKeys:"passthrough"})}extend(t){return new ur({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new ur({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:_t.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new ur({...this._def,catchall:t})}pick(t){const n={};for(const r of Zt.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new ur({...this._def,shape:()=>n})}omit(t){const n={};for(const r of Zt.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new ur({...this._def,shape:()=>n})}deepPartial(){return Rc(this)}partial(t){const n={};for(const r of Zt.objectKeys(this.shape)){const s=this.shape[r];t&&!t[r]?n[r]=s:n[r]=s.optional()}return new ur({...this._def,shape:()=>n})}required(t){const n={};for(const r of Zt.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof ba;)i=i._def.innerType;n[r]=i}return new ur({...this._def,shape:()=>n})}keyof(){return WA(Zt.objectKeys(this.shape))}}ur.create=(e,t)=>new ur({shape:()=>e,unknownKeys:"strip",catchall:No.create(),typeName:_t.ZodObject,...Mt(t)});ur.strictCreate=(e,t)=>new ur({shape:()=>e,unknownKeys:"strict",catchall:No.create(),typeName:_t.ZodObject,...Mt(t)});ur.lazycreate=(e,t)=>new ur({shape:e,unknownKeys:"strip",catchall:No.create(),typeName:_t.ZodObject,...Mt(t)});class Cp extends Ht{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function s(i){for(const u of i)if(u.result.status==="valid")return u.result;for(const u of i)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const o=i.map(u=>new Sa(u.ctx.common.issues));return Be(n,{code:Ae.invalid_union,unionErrors:o}),bt}if(n.common.async)return Promise.all(r.map(async i=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(s);{let i;const o=[];for(const f of r){const h={...n,common:{...n.common,issues:[]},parent:null},p=f._parseSync({data:n.data,path:n.path,parent:h});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:h}),h.common.issues.length&&o.push(h.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const u=o.map(f=>new Sa(f));return Be(n,{code:Ae.invalid_union,unionErrors:u}),bt}}get options(){return this._def.options}}Cp.create=(e,t)=>new Cp({options:e,typeName:_t.ZodUnion,...Mt(t)});const da=e=>e instanceof Xb?da(e.schema):e instanceof kl?da(e.innerType()):e instanceof Rp?[e.value]:e instanceof Sl?e.options:e instanceof Qb?Zt.objectValues(e.enum):e instanceof Op?da(e._def.innerType):e instanceof Yb?[void 0]:e instanceof Wb?[null]:e instanceof ba?[void 0,...da(e.unwrap())]:e instanceof Nl?[null,...da(e.unwrap())]:e instanceof ZA||e instanceof Lp?da(e.unwrap()):e instanceof Ip?da(e._def.innerType):[];class gw extends Ht{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Ye.object)return Be(n,{code:Ae.invalid_type,expected:Ye.object,received:n.parsedType}),bt;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Be(n,{code:Ae.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),bt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const s=new Map;for(const i of n){const o=da(i.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const u of o){if(s.has(u))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(u)}`);s.set(u,i)}}return new gw({typeName:_t.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:s,...Mt(r)})}}function Zb(e,t){const n=uo(e),r=uo(t);if(e===t)return{valid:!0,data:e};if(n===Ye.object&&r===Ye.object){const s=Zt.objectKeys(t),i=Zt.objectKeys(e).filter(u=>s.indexOf(u)!==-1),o={...e,...t};for(const u of i){const f=Zb(e[u],t[u]);if(!f.valid)return{valid:!1};o[u]=f.data}return{valid:!0,data:o}}else if(n===Ye.array&&r===Ye.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let i=0;i<e.length;i++){const o=e[i],u=t[i],f=Zb(o,u);if(!f.valid)return{valid:!1};s.push(f.data)}return{valid:!0,data:s}}else return n===Ye.date&&r===Ye.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Tp extends Ht{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=(i,o)=>{if(PE(i)||PE(o))return bt;const u=Zb(i.value,o.value);return u.valid?((zE(i)||zE(o))&&n.dirty(),{status:n.value,value:u.data}):(Be(r,{code:Ae.invalid_intersection_types}),bt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,o])=>s(i,o)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Tp.create=(e,t,n)=>new Tp({left:e,right:t,typeName:_t.ZodIntersection,...Mt(n)});class _l extends Ht{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ye.array)return Be(r,{code:Ae.invalid_type,expected:Ye.array,received:r.parsedType}),bt;if(r.data.length<this._def.items.length)return Be(r,{code:Ae.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&r.data.length>this._def.items.length&&(Be(r,{code:Ae.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((o,u)=>{const f=this._def.items[u]||this._def.rest;return f?f._parse(new Bi(r,o,r.path,u)):null}).filter(o=>!!o);return r.common.async?Promise.all(i).then(o=>rs.mergeArray(n,o)):rs.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _l({...this._def,rest:t})}}_l.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _l({items:e,typeName:_t.ZodTuple,rest:null,...Mt(t)})};class Ap extends Ht{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ye.object)return Be(r,{code:Ae.invalid_type,expected:Ye.object,received:r.parsedType}),bt;const s=[],i=this._def.keyType,o=this._def.valueType;for(const u in r.data)s.push({key:i._parse(new Bi(r,u,r.path,u)),value:o._parse(new Bi(r,r.data[u],r.path,u)),alwaysSet:u in r.data});return r.common.async?rs.mergeObjectAsync(n,s):rs.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Ht?new Ap({keyType:t,valueType:n,typeName:_t.ZodRecord,...Mt(r)}):new Ap({keyType:Oi.create(),valueType:t,typeName:_t.ZodRecord,...Mt(n)})}}class HE extends Ht{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ye.map)return Be(r,{code:Ae.invalid_type,expected:Ye.map,received:r.parsedType}),bt;const s=this._def.keyType,i=this._def.valueType,o=[...r.data.entries()].map(([u,f],h)=>({key:s._parse(new Bi(r,u,r.path,[h,"key"])),value:i._parse(new Bi(r,f,r.path,[h,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const f of o){const h=await f.key,p=await f.value;if(h.status==="aborted"||p.status==="aborted")return bt;(h.status==="dirty"||p.status==="dirty")&&n.dirty(),u.set(h.value,p.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const f of o){const h=f.key,p=f.value;if(h.status==="aborted"||p.status==="aborted")return bt;(h.status==="dirty"||p.status==="dirty")&&n.dirty(),u.set(h.value,p.value)}return{status:n.value,value:u}}}}HE.create=(e,t,n)=>new HE({valueType:t,keyType:e,typeName:_t.ZodMap,...Mt(n)});class Mf extends Ht{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==Ye.set)return Be(r,{code:Ae.invalid_type,expected:Ye.set,received:r.parsedType}),bt;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Be(r,{code:Ae.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Be(r,{code:Ae.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function o(f){const h=new Set;for(const p of f){if(p.status==="aborted")return bt;p.status==="dirty"&&n.dirty(),h.add(p.value)}return{status:n.value,value:h}}const u=[...r.data.values()].map((f,h)=>i._parse(new Bi(r,f,r.path,h)));return r.common.async?Promise.all(u).then(f=>o(f)):o(u)}min(t,n){return new Mf({...this._def,minSize:{value:t,message:at.toString(n)}})}max(t,n){return new Mf({...this._def,maxSize:{value:t,message:at.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Mf.create=(e,t)=>new Mf({valueType:e,minSize:null,maxSize:null,typeName:_t.ZodSet,...Mt(t)});class Xb extends Ht{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Xb.create=(e,t)=>new Xb({getter:e,typeName:_t.ZodLazy,...Mt(t)});class Rp extends Ht{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Be(n,{received:n.data,code:Ae.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}}Rp.create=(e,t)=>new Rp({value:e,typeName:_t.ZodLiteral,...Mt(t)});function WA(e,t){return new Sl({values:e,typeName:_t.ZodEnum,...Mt(t)})}class Sl extends Ht{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Be(n,{expected:Zt.joinValues(r),received:n.parsedType,code:Ae.invalid_type}),bt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const n=this._getOrReturnCtx(t),r=this._def.values;return Be(n,{received:n.data,code:Ae.invalid_enum_value,options:r}),bt}return ii(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Sl.create(t,{...this._def,...n})}exclude(t,n=this._def){return Sl.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}Sl.create=WA;class Qb extends Ht{_parse(t){const n=Zt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==Ye.string&&r.parsedType!==Ye.number){const s=Zt.objectValues(n);return Be(r,{expected:Zt.joinValues(s),received:r.parsedType,code:Ae.invalid_type}),bt}if(this._cache||(this._cache=new Set(Zt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const s=Zt.objectValues(n);return Be(r,{received:r.data,code:Ae.invalid_enum_value,options:s}),bt}return ii(t.data)}get enum(){return this._def.values}}Qb.create=(e,t)=>new Qb({values:e,typeName:_t.ZodNativeEnum,...Mt(t)});class Mp extends Ht{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==Ye.promise&&n.common.async===!1)return Be(n,{code:Ae.invalid_type,expected:Ye.promise,received:n.parsedType}),bt;const r=n.parsedType===Ye.promise?n.data:Promise.resolve(n.data);return ii(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Mp.create=(e,t)=>new Mp({type:e,typeName:_t.ZodPromise,...Mt(t)});class kl extends Ht{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_t.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),s=this._def.effect||null,i={addIssue:o=>{Be(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const o=s.transform(r.data,i);if(r.common.async)return Promise.resolve(o).then(async u=>{if(n.value==="aborted")return bt;const f=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return f.status==="aborted"?bt:f.status==="dirty"||n.value==="dirty"?sf(f.value):f});{if(n.value==="aborted")return bt;const u=this._def.schema._parseSync({data:o,path:r.path,parent:r});return u.status==="aborted"?bt:u.status==="dirty"||n.value==="dirty"?sf(u.value):u}}if(s.type==="refinement"){const o=u=>{const f=s.refinement(u,i);if(r.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?bt:(u.status==="dirty"&&n.dirty(),o(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?bt:(u.status==="dirty"&&n.dirty(),o(u.value).then(()=>({status:n.value,value:u.value}))))}if(s.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ou(o))return bt;const u=s.transform(o.value,i);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>ou(o)?Promise.resolve(s.transform(o.value,i)).then(u=>({status:n.value,value:u})):bt);Zt.assertNever(s)}}kl.create=(e,t,n)=>new kl({schema:e,typeName:_t.ZodEffects,effect:t,...Mt(n)});kl.createWithPreprocess=(e,t,n)=>new kl({schema:t,effect:{type:"preprocess",transform:e},typeName:_t.ZodEffects,...Mt(n)});class ba extends Ht{_parse(t){return this._getType(t)===Ye.undefined?ii(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ba.create=(e,t)=>new ba({innerType:e,typeName:_t.ZodOptional,...Mt(t)});class Nl extends Ht{_parse(t){return this._getType(t)===Ye.null?ii(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Nl.create=(e,t)=>new Nl({innerType:e,typeName:_t.ZodNullable,...Mt(t)});class Op extends Ht{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===Ye.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Op.create=(e,t)=>new Op({innerType:e,typeName:_t.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Mt(t)});class Ip extends Ht{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ep(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Sa(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Sa(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Ip.create=(e,t)=>new Ip({innerType:e,typeName:_t.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Mt(t)});class VE extends Ht{_parse(t){if(this._getType(t)!==Ye.nan){const r=this._getOrReturnCtx(t);return Be(r,{code:Ae.invalid_type,expected:Ye.nan,received:r.parsedType}),bt}return{status:"valid",value:t.data}}}VE.create=e=>new VE({typeName:_t.ZodNaN,...Mt(e)});class ZA extends Ht{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class vw extends Ht{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?bt:i.status==="dirty"?(n.dirty(),sf(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?bt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(t,n){return new vw({in:t,out:n,typeName:_t.ZodPipeline})}}class Lp extends Ht{_parse(t){const n=this._def.innerType._parse(t),r=s=>(ou(s)&&(s.value=Object.freeze(s.value)),s);return Ep(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Lp.create=(e,t)=>new Lp({innerType:e,typeName:_t.ZodReadonly,...Mt(t)});var _t;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(_t||(_t={}));const yw=Oi.create;bl.create;wl.create;const xw=jp.create;lu.create;No.create;const $z=Pi.create,bw=ur.create;Cp.create;const Fz=gw.create;Tp.create;_l.create;const lg=Ap.create,ww=Rp.create,_w=Sl.create;Mp.create;ba.create;Nl.create;const Sw={string:(e=>Oi.create({...e,coerce:!0})),number:(e=>bl.create({...e,coerce:!0})),boolean:(e=>jp.create({...e,coerce:!0})),bigint:(e=>wl.create({...e,coerce:!0})),date:(e=>lu.create({...e,coerce:!0}))};var XA=(e=>(e.LLM="llm",e.AGENT="agent",e.CONFIG="config",e.CONTEXT="context",e.SESSION="session",e.MCP="mcp",e.TOOLS="tools",e.STORAGE="storage",e.LOGGER="logger",e.SYSTEM_PROMPT="system_prompt",e.RESOURCE="resource",e.PROMPT="prompt",e.MEMORY="memory",e.HOOK="hook",e.TELEMETRY="telemetry",e))(XA||{}),QA=(e=>(e.USER="user",e.PAYMENT_REQUIRED="payment_required",e.FORBIDDEN="forbidden",e.NOT_FOUND="not_found",e.TIMEOUT="timeout",e.CONFLICT="conflict",e.RATE_LIMIT="rate_limit",e.SYSTEM="system",e.THIRD_PARTY="third_party",e.UNKNOWN="unknown",e))(QA||{}),Uz={};yw().transform(e=>e.trim()).refine(e=>e.length>0,{message:"Required"});const JA=new Set(["http:","https:","codex:"]);function Bz(e){try{const t=new URL(e);return JA.has(t.protocol)}catch{return!1}}yw().transform(e=>e.trim()).refine(e=>e===""||Bz(e),{message:"Invalid URL"}).transform(e=>e===""?void 0:e).optional();const Wc=e=>yw().transform(t=>{if(typeof t!="string")return"";const n=e??Uz;return t.replace(/\$([A-Z_][A-Z0-9_]*)|\${([A-Z_][A-Z0-9_]*)}/gi,(s,i,o)=>n[i||o]??"").trim()}),e2=e=>Wc(e).refine(t=>{try{const n=new URL(t);return JA.has(n.protocol)}catch{return!1}},{message:"Invalid URL"});function kw(e){return e?.startsWith("audio/")?"audio":e?.startsWith("video/")?"video":"binary"}function qz(e){return e?.startsWith("image/")?"image":e?.startsWith("audio/")?"audio":e?.startsWith("video/")?"video":"binary"}const $c=["openai","openai-compatible","anthropic","google","groq","xai","cohere","minimax","glm","openrouter","litellm","glama","vertex","bedrock","local","ollama","dexto-nova"];var t2=(e=>(e.SCHEMA_VALIDATION="mcp_schema_validation",e.COMMAND_MISSING="mcp_command_missing",e.DUPLICATE_NAME="mcp_duplicate_name",e.CONNECTION_FAILED="mcp_connection_failed",e.DISCONNECTION_FAILED="mcp_disconnection_failed",e.AUTH_REQUIRED="mcp_auth_required",e.PROTOCOL_ERROR="mcp_protocol_error",e.SERVER_NOT_FOUND="mcp_server_not_found",e.TOOL_NOT_FOUND="mcp_tool_not_found",e.PROMPT_NOT_FOUND="mcp_prompt_not_found",e.RESOURCE_NOT_FOUND="mcp_resource_not_found",e))(t2||{}),n2={};const Hz=["stdio","sse","http"],Nw=["strict","lenient"],Ew="lenient",Vz=bw({type:ww("stdio"),enabled:xw().default(!0).describe("Whether this server is enabled (disabled servers are not connected)"),command:Wc().superRefine((e,t)=>{e.length===0&&t.addIssue({code:Ae.custom,message:"Stdio server requires a non-empty command",params:{code:t2.COMMAND_MISSING,scope:XA.MCP,type:QA.USER}})}),args:$z(Wc()).default([]).describe("Array of arguments for the command (e.g., ['script.js'])"),env:lg(Wc()).default({}).describe("Optional environment variables for the server process"),timeout:Sw.number().int().positive().default(3e4),connectionMode:_w(Nw).default(Ew)}).strict(),Kz=bw({type:ww("sse"),enabled:xw().default(!0).describe("Whether this server is enabled (disabled servers are not connected)"),url:e2(n2).describe("URL for the SSE server endpoint"),headers:lg(Wc()).default({}),timeout:Sw.number().int().positive().default(3e4),connectionMode:_w(Nw).default(Ew)}).strict(),Gz=bw({type:ww("http"),enabled:xw().default(!0).describe("Whether this server is enabled (disabled servers are not connected)"),url:e2(n2).describe("URL for the HTTP server"),headers:lg(Wc()).default({}),timeout:Sw.number().int().positive().default(3e4),connectionMode:_w(Nw).default(Ew)}).strict(),Yz=Fz("type",[Vz,Kz,Gz]).superRefine((e,t)=>{}).brand();lg(Yz).describe("A dictionary of server configurations, keyed by server name").brand();var Zc=(e=>(e.APPROVED="approved",e.DENIED="denied",e.CANCELLED="cancelled",e))(Zc||{});const Wz="modulepreload",Zz=function(e){return"/"+e},KE={},Xz=function(t,n,r){let s=Promise.resolve();if(n&&n.length>0){let f=function(h){return Promise.all(h.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=o?.nonce||o?.getAttribute("nonce");s=f(n.map(h=>{if(h=Zz(h),h in KE)return;KE[h]=!0;const p=h.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${g}`))return;const v=document.createElement("link");if(v.rel=p?"stylesheet":Wz,p||(v.as="script"),v.crossOrigin="",v.href=h,u&&v.setAttribute("nonce",u),document.head.appendChild(v),p)return new Promise((y,S)=>{v.addEventListener("load",y),v.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${h}`)))})}))}function i(o){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=o,window.dispatchEvent(u),!u.defaultPrevented)throw o}return s.then(o=>{for(const u of o||[])u.status==="rejected"&&i(u.reason);return t().catch(i)})};function Qz(e){const t=[],n=new RegExp("(?:^|(?<=\\s))@(?:(<[^>]+>)|([a-zA-Z0-9_-]+):([a-zA-Z0-9._/-]+)|([a-zA-Z0-9._/-]+))(?![a-zA-Z0-9@.])","g");let r;for(;(r=n.exec(e))!==null;){const[s,i,o,u,f]=r;i?t.push({originalRef:s,type:"uri",identifier:i.slice(1,-1)}):o&&u?t.push({originalRef:s,type:"server-scoped",serverName:o,identifier:u}):f&&t.push({originalRef:s,type:"name",identifier:f})}return t}function Jz(e,t){const n=e.map(r=>({...r}));for(const r of n)switch(r.type){case"uri":{if(t[r.identifier])r.resourceUri=r.identifier;else{const s=e$(t,r.identifier);s&&(r.resourceUri=s)}break}case"server-scoped":{const s=t$(t,r.serverName,r.identifier);s&&(r.resourceUri=s);break}case"name":{const s=n$(t,r.identifier);s&&(r.resourceUri=s);break}}return n}function e$(e,t){const n=t.trim().toLowerCase();for(const[r,s]of Object.entries(e)){const i=typeof s.metadata?.originalUri=="string"?s.metadata.originalUri:void 0;if(i&&i.toLowerCase()===n)return r}for(const[r,s]of Object.entries(e)){const i=typeof s.metadata?.originalUri=="string"?s.metadata.originalUri:void 0;if(i&&i.toLowerCase().includes(n))return r}}function t$(e,t,n){const r=n.trim().toLowerCase(),s=Object.entries(e).filter(([,i])=>i.serverName===t);for(const[i,o]of s){if(!o.name)continue;const u=o.name.trim().toLowerCase();if(u===r||u.includes(r))return i}for(const[i,o]of s)if((typeof o.metadata?.originalUri=="string"?o.metadata.originalUri:void 0)?.toLowerCase().includes(r)||i.toLowerCase().includes(r))return i}function n$(e,t){const n=t.trim().toLowerCase();for(const[r,s]of Object.entries(e)){if(!s.name)continue;const i=s.name.trim().toLowerCase();if(i===n||i.includes(n))return r}for(const[r,s]of Object.entries(e))if((typeof s.metadata?.originalUri=="string"?s.metadata.originalUri:void 0)?.toLowerCase().includes(n)||r.toLowerCase().includes(n))return r}function r$(e){return e===Zc.APPROVED||e===Zc.DENIED||e===Zc.CANCELLED}const Of=Ca((e,t)=>({pendingApproval:null,queue:[],addApproval:n=>{e(r=>r.pendingApproval?{queue:[...r.queue,n]}:{pendingApproval:n})},processResponse:n=>{e(r=>{if(r.pendingApproval?.approvalId!==n.approvalId)return r;if(r$(n.status)){const[s,...i]=r.queue;return{pendingApproval:s??null,queue:i}}return r})},clearApproval:()=>{e(n=>{const[r,...s]=n.queue;return{pendingApproval:r??null,queue:s}})},clearAll:()=>{e({pendingApproval:null,queue:[]})},getPendingCount:()=>{const n=t();return(n.pendingApproval?1:0)+n.queue.length},getPendingForSession:n=>{const r=t(),s=[];return r.pendingApproval?.sessionId===n&&s.push(r.pendingApproval),s.push(...r.queue.filter(i=>i.sessionId===n)),s},hasPendingApproval:()=>t().pendingApproval!==null}));function s$(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const o=f=>f===null?null:JSON.parse(f,void 0),u=(i=n.getItem(s))!=null?i:null;return u instanceof Promise?u.then(o):o(u)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const Jb=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Jb(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Jb(r)(n)}}}},i$=(e,t)=>(n,r,s)=>{let i={storage:s$(()=>localStorage),partialize:w=>w,version:0,merge:(w,N)=>({...N,...w}),...t},o=!1;const u=new Set,f=new Set;let h=i.storage;if(!h)return e((...w)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...w)},r,s);const p=()=>{const w=i.partialize({...r()});return h.setItem(i.name,{state:w,version:i.version})},g=s.setState;s.setState=(w,N)=>(g(w,N),p());const v=e((...w)=>(n(...w),p()),r,s);s.getInitialState=()=>v;let y;const S=()=>{var w,N;if(!h)return;o=!1,u.forEach(j=>{var E;return j((E=r())!=null?E:v)});const k=((N=i.onRehydrateStorage)==null?void 0:N.call(i,(w=r())!=null?w:v))||void 0;return Jb(h.getItem.bind(h))(i.name).then(j=>{if(j)if(typeof j.version=="number"&&j.version!==i.version){if(i.migrate){const E=i.migrate(j.state,j.version);return E instanceof Promise?E.then(C=>[!0,C]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,j.state];return[!1,void 0]}).then(j=>{var E;const[C,M]=j;if(y=i.merge(M,(E=r())!=null?E:v),n(y,!0),C)return p()}).then(()=>{k?.(y,void 0),y=r(),o=!0,f.forEach(j=>j(y))}).catch(j=>{k?.(void 0,j)})};return s.persist={setOptions:w=>{i={...i,...w},w.storage&&(h=w.storage)},clearStorage:()=>{h?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>o,onHydrate:w=>(u.add(w),()=>{u.delete(w)}),onFinishHydration:w=>(f.add(w),()=>{f.delete(w)})},i.skipHydration||S(),y||v},r2=i$,a$={isStreaming:!0},s2=Ca()(r2(e=>({...a$,setStreaming:t=>{e({isStreaming:t})}}),{name:"dexto-preferences",version:1})),i2=Ca()((e,t)=>({sessions:new Map,getTodos:n=>t().sessions.get(n)?.todos??[],setTodos:(n,r)=>{e(s=>{const i=new Map(s.sessions);return i.set(n,{todos:r}),{sessions:i}})},clearTodos:n=>{e(r=>{const s=new Map(r.sessions);return s.delete(n),{sessions:s}})}})),jw=new Map;function As(e,t){jw.set(e,t)}function a2(e){const t=un.getState();t.getSessionState(e).streamingMessage&&t.finalizeStreamingMessage(e,{})}function pf(e){if(e.startsWith("mcp--")){const t=e.substring(5),n=t.split("--");return n.length>=2?n.slice(1).join("--"):t}return e}function o$(e){const{sessionId:t}=e;un.getState().setProcessing(t,!0),Ui.getState().setThinking(t)}function l$(e){if(!s2.getState().isStreaming)return;const{sessionId:n,content:r,chunkType:s="text"}=e,i=un.getState();if(i.getSessionState(n).streamingMessage)i.appendToStreamingMessage(n,r,s);else{const u={id:og(),role:"assistant",content:s==="text"?r:"",reasoning:s==="reasoning"?r:void 0,createdAt:Date.now(),sessionId:n};i.setStreamingMessage(n,u)}}function c$(e){const{sessionId:t,content:n,reasoning:r,tokenUsage:s,model:i,provider:o,estimatedInputTokens:u,reasoningVariant:f,reasoningBudgetTokens:h}=e,p=un.getState(),g=p.getSessionState(t),v=typeof n=="string"?n:"";if(g.streamingMessage){if(p.finalizeStreamingMessage(t,{content:v,...r&&{reasoning:r},tokenUsage:s,...i&&{model:i},...o&&{provider:o}}),s&&(s.inputTokens||s.outputTokens)){let w;if(u!==void 0&&s.inputTokens){const N=u-s.inputTokens;w=Math.round(N/s.inputTokens*100)}TE({sessionId:t,provider:o,model:i,reasoningVariant:f,reasoningBudgetTokens:h,inputTokens:s.inputTokens,outputTokens:s.outputTokens,reasoningTokens:s.reasoningTokens,totalTokens:s.totalTokens,cacheReadTokens:s.cacheReadTokens,cacheWriteTokens:s.cacheWriteTokens,estimatedInputTokens:u,estimateAccuracyPercent:w})}return}const y=g.messages;let S=null;for(let w=y.length-1;w>=0;w--){const N=y[w];if(N.role==="assistant"){S=N;break}if(N.role==="user")break}if(S?p.updateMessage(t,S.id,{content:v||S.content,...r&&{reasoning:r},tokenUsage:s,...i&&{model:i},...o&&{provider:o}}):v&&p.addMessage(t,{id:og(),role:"assistant",content:v,...r&&{reasoning:r},tokenUsage:s,...i&&{model:i},...o&&{provider:o},createdAt:Date.now(),sessionId:t}),s&&(s.inputTokens||s.outputTokens)){let w;if(u!==void 0&&s.inputTokens){const N=u-s.inputTokens;w=Math.round(N/s.inputTokens*100)}TE({sessionId:t,provider:o,model:i,reasoningVariant:f,reasoningBudgetTokens:h,inputTokens:s.inputTokens,outputTokens:s.outputTokens,reasoningTokens:s.reasoningTokens,totalTokens:s.totalTokens,cacheReadTokens:s.cacheReadTokens,cacheWriteTokens:s.cacheWriteTokens,estimatedInputTokens:u,estimateAccuracyPercent:w})}}function u$(e){const{sessionId:t,toolName:n,args:r,callId:s,presentationSnapshot:i}=e,o=un.getState();a2(t);const u=o.getMessages(t),f=u.find(v=>v.role==="tool"&&v.toolCallId===s&&v.toolResult===void 0);if(f){o.updateMessage(t,f.id,{toolArgs:r,...i!==void 0&&{presentationSnapshot:i}}),console.debug("[handlers] Tool call message already exists:",f.id);return}const h=pf(n),p=u.find(v=>v.role!=="tool"||v.toolResult!==void 0||v.requireApproval!==!0||v.approvalStatus!=="pending"?!1:!!(v.toolName===n||v.toolName&&pf(v.toolName)===h));if(p){o.updateMessage(t,p.id,{toolCallId:s,toolArgs:r,...i!==void 0&&{presentationSnapshot:i}}),console.debug("[handlers] Updated existing approval message with callId:",p.id);return}const g={id:`tool-${s}`,role:"tool",content:null,toolName:n,...i!==void 0&&{presentationSnapshot:i},toolArgs:r,toolCallId:s,createdAt:Date.now(),sessionId:t};o.addMessage(t,g),Ui.getState().setExecutingTool(t,n)}function d$(e){const{sessionId:t,callId:n,success:r,sanitized:s,requireApproval:i,approvalStatus:o,presentationSnapshot:u}=e,f=un.getState();let h=n?f.getMessageByToolCallId(t,n):void 0;if(!h&&n&&(h=f.getMessages(t).find(g=>g.id===`tool-${n}`||g.id===`approval-${n}`)),!h){const g=f.getMessages(t).filter(v=>v.role==="tool"&&v.toolResult===void 0).sort((v,y)=>y.createdAt-v.createdAt);h=g.find(v=>v.id.startsWith("approval-"))||g[0]}h?f.updateMessage(t,h.id,{toolResult:s,toolResultMeta:s?.meta,toolResultSuccess:r,...u!==void 0&&{presentationSnapshot:u},...i!==void 0&&{requireApproval:i},...o!==void 0&&{approvalStatus:o}}):console.warn("[handlers] Could not find tool message to update for callId:",n)}function f$(e){const{sessionId:t,error:n,context:r,recoverable:s}=e,i=un.getState();i.setError(t,{id:og(),message:n?.message||"Unknown error",timestamp:Date.now(),context:r,recoverable:s,sessionId:t}),i.setProcessing(t,!1),Ui.getState().setIdle()}function h$(e){const t=e.sessionId||"",n=un.getState();t&&a2(t),Of.getState().addApproval(e);const r=e.approvalId,s=e.metadata?.toolName||e.toolName||"unknown",i=e.metadata?.args||e.args||{},o=e.metadata?.presentationSnapshot,u=e.type,f=pf(s),h=n.getMessages(t),p=h.find(g=>g.role!=="tool"||g.toolResult!==void 0||g.requireApproval===!0?!1:!!(g.toolName===s||g.toolName&&pf(g.toolName)===f));if(p)n.updateMessage(t,p.id,{requireApproval:!0,approvalStatus:"pending",...o!==void 0&&{presentationSnapshot:o}}),console.debug("[handlers] Updated existing tool message with approval:",p.id);else if(t){const g=h.find(v=>v.role==="tool"&&v.requireApproval===!0&&v.approvalStatus==="pending"&&v.toolResult===void 0&&(v.toolName===s||v.toolName&&pf(v.toolName)===f));if(g)console.debug("[handlers] Approval message already exists:",g.id);else{const v={id:`approval-${r}`,role:"tool",content:null,toolName:s,...o!==void 0&&{presentationSnapshot:o},toolArgs:i,toolCallId:r,createdAt:Date.now(),sessionId:t,requireApproval:!0,approvalStatus:"pending",...u&&{approvalType:u}};n.addMessage(t,v)}}t&&Ui.getState().setAwaitingApproval(t)}function m$(e){const{status:t}=e,n=e.sessionId||"",r=e.approvalId;if(Of.getState().processResponse(e),n&&r){const i=un.getState(),u=i.getMessages(n).find(f=>f.id===`approval-${r}`||f.toolCallId===r&&f.requireApproval);if(u){const f=t==="approved"?"approved":"rejected";i.updateMessage(n,u.id,{approvalStatus:f,...f==="rejected"&&{toolResultSuccess:!1}}),console.debug("[handlers] Updated approval status:",u.id,f)}}t==="approved"?n&&Ui.getState().setThinking(n):(Ui.getState().setIdle(),n&&un.getState().setProcessing(n,!1))}function p$(e){const{sessionId:t}=e;un.getState().setProcessing(t,!1),Ui.getState().setIdle()}function g$(e){console.debug("[handlers] session:title-updated",e.sessionId,e.title)}function v$(e){const{sessionId:t,content:n}=e,r=un.getState(),s=n.filter(u=>u.type==="text").map(u=>u.text).join(`
29
- `),i=n.find(u=>u.type==="image"),o=n.find(u=>u.type==="file");if(s||n.length>0){const u=i&&typeof i.image=="string"?{image:i.image,mimeType:i.mimeType??"image/jpeg"}:void 0,f={id:og(),role:"user",content:s||"[attachment]",createdAt:Date.now(),sessionId:t,imageData:u,fileData:o?{data:typeof o.data=="string"?o.data:"",mimeType:o.mimeType,filename:o.filename}:void 0};r.addMessage(t,f)}}function y$(e){console.debug(`[handlers] Context compacted: ${e.originalTokens.toLocaleString()} → ${e.compactedTokens.toLocaleString()} tokens (${e.originalMessages} → ${e.compactedMessages} messages) via ${e.strategy}`)}function x$(e){const{service:t,event:n,toolCallId:r,sessionId:s,data:i}=e;if(t==="agent-spawner"&&n==="progress"&&r&&s){const o=un.getState(),u=i,h=o.getMessages(s).find(p=>p.role==="tool"&&p.toolCallId===r);h&&o.updateMessage(s,h.id,{subAgentProgress:{task:u.task,agentId:u.agentId,toolsCalled:u.toolsCalled,currentTool:u.currentTool,currentArgs:u.currentArgs}})}if(t==="todo"&&n==="updated"&&s){const o=i;i2.getState().setTodos(s,o.todos)}}function b$(){jw.clear(),As("llm:thinking",o$),As("llm:chunk",l$),As("llm:response",c$),As("llm:tool-call",u$),As("llm:tool-result",d$),As("llm:error",f$),As("approval:request",h$),As("approval:response",m$),As("run:complete",p$),As("session:title-updated",g$),As("message:dequeued",v$),As("context:compacted",y$),As("service:event",x$)}function w$(e){b$();const t=[];return jw.forEach((n,r)=>{const s=e.on(r,n);t.push(s)}),()=>{t.forEach(n=>n.unsubscribe())}}const _$=b.createContext(null);function S$({children:e,middleware:t=[],enableLogging:n=!1,enableActivityLogging:r=!0,enableNotifications:s=!0,bus:i=VA}){b.useEffect(()=>{const u=[];let f;n&&(i.use(RE),u.push(RE)),r&&(i.use(LE),u.push(LE)),s&&(i.use(IE),u.push(IE));for(const h of t)i.use(h),u.push(h);return f=w$(i),()=>{for(const h of u)i.removeMiddleware(h);f?.()}},[i,n,r,s,t]);const o=b.useMemo(()=>({bus:i}),[i]);return l.jsx(_$.Provider,{value:o,children:e})}const o2=b.createContext(null);function k$({children:e}){const t=Of(r=>r.addApproval),n=b.useCallback(r=>{t(r)},[t]);return l.jsx(o2.Provider,{value:{handleApprovalRequest:n},children:e})}function N$(){const e=b.useContext(o2);if(!e)throw new Error("useApproval must be used within an ApprovalProvider");return e}var E$=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},j$=(e,t,n)=>(t=encodeURIComponent(t),E$(e,t,n)),C$=(e,t)=>(e=e.replace(/\/+$/,""),e=e+"/",t=t.replace(/^\/+/,""),e+t),e0=(e,t)=>{for(const[n,r]of Object.entries(t)){const s=new RegExp("/:"+n+"(?:{[^/]+})?\\??");e=e.replace(s,r?`/${r}`:"")}return e},T$=e=>{const t=new URLSearchParams;for(const[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r))for(const s of r)t.append(n,s);else t.set(n,r);return t},A$=(e,t)=>{switch(t){case"ws":return e.replace(/^http/,"ws");case"http":return e.replace(/^ws/,"http")}},l2=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,"/"):e.replace(/\/index(?=\?|$)/,"");function Nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function c2(e,t){if(!Nm(e)&&!Nm(t))return t;const n={...e};for(const r in t){const s=t[r];Nm(n[r])&&Nm(s)?n[r]=c2(n[r],s):n[r]=s}return n}var u2=(e,t)=>new Proxy(()=>{},{get(r,s){if(!(typeof s!="string"||s==="then"))return u2(e,[...t,s])},apply(r,s,i){return e({path:t,args:i})}}),R$=class{url;method;buildSearchParams;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t,n){this.url=e,this.method=t,this.buildSearchParams=n.buildSearchParams}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=this.buildSearchParams(e.query)),e.form){const u=new FormData;for(const[f,h]of Object.entries(e.form))if(Array.isArray(h))for(const p of h)u.append(f,p);else u.append(f,h);this.rBody=u}e.json&&(this.rBody=JSON.stringify(e.json),this.cType="application/json"),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase();const r={...e?.header,...typeof t?.headers=="function"?await t.headers():t?.headers};if(e?.cookie){const u=[];for(const[f,h]of Object.entries(e.cookie))u.push(j$(f,h,{path:"/"}));r.Cookie=u.join(",")}this.cType&&(r["Content-Type"]=this.cType);const s=new Headers(r??void 0);let i=this.url;i=l2(i),i=e0(i,this.pathParams),this.queryParams&&(i=i+"?"+this.queryParams.toString()),n=this.method.toUpperCase();const o=!(n==="GET"||n==="HEAD");return(t?.fetch||fetch)(i,{body:o?this.rBody:void 0,method:n,headers:s,...t?.init})}},M$=(e,t)=>u2(function n(r){const s=t?.buildSearchParams??T$,i=[...r.path],o=i.slice(-3).reverse();if(o[0]==="toString")return o[1]==="name"?o[2]||"":n.toString();if(o[0]==="valueOf")return o[1]==="name"?o[2]||"":n;let u="";if(/^\$/.test(o[0])){const g=i.pop();g&&(u=g.replace(/^\$/,""))}const f=i.join("/"),h=C$(e,f);if(u==="url"){let g=h;return r.args[0]&&(r.args[0].param&&(g=e0(h,r.args[0].param)),r.args[0].query&&(g=g+"?"+s(r.args[0].query).toString())),g=l2(g),new URL(g)}if(u==="ws"){const g=A$(r.args[0]&&r.args[0].param?e0(h,r.args[0].param):h,"ws"),v=new URL(g),y=r.args[0]?.query;return y&&Object.entries(y).forEach(([w,N])=>{Array.isArray(N)?N.forEach(k=>v.searchParams.append(w,k)):v.searchParams.set(w,N)}),((...w)=>t?.webSocket!==void 0&&typeof t.webSocket=="function"?t.webSocket(...w):new WebSocket(...w))(v.toString())}const p=new R$(h,u,{buildSearchParams:s});if(u){t??={};const g=c2(t,{...r.args[1]});return p.fetch(r.args[0],g)}return p},[]),O$=class extends Error{constructor(e,t){super(`SSE Error: ${e}`),this.status=e,this.body=t,this.name="SSEError"}};async function*I$(e,t){var n;if(!e.ok){const h=e.headers.get("content-type");let p;try{h&&h.includes("application/json")?p=await e.json():p=await e.text()}catch{p="Unknown error"}throw new O$(e.status,p)}const r=(n=e.body)==null?void 0:n.getReader();if(!r)throw new Error("Response body is null");const s=new globalThis.TextDecoder;let i="";const o=t?.signal;let u=!1;const f=()=>{u=!0,r.cancel().catch(()=>{})};if(o){if(o.aborted){r.cancel().catch(()=>{});return}o.addEventListener("abort",f)}try{for(;;){if(u||o?.aborted)return;const h=i.split(`
29
+ `),i=n.find(u=>u.type==="image"),o=n.find(u=>u.type==="file");if(s||n.length>0){const u=i&&typeof i.image=="string"?{image:i.image,mimeType:i.mimeType??"image/jpeg"}:void 0,f={id:og(),role:"user",content:s||"[attachment]",createdAt:Date.now(),sessionId:t,imageData:u,fileData:o?{data:typeof o.data=="string"?o.data:"",mimeType:o.mimeType,filename:o.filename}:void 0};r.addMessage(t,f)}}function y$(e){console.debug(`[handlers] Context compacted: ${e.originalTokens.toLocaleString()} → ${e.compactedTokens.toLocaleString()} tokens (${e.originalMessages} → ${e.compactedMessages} messages) via ${e.strategy}`)}function x$(e){const{service:t,event:n,toolCallId:r,sessionId:s,data:i}=e;if(t==="agent-spawner"&&n==="progress"&&r&&s){const o=un.getState(),u=i,h=o.getMessages(s).find(p=>p.role==="tool"&&p.toolCallId===r);h&&o.updateMessage(s,h.id,{subAgentProgress:{task:u.task,agentId:u.agentId,toolsCalled:u.toolsCalled,currentTool:u.currentTool,currentArgs:u.currentArgs}})}if(t==="todo"&&n==="updated"&&s){const o=i;i2.getState().setTodos(s,o.todos)}}function b$(){jw.clear(),As("llm:thinking",o$),As("llm:chunk",l$),As("llm:response",c$),As("llm:tool-call",u$),As("llm:tool-result",d$),As("llm:error",f$),As("approval:request",h$),As("approval:response",m$),As("run:complete",p$),As("session:title-updated",g$),As("message:dequeued",v$),As("context:compacted",y$),As("service:event",x$)}function w$(e){b$();const t=[];return jw.forEach((n,r)=>{const s=e.on(r,n);t.push(s)}),()=>{t.forEach(n=>n.unsubscribe())}}const _$=b.createContext(null);function S$({children:e,middleware:t=[],enableLogging:n=!1,enableActivityLogging:r=!0,enableNotifications:s=!0,bus:i=VA}){b.useEffect(()=>{const u=[];let f;n&&(i.use(RE),u.push(RE)),r&&(i.use(LE),u.push(LE)),s&&(i.use(IE),u.push(IE));for(const h of t)i.use(h),u.push(h);return f=w$(i),()=>{for(const h of u)i.removeMiddleware(h);f?.()}},[i,n,r,s,t]);const o=b.useMemo(()=>({bus:i}),[i]);return l.jsx(_$.Provider,{value:o,children:e})}const o2=b.createContext(null);function k$({children:e}){const t=Of(r=>r.addApproval),n=b.useCallback(r=>{t(r)},[t]);return l.jsx(o2.Provider,{value:{handleApprovalRequest:n},children:e})}function N$(){const e=b.useContext(o2);if(!e)throw new Error("useApproval must be used within an ApprovalProvider");return e}var E$=(e,t,n={})=>{let r=`${e}=${t}`;if(e.startsWith("__Secure-")&&!n.secure)throw new Error("__Secure- Cookie must have Secure attributes");if(e.startsWith("__Host-")){if(!n.secure)throw new Error("__Host- Cookie must have Secure attributes");if(n.path!=="/")throw new Error('__Host- Cookie must have Path attributes with "/"');if(n.domain)throw new Error("__Host- Cookie must not have Domain attributes")}for(const s of["domain","path"])if(n[s]&&/[;\r\n]/.test(n[s]))throw new Error(`${s} must not contain ";", "\\r", or "\\n"`);if(n&&typeof n.maxAge=="number"&&n.maxAge>=0){if(n.maxAge>3456e4)throw new Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");r+=`; Max-Age=${n.maxAge|0}`}if(n.domain&&n.prefix!=="host"&&(r+=`; Domain=${n.domain}`),n.path&&(r+=`; Path=${n.path}`),n.expires){if(n.expires.getTime()-Date.now()>3456e7)throw new Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");r+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(r+="; HttpOnly"),n.secure&&(r+="; Secure"),n.sameSite&&(r+=`; SameSite=${n.sameSite.charAt(0).toUpperCase()+n.sameSite.slice(1)}`),n.priority&&(r+=`; Priority=${n.priority.charAt(0).toUpperCase()+n.priority.slice(1)}`),n.partitioned){if(!n.secure)throw new Error("Partitioned Cookie must have Secure attributes");r+="; Partitioned"}return r},j$=(e,t,n)=>(t=encodeURIComponent(t),E$(e,t,n)),C$=(e,t)=>(e=e.replace(/\/+$/,""),e=e+"/",t=t.replace(/^\/+/,""),e+t),e0=(e,t)=>{for(const[n,r]of Object.entries(t)){const s=new RegExp("/:"+n+"(?:{[^/]+})?\\??");e=e.replace(s,r?`/${r}`:"")}return e},T$=e=>{const t=new URLSearchParams;for(const[n,r]of Object.entries(e))if(r!==void 0)if(Array.isArray(r))for(const s of r)t.append(n,s);else t.set(n,r);return t},A$=(e,t)=>{switch(t){case"ws":return e.replace(/^http/,"ws");case"http":return e.replace(/^ws/,"http")}},l2=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,"/"):e.replace(/\/index(?=\?|$)/,"");function Nm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function c2(e,t){if(!Nm(e)&&!Nm(t))return t;const n={...e};for(const r in t){const s=t[r];Nm(n[r])&&Nm(s)?n[r]=c2(n[r],s):n[r]=s}return n}var u2=(e,t)=>new Proxy(()=>{},{get(r,s){if(!(typeof s!="string"||s==="then"))return u2(e,[...t,s])},apply(r,s,i){return e({path:t,args:i})}}),R$=class{url;method;buildSearchParams;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t,n){this.url=e,this.method=t,this.buildSearchParams=n.buildSearchParams}fetch=async(e,t)=>{if(e){if(e.query&&(this.queryParams=this.buildSearchParams(e.query)),e.form){const u=new FormData;for(const[f,h]of Object.entries(e.form))if(h!==void 0)if(Array.isArray(h))for(const p of h)u.append(f,p);else u.append(f,h);this.rBody=u}e.json&&(this.rBody=JSON.stringify(e.json),this.cType="application/json"),e.param&&(this.pathParams=e.param)}let n=this.method.toUpperCase();const r={...e?.header,...typeof t?.headers=="function"?await t.headers():t?.headers};if(e?.cookie){const u=[];for(const[f,h]of Object.entries(e.cookie))u.push(j$(f,h,{path:"/"}));r.Cookie=u.join(",")}this.cType&&(r["Content-Type"]=this.cType);const s=new Headers(r??void 0);let i=this.url;i=l2(i),i=e0(i,this.pathParams),this.queryParams&&(i=i+"?"+this.queryParams.toString()),n=this.method.toUpperCase();const o=!(n==="GET"||n==="HEAD");return(t?.fetch||fetch)(i,{body:o?this.rBody:void 0,method:n,headers:s,...t?.init})}},M$=(e,t)=>u2(function n(r){const s=t?.buildSearchParams??T$,i=[...r.path],o=i.slice(-3).reverse();if(o[0]==="toString")return o[1]==="name"?o[2]||"":n.toString();if(o[0]==="valueOf")return o[1]==="name"?o[2]||"":n;let u="";if(/^\$/.test(o[0])){const g=i.pop();g&&(u=g.replace(/^\$/,""))}const f=i.join("/"),h=C$(e,f);if(u==="url"||u==="path"){let g=h;return r.args[0]&&(r.args[0].param&&(g=e0(h,r.args[0].param)),r.args[0].query&&(g=g+"?"+s(r.args[0].query).toString())),g=l2(g),u==="url"?new URL(g):g.slice(e.replace(/\/+$/,"").length).replace(/^\/?/,"/")}if(u==="ws"){const g=A$(r.args[0]&&r.args[0].param?e0(h,r.args[0].param):h,"ws"),v=new URL(g),y=r.args[0]?.query;return y&&Object.entries(y).forEach(([w,N])=>{Array.isArray(N)?N.forEach(k=>v.searchParams.append(w,k)):v.searchParams.set(w,N)}),((...w)=>t?.webSocket!==void 0&&typeof t.webSocket=="function"?t.webSocket(...w):new WebSocket(...w))(v.toString())}const p=new R$(h,u,{buildSearchParams:s});if(u){t??={};const g=c2(t,{...r.args[1]});return p.fetch(r.args[0],g)}return p},[]),O$=class extends Error{constructor(e,t){super(`SSE Error: ${e}`),this.status=e,this.body=t,this.name="SSEError"}};async function*I$(e,t){var n;if(!e.ok){const h=e.headers.get("content-type");let p;try{h&&h.includes("application/json")?p=await e.json():p=await e.text()}catch{p="Unknown error"}throw new O$(e.status,p)}const r=(n=e.body)==null?void 0:n.getReader();if(!r)throw new Error("Response body is null");const s=new globalThis.TextDecoder;let i="";const o=t?.signal;let u=!1;const f=()=>{u=!0,r.cancel().catch(()=>{})};if(o){if(o.aborted){r.cancel().catch(()=>{});return}o.addEventListener("abort",f)}try{for(;;){if(u||o?.aborted)return;const h=i.split(`
30
30
 
31
31
  `);if(h.length>1){const v=h.shift();i=h.join(`
32
32