rivet-design 0.10.2 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mcp/agent-variants/WorktreeOrchestrator.d.ts +5 -0
- package/dist/mcp/agent-variants/WorktreeOrchestrator.d.ts.map +1 -1
- package/dist/mcp/agent-variants/WorktreeOrchestrator.js +111 -8
- package/dist/mcp/agent-variants/WorktreeOrchestrator.js.map +1 -1
- package/dist/mcp/agent-variants/WorktreeOrchestrator.testHelpers.d.ts +5 -0
- package/dist/mcp/agent-variants/WorktreeOrchestrator.testHelpers.d.ts.map +1 -1
- package/dist/mcp/agent-variants/WorktreeOrchestrator.testHelpers.js +8 -0
- package/dist/mcp/agent-variants/WorktreeOrchestrator.testHelpers.js.map +1 -1
- package/dist/services/AuthService.d.ts.map +1 -1
- package/dist/services/AuthService.js +7 -0
- package/dist/services/AuthService.js.map +1 -1
- package/dist/services/WorktreeManager.d.ts.map +1 -1
- package/dist/services/WorktreeManager.js +30 -9
- package/dist/services/WorktreeManager.js.map +1 -1
- package/package.json +1 -1
- package/src/ui/dist/assets/{main-CMk2ORlB.js → main-DshwLV4N.js} +3 -3
- package/src/ui/dist/index.html +1 -1
|
@@ -14,7 +14,7 @@ var CU=Object.defineProperty;var nS=e=>{throw TypeError(e)};var EU=(e,t,n)=>t in
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var sS;function TU(){if(sS)return Jf;sS=1;var e=j8(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function o(a,l,u){var f,p={},m=null,g=null;u!==void 0&&(m=""+u),l.key!==void 0&&(m=""+l.key),l.ref!==void 0&&(g=l.ref);for(f in l)r.call(l,f)&&!s.hasOwnProperty(f)&&(p[f]=l[f]);if(a&&a.defaultProps)for(f in l=a.defaultProps,l)p[f]===void 0&&(p[f]=l[f]);return{$$typeof:t,type:a,key:m,ref:g,props:p,_owner:i.current}}return Jf.Fragment=n,Jf.jsx=o,Jf.jsxs=o,Jf}var oS;function PU(){return oS||(oS=1,fb.exports=TU()),fb.exports}var y=PU(),h=j8();const xe=Wc(h),QR=SU({__proto__:null,default:xe},[h]);var Gp=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fc,Ya,bd,FR,IU=(FR=class extends Gp{constructor(){super();_t(this,fc);_t(this,Ya);_t(this,bd);tt(this,bd,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){se(this,Ya)||this.setEventListener(se(this,bd))}onUnsubscribe(){var t;this.hasListeners()||((t=se(this,Ya))==null||t.call(this),tt(this,Ya,void 0))}setEventListener(t){var n;tt(this,bd,t),(n=se(this,Ya))==null||n.call(this),tt(this,Ya,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){se(this,fc)!==t&&(tt(this,fc,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof se(this,fc)=="boolean"?se(this,fc):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},fc=new WeakMap,Ya=new WeakMap,bd=new WeakMap,FR),F8=new IU,RU={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Xa,L8,OR,MU=(OR=class{constructor(){_t(this,Xa,RU);_t(this,L8,!1)}setTimeoutProvider(e){tt(this,Xa,e)}setTimeout(e,t){return se(this,Xa).setTimeout(e,t)}clearTimeout(e){se(this,Xa).clearTimeout(e)}setInterval(e,t){return se(this,Xa).setInterval(e,t)}clearInterval(e){se(this,Xa).clearInterval(e)}},Xa=new WeakMap,L8=new WeakMap,OR),ac=new MU;function $U(e){setTimeout(e,0)}var DU=typeof window>"u"||"Deno"in globalThis;function hi(){}function NU(e,t){return typeof e=="function"?e(t):e}function kw(e){return typeof e=="number"&&e>=0&&e!==1/0}function JR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function al(e,t){return typeof e=="function"?e(t):e}function Mi(e,t){return typeof e=="function"?e(t):e}function aS(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==O8(o,t.options))return!1}else if(!op(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||i&&i!==t.state.fetchStatus||s&&!s(t))}function lS(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(sp(t.options.mutationKey)!==sp(s))return!1}else if(!op(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function O8(e,t){return((t==null?void 0:t.queryKeyHashFn)||sp)(e)}function sp(e){return JSON.stringify(e,(t,n)=>Ew(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function op(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>op(e[n],t[n])):!1}var LU=Object.prototype.hasOwnProperty;function eM(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cS(e)&&cS(t);if(!r&&!(Ew(e)&&Ew(t)))return t;const s=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,l=r?new Array(a):{};let u=0;for(let f=0;f<a;f++){const p=r?f:o[f],m=e[p],g=t[p];if(m===g){l[p]=m,(r?f<s:LU.call(e,p))&&u++;continue}if(m===null||g===null||typeof m!="object"||typeof g!="object"){l[p]=g;continue}const b=eM(m,g,n+1);l[p]=b,b===m&&u++}return s===a&&u===s?e:l}function Cw(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function cS(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ew(e){if(!uS(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!uS(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function uS(e){return Object.prototype.toString.call(e)==="[object Object]"}function jU(e){return new Promise(t=>{ac.setTimeout(t,e)})}function Sw(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?eM(e,t):t}function FU(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function OU(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var V8=Symbol();function tM(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===V8?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nM(e,t){return typeof e=="function"?e(...t):!!e}function VU(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??(i=t()),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var ap=(()=>{let e=()=>DU;return{isServer(){return e()},setIsServer(t){e=t}}})();function Aw(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var HU=$U;function BU(){let e=[],t=0,n=a=>{a()},r=a=>{a()},i=HU;const s=a=>{t?e.push(a):i(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&i(()=>{r(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{s(()=>{a(...l)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{i=a}}}var Rr=BU(),xd,Qa,wd,VR,zU=(VR=class extends Gp{constructor(){super();_t(this,xd,!0);_t(this,Qa);_t(this,wd);tt(this,wd,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){se(this,Qa)||this.setEventListener(se(this,wd))}onUnsubscribe(){var t;this.hasListeners()||((t=se(this,Qa))==null||t.call(this),tt(this,Qa,void 0))}setEventListener(t){var n;tt(this,wd,t),(n=se(this,Qa))==null||n.call(this),tt(this,Qa,t(this.setOnline.bind(this)))}setOnline(t){se(this,xd)!==t&&(tt(this,xd,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return se(this,xd)}},xd=new WeakMap,Qa=new WeakMap,wd=new WeakMap,VR),qg=new zU;function UU(e){return Math.min(1e3*2**e,3e4)}function rM(e){return(e??"online")==="online"?qg.isOnline():!0}var Tw=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function iM(e){let t=!1,n=0,r;const i=Aw(),s=()=>i.status!=="pending",o=x=>{var k;if(!s()){const w=new Tw(x);m(w),(k=e.onCancel)==null||k.call(e,w)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>F8.isFocused()&&(e.networkMode==="always"||qg.isOnline())&&e.canRun(),f=()=>rM(e.networkMode)&&e.canRun(),p=x=>{s()||(r==null||r(),i.resolve(x))},m=x=>{s()||(r==null||r(),i.reject(x))},g=()=>new Promise(x=>{var k;r=w=>{(s()||u())&&x(w)},(k=e.onPause)==null||k.call(e)}).then(()=>{var x;r=void 0,s()||(x=e.onContinue)==null||x.call(e)}),b=()=>{if(s())return;let x;const k=n===0?e.initialPromise:void 0;try{x=k??e.fn()}catch(w){x=Promise.reject(w)}Promise.resolve(x).then(p).catch(w=>{var P;if(s())return;const C=e.retry??(ap.isServer()?0:3),E=e.retryDelay??UU,A=typeof E=="function"?E(n,w):E,R=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,w);if(t||!R){m(w);return}n++,(P=e.onFail)==null||P.call(e,n,w),jU(A).then(()=>u()?void 0:g()).then(()=>{t?m(w):b()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r==null||r(),i),cancelRetry:a,continueRetry:l,canStart:f,start:()=>(f()?b():g().then(b),i)}}var hc,HR,sM=(HR=class{constructor(){_t(this,hc)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kw(this.gcTime)&&tt(this,hc,ac.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ap.isServer()?1/0:300*1e3))}clearGcTimeout(){se(this,hc)!==void 0&&(ac.clearTimeout(se(this,hc)),tt(this,hc,void 0))}},hc=new WeakMap,HR);function ZU(e){return{onFetch:(t,n)=>{var f,p,m,g,b;const r=t.options,i=(m=(p=(f=t.fetchOptions)==null?void 0:f.meta)==null?void 0:p.fetchMore)==null?void 0:m.direction,s=((g=t.state.data)==null?void 0:g.pages)||[],o=((b=t.state.data)==null?void 0:b.pageParams)||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let x=!1;const k=E=>{VU(E,()=>t.signal,()=>x=!0)},w=tM(t.options,t.fetchOptions),C=async(E,A,R)=>{if(x)return Promise.reject(t.signal.reason);if(A==null&&E.pages.length)return Promise.resolve(E);const I=(()=>{const D={client:t.client,queryKey:t.queryKey,pageParam:A,direction:R?"backward":"forward",meta:t.options.meta};return k(D),D})(),T=await w(I),{maxPages:L}=t.options,M=R?OU:FU;return{pages:M(E.pages,T,L),pageParams:M(E.pageParams,A,L)}};if(i&&s.length){const E=i==="backward",A=E?WU:dS,R={pages:s,pageParams:o},P=A(r,R);a=await C(R,P,E)}else{const E=e??s.length;do{const A=l===0?o[0]??r.initialPageParam:dS(r,a);if(l>0&&A==null)break;a=await C(a,A),l++}while(l<E)}return a};t.options.persister?t.fetchFn=()=>{var x,k;return(k=(x=t.options).persister)==null?void 0:k.call(x,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function dS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function WU(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var _d,pc,kd,Yi,mc,xr,Bp,gc,Ri,oM,jo,BR,GU=(BR=class extends sM{constructor(t){super();_t(this,Ri);_t(this,_d);_t(this,pc);_t(this,kd);_t(this,Yi);_t(this,mc);_t(this,xr);_t(this,Bp);_t(this,gc);tt(this,gc,!1),tt(this,Bp,t.defaultOptions),this.setOptions(t.options),this.observers=[],tt(this,mc,t.client),tt(this,Yi,se(this,mc).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,tt(this,pc,hS(this.options)),this.state=t.state??se(this,pc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return se(this,_d)}get promise(){var t;return(t=se(this,xr))==null?void 0:t.promise}setOptions(t){if(this.options={...se(this,Bp),...t},t!=null&&t._type&&tt(this,_d,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=hS(this.options);n.data!==void 0&&(this.setState(fS(n.data,n.dataUpdatedAt)),tt(this,pc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&se(this,Yi).remove(this)}setData(t,n){const r=Sw(this.state.data,t,this.options);return Xt(this,Ri,jo).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){Xt(this,Ri,jo).call(this,{type:"setState",state:t})}cancel(t){var r,i;const n=(r=se(this,xr))==null?void 0:r.promise;return(i=se(this,xr))==null||i.cancel(t),n?n.then(hi).catch(hi):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return se(this,pc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Mi(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===V8||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>al(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!JR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=se(this,xr))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=se(this,xr))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),se(this,Yi).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(se(this,xr)&&(se(this,gc)||Xt(this,Ri,oM).call(this)?se(this,xr).cancel({revert:!0}):se(this,xr).cancelRetry()),this.scheduleGc()),se(this,Yi).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Xt(this,Ri,jo).call(this,{type:"invalidate"})}async fetch(t,n){var u,f,p,m,g,b,x,k,w,C,E;if(this.state.fetchStatus!=="idle"&&((u=se(this,xr))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(se(this,xr))return se(this,xr).continueRetry(),se(this,xr).promise}if(t&&this.setOptions(t),!this.options.queryFn){const A=this.observers.find(R=>R.options.queryFn);A&&this.setOptions(A.options)}const r=new AbortController,i=A=>{Object.defineProperty(A,"signal",{enumerable:!0,get:()=>(tt(this,gc,!0),r.signal)})},s=()=>{const A=tM(this.options,n),P=(()=>{const I={client:se(this,mc),queryKey:this.queryKey,meta:this.meta};return i(I),I})();return tt(this,gc,!1),this.options.persister?this.options.persister(A,P,this):A(P)},a=(()=>{const A={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:se(this,mc),state:this.state,fetchFn:s};return i(A),A})(),l=se(this,_d)==="infinite"?ZU(this.options.pages):this.options.behavior;l==null||l.onFetch(a,this),tt(this,kd,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((f=a.fetchOptions)==null?void 0:f.meta))&&Xt(this,Ri,jo).call(this,{type:"fetch",meta:(p=a.fetchOptions)==null?void 0:p.meta}),tt(this,xr,iM({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:A=>{A instanceof Tw&&A.revert&&this.setState({...se(this,kd),fetchStatus:"idle"}),r.abort()},onFail:(A,R)=>{Xt(this,Ri,jo).call(this,{type:"failed",failureCount:A,error:R})},onPause:()=>{Xt(this,Ri,jo).call(this,{type:"pause"})},onContinue:()=>{Xt(this,Ri,jo).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const A=await se(this,xr).start();if(A===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(A),(g=(m=se(this,Yi).config).onSuccess)==null||g.call(m,A,this),(x=(b=se(this,Yi).config).onSettled)==null||x.call(b,A,this.state.error,this),A}catch(A){if(A instanceof Tw){if(A.silent)return se(this,xr).promise;if(A.revert){if(this.state.data===void 0)throw A;return this.state.data}}throw Xt(this,Ri,jo).call(this,{type:"error",error:A}),(w=(k=se(this,Yi).config).onError)==null||w.call(k,A,this),(E=(C=se(this,Yi).config).onSettled)==null||E.call(C,this.state.data,A,this),A}finally{this.scheduleGc()}}},_d=new WeakMap,pc=new WeakMap,kd=new WeakMap,Yi=new WeakMap,mc=new WeakMap,xr=new WeakMap,Bp=new WeakMap,gc=new WeakMap,Ri=new WeakSet,oM=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},jo=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...aM(r.data,this.options),fetchMeta:t.meta??null};case"success":const i={...r,...fS(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return tt(this,kd,t.manual?i:void 0),i;case"error":const s=t.error;return{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Rr.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),se(this,Yi).notify({query:this,type:"updated",action:t})})},BR);function aM(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:rM(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function fS(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function hS(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ci,tn,zp,Yr,vc,Cd,Zo,Ja,Up,Ed,Sd,yc,bc,el,Ad,gn,Ch,Pw,Iw,Rw,Mw,$w,Dw,Nw,lM,zR,qU=(zR=class extends Gp{constructor(t,n){super();_t(this,gn);_t(this,ci);_t(this,tn);_t(this,zp);_t(this,Yr);_t(this,vc);_t(this,Cd);_t(this,Zo);_t(this,Ja);_t(this,Up);_t(this,Ed);_t(this,Sd);_t(this,yc);_t(this,bc);_t(this,el);_t(this,Ad,new Set);this.options=n,tt(this,ci,t),tt(this,Ja,null),tt(this,Zo,Aw()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(se(this,tn).addObserver(this),pS(se(this,tn),this.options)?Xt(this,gn,Ch).call(this):this.updateResult(),Xt(this,gn,Mw).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Lw(se(this,tn),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Lw(se(this,tn),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Xt(this,gn,$w).call(this),Xt(this,gn,Dw).call(this),se(this,tn).removeObserver(this)}setOptions(t){const n=this.options,r=se(this,tn);if(this.options=se(this,ci).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Mi(this.options.enabled,se(this,tn))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Xt(this,gn,Nw).call(this),se(this,tn).setOptions(this.options),n._defaulted&&!Cw(this.options,n)&&se(this,ci).getQueryCache().notify({type:"observerOptionsUpdated",query:se(this,tn),observer:this});const i=this.hasListeners();i&&mS(se(this,tn),r,this.options,n)&&Xt(this,gn,Ch).call(this),this.updateResult(),i&&(se(this,tn)!==r||Mi(this.options.enabled,se(this,tn))!==Mi(n.enabled,se(this,tn))||al(this.options.staleTime,se(this,tn))!==al(n.staleTime,se(this,tn)))&&Xt(this,gn,Pw).call(this);const s=Xt(this,gn,Iw).call(this);i&&(se(this,tn)!==r||Mi(this.options.enabled,se(this,tn))!==Mi(n.enabled,se(this,tn))||s!==se(this,el))&&Xt(this,gn,Rw).call(this,s)}getOptimisticResult(t){const n=se(this,ci).getQueryCache().build(se(this,ci),t),r=this.createResult(n,t);return YU(this,r)&&(tt(this,Yr,r),tt(this,Cd,this.options),tt(this,vc,se(this,tn).state)),r}getCurrentResult(){return se(this,Yr)}trackResult(t,n){return new Proxy(t,{get:(r,i)=>(this.trackProp(i),n==null||n(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&se(this,Zo).status==="pending"&&se(this,Zo).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(t){se(this,Ad).add(t)}getCurrentQuery(){return se(this,tn)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=se(this,ci).defaultQueryOptions(t),r=se(this,ci).getQueryCache().build(se(this,ci),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Xt(this,gn,Ch).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),se(this,Yr)))}createResult(t,n){var L;const r=se(this,tn),i=this.options,s=se(this,Yr),o=se(this,vc),a=se(this,Cd),u=t!==r?t.state:se(this,zp),{state:f}=t;let p={...f},m=!1,g;if(n._optimisticResults){const M=this.hasListeners(),D=!M&&pS(t,n),O=M&&mS(t,r,n,i);(D||O)&&(p={...p,...aM(f.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:b,errorUpdatedAt:x,status:k}=p;g=p.data;let w=!1;if(n.placeholderData!==void 0&&g===void 0&&k==="pending"){let M;s!=null&&s.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(M=s.data,w=!0):M=typeof n.placeholderData=="function"?n.placeholderData((L=se(this,Sd))==null?void 0:L.state.data,se(this,Sd)):n.placeholderData,M!==void 0&&(k="success",g=Sw(s==null?void 0:s.data,M,n),m=!0)}if(n.select&&g!==void 0&&!w)if(s&&g===(o==null?void 0:o.data)&&n.select===se(this,Up))g=se(this,Ed);else try{tt(this,Up,n.select),g=n.select(g),g=Sw(s==null?void 0:s.data,g,n),tt(this,Ed,g),tt(this,Ja,null)}catch(M){tt(this,Ja,M)}se(this,Ja)&&(b=se(this,Ja),g=se(this,Ed),x=Date.now(),k="error");const C=p.fetchStatus==="fetching",E=k==="pending",A=k==="error",R=E&&C,P=g!==void 0,T={status:k,fetchStatus:p.fetchStatus,isPending:E,isSuccess:k==="success",isError:A,isInitialLoading:R,isLoading:R,data:g,dataUpdatedAt:p.dataUpdatedAt,error:b,errorUpdatedAt:x,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:A&&!P,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:A&&P,isStale:H8(t,n),refetch:this.refetch,promise:se(this,Zo),isEnabled:Mi(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const M=T.data!==void 0,D=T.status==="error"&&!M,O=V=>{D?V.reject(T.error):M&&V.resolve(T.data)},F=()=>{const V=tt(this,Zo,T.promise=Aw());O(V)},Z=se(this,Zo);switch(Z.status){case"pending":t.queryHash===r.queryHash&&O(Z);break;case"fulfilled":(D||T.data!==Z.value)&&F();break;case"rejected":(!D||T.error!==Z.reason)&&F();break}}return T}updateResult(){const t=se(this,Yr),n=this.createResult(se(this,tn),this.options);if(tt(this,vc,se(this,tn).state),tt(this,Cd,this.options),se(this,vc).data!==void 0&&tt(this,Sd,se(this,tn)),Cw(n,t))return;tt(this,Yr,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,s=typeof i=="function"?i():i;if(s==="all"||!s&&!se(this,Ad).size)return!0;const o=new Set(s??se(this,Ad));return this.options.throwOnError&&o.add("error"),Object.keys(se(this,Yr)).some(a=>{const l=a;return se(this,Yr)[l]!==t[l]&&o.has(l)})};Xt(this,gn,lM).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Xt(this,gn,Mw).call(this)}},ci=new WeakMap,tn=new WeakMap,zp=new WeakMap,Yr=new WeakMap,vc=new WeakMap,Cd=new WeakMap,Zo=new WeakMap,Ja=new WeakMap,Up=new WeakMap,Ed=new WeakMap,Sd=new WeakMap,yc=new WeakMap,bc=new WeakMap,el=new WeakMap,Ad=new WeakMap,gn=new WeakSet,Ch=function(t){Xt(this,gn,Nw).call(this);let n=se(this,tn).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(hi)),n},Pw=function(){Xt(this,gn,$w).call(this);const t=al(this.options.staleTime,se(this,tn));if(ap.isServer()||se(this,Yr).isStale||!kw(t))return;const r=JR(se(this,Yr).dataUpdatedAt,t)+1;tt(this,yc,ac.setTimeout(()=>{se(this,Yr).isStale||this.updateResult()},r))},Iw=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(se(this,tn)):this.options.refetchInterval)??!1},Rw=function(t){Xt(this,gn,Dw).call(this),tt(this,el,t),!(ap.isServer()||Mi(this.options.enabled,se(this,tn))===!1||!kw(se(this,el))||se(this,el)===0)&&tt(this,bc,ac.setInterval(()=>{(this.options.refetchIntervalInBackground||F8.isFocused())&&Xt(this,gn,Ch).call(this)},se(this,el)))},Mw=function(){Xt(this,gn,Pw).call(this),Xt(this,gn,Rw).call(this,Xt(this,gn,Iw).call(this))},$w=function(){se(this,yc)!==void 0&&(ac.clearTimeout(se(this,yc)),tt(this,yc,void 0))},Dw=function(){se(this,bc)!==void 0&&(ac.clearInterval(se(this,bc)),tt(this,bc,void 0))},Nw=function(){const t=se(this,ci).getQueryCache().build(se(this,ci),this.options);if(t===se(this,tn))return;const n=se(this,tn);tt(this,tn,t),tt(this,zp,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},lM=function(t){Rr.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(se(this,Yr))}),se(this,ci).getQueryCache().notify({query:se(this,tn),type:"observerResultsUpdated"})})},zR);function KU(e,t){return Mi(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&Mi(t.retryOnMount,e)===!1)}function pS(e,t){return KU(e,t)||e.state.data!==void 0&&Lw(e,t,t.refetchOnMount)}function Lw(e,t,n){if(Mi(t.enabled,e)!==!1&&al(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&H8(e,t)}return!1}function mS(e,t,n,r){return(e!==t||Mi(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&H8(e,n)}function H8(e,t){return Mi(t.enabled,e)!==!1&&e.isStaleByTime(al(t.staleTime,e))}function YU(e,t){return!Cw(e.getCurrentResult(),t)}var Zp,Js,Hr,xc,eo,za,UR,XU=(UR=class extends sM{constructor(t){super();_t(this,eo);_t(this,Zp);_t(this,Js);_t(this,Hr);_t(this,xc);tt(this,Zp,t.client),this.mutationId=t.mutationId,tt(this,Hr,t.mutationCache),tt(this,Js,[]),this.state=t.state||QU(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){se(this,Js).includes(t)||(se(this,Js).push(t),this.clearGcTimeout(),se(this,Hr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){tt(this,Js,se(this,Js).filter(n=>n!==t)),this.scheduleGc(),se(this,Hr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){se(this,Js).length||(this.state.status==="pending"?this.scheduleGc():se(this,Hr).remove(this))}continue(){var t;return((t=se(this,xc))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,a,l,u,f,p,m,g,b,x,k,w,C,E,A,R,P,I;const n=()=>{Xt(this,eo,za).call(this,{type:"continue"})},r={client:se(this,Zp),meta:this.options.meta,mutationKey:this.options.mutationKey};tt(this,xc,iM({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(T,L)=>{Xt(this,eo,za).call(this,{type:"failed",failureCount:T,error:L})},onPause:()=>{Xt(this,eo,za).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>se(this,Hr).canRun(this)}));const i=this.state.status==="pending",s=!se(this,xc).canStart();try{if(i)n();else{Xt(this,eo,za).call(this,{type:"pending",variables:t,isPaused:s}),se(this,Hr).config.onMutate&&await se(this,Hr).config.onMutate(t,this,r);const L=await((a=(o=this.options).onMutate)==null?void 0:a.call(o,t,r));L!==this.state.context&&Xt(this,eo,za).call(this,{type:"pending",context:L,variables:t,isPaused:s})}const T=await se(this,xc).start();return await((u=(l=se(this,Hr).config).onSuccess)==null?void 0:u.call(l,T,t,this.state.context,this,r)),await((p=(f=this.options).onSuccess)==null?void 0:p.call(f,T,t,this.state.context,r)),await((g=(m=se(this,Hr).config).onSettled)==null?void 0:g.call(m,T,null,this.state.variables,this.state.context,this,r)),await((x=(b=this.options).onSettled)==null?void 0:x.call(b,T,null,t,this.state.context,r)),Xt(this,eo,za).call(this,{type:"success",data:T}),T}catch(T){try{await((w=(k=se(this,Hr).config).onError)==null?void 0:w.call(k,T,t,this.state.context,this,r))}catch(L){Promise.reject(L)}try{await((E=(C=this.options).onError)==null?void 0:E.call(C,T,t,this.state.context,r))}catch(L){Promise.reject(L)}try{await((R=(A=se(this,Hr).config).onSettled)==null?void 0:R.call(A,void 0,T,this.state.variables,this.state.context,this,r))}catch(L){Promise.reject(L)}try{await((I=(P=this.options).onSettled)==null?void 0:I.call(P,void 0,T,t,this.state.context,r))}catch(L){Promise.reject(L)}throw Xt(this,eo,za).call(this,{type:"error",error:T}),T}finally{se(this,Hr).runNext(this)}}},Zp=new WeakMap,Js=new WeakMap,Hr=new WeakMap,xc=new WeakMap,eo=new WeakSet,za=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Rr.batch(()=>{se(this,Js).forEach(r=>{r.onMutationUpdate(t)}),se(this,Hr).notify({mutation:this,type:"updated",action:t})})},UR);function QU(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Wo,ks,Wp,ZR,JU=(ZR=class extends Gp{constructor(t={}){super();_t(this,Wo);_t(this,ks);_t(this,Wp);this.config=t,tt(this,Wo,new Set),tt(this,ks,new Map),tt(this,Wp,0)}build(t,n,r){const i=new XU({client:t,mutationCache:this,mutationId:++ym(this,Wp)._,options:t.defaultMutationOptions(n),state:r});return this.add(i),i}add(t){se(this,Wo).add(t);const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n);r?r.push(t):se(this,ks).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(se(this,Wo).delete(t)){const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n);if(r)if(r.length>1){const i=r.indexOf(t);i!==-1&&r.splice(i,1)}else r[0]===t&&se(this,ks).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n),i=r==null?void 0:r.find(s=>s.state.status==="pending");return!i||i===t}else return!0}runNext(t){var r;const n=xm(t);if(typeof n=="string"){const i=(r=se(this,ks).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Rr.batch(()=>{se(this,Wo).forEach(t=>{this.notify({type:"removed",mutation:t})}),se(this,Wo).clear(),se(this,ks).clear()})}getAll(){return Array.from(se(this,Wo))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>lS(n,r))}findAll(t={}){return this.getAll().filter(n=>lS(t,n))}notify(t){Rr.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Rr.batch(()=>Promise.all(t.map(n=>n.continue().catch(hi))))}},Wo=new WeakMap,ks=new WeakMap,Wp=new WeakMap,ZR);function xm(e){var t;return(t=e.options.scope)==null?void 0:t.id}var to,WR,eZ=(WR=class extends Gp{constructor(t={}){super();_t(this,to);this.config=t,tt(this,to,new Map)}build(t,n,r){const i=n.queryKey,s=n.queryHash??O8(i,n);let o=this.get(s);return o||(o=new GU({client:t,queryKey:i,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(i)}),this.add(o)),o}add(t){se(this,to).has(t.queryHash)||(se(this,to).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=se(this,to).get(t.queryHash);n&&(t.destroy(),n===t&&se(this,to).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Rr.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return se(this,to).get(t)}getAll(){return[...se(this,to).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>aS(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>aS(t,r)):n}notify(t){Rr.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Rr.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Rr.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},to=new WeakMap,WR),Zn,tl,nl,Td,Pd,rl,Id,Rd,GR,tZ=(GR=class{constructor(e={}){_t(this,Zn);_t(this,tl);_t(this,nl);_t(this,Td);_t(this,Pd);_t(this,rl);_t(this,Id);_t(this,Rd);tt(this,Zn,e.queryCache||new eZ),tt(this,tl,e.mutationCache||new JU),tt(this,nl,e.defaultOptions||{}),tt(this,Td,new Map),tt(this,Pd,new Map),tt(this,rl,0)}mount(){ym(this,rl)._++,se(this,rl)===1&&(tt(this,Id,F8.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Zn).onFocus())})),tt(this,Rd,qg.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Zn).onOnline())})))}unmount(){var e,t;ym(this,rl)._--,se(this,rl)===0&&((e=se(this,Id))==null||e.call(this),tt(this,Id,void 0),(t=se(this,Rd))==null||t.call(this),tt(this,Rd,void 0))}isFetching(e){return se(this,Zn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return se(this,tl).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=se(this,Zn).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=se(this,Zn).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(al(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return se(this,Zn).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=se(this,Zn).get(r.queryHash),s=i==null?void 0:i.state.data,o=NU(t,s);if(o!==void 0)return se(this,Zn).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return Rr.batch(()=>se(this,Zn).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=se(this,Zn).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=se(this,Zn);Rr.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=se(this,Zn);return Rr.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Rr.batch(()=>se(this,Zn).findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(hi).catch(hi)}invalidateQueries(e,t={}){return Rr.batch(()=>(se(this,Zn).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Rr.batch(()=>se(this,Zn).findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(hi)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(hi)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=se(this,Zn).build(this,t);return n.isStaleByTime(al(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(hi).catch(hi)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(hi).catch(hi)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return qg.isOnline()?se(this,tl).resumePausedMutations():Promise.resolve()}getQueryCache(){return se(this,Zn)}getMutationCache(){return se(this,tl)}getDefaultOptions(){return se(this,nl)}setDefaultOptions(e){tt(this,nl,e)}setQueryDefaults(e,t){se(this,Td).set(sp(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...se(this,Td).values()],n={};return t.forEach(r=>{op(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){se(this,Pd).set(sp(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...se(this,Pd).values()],n={};return t.forEach(r=>{op(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...se(this,nl).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=O8(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===V8&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...se(this,nl).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){se(this,Zn).clear(),se(this,tl).clear()}},Zn=new WeakMap,tl=new WeakMap,nl=new WeakMap,Td=new WeakMap,Pd=new WeakMap,rl=new WeakMap,Id=new WeakMap,Rd=new WeakMap,GR),cM=h.createContext(void 0),nZ=e=>{const t=h.useContext(cM);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rZ=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),y.jsx(cM.Provider,{value:e,children:t})),uM=h.createContext(!1),iZ=()=>h.useContext(uM);uM.Provider;function sZ(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var oZ=h.createContext(sZ()),aZ=()=>h.useContext(oZ),lZ=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?nM(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},cZ=e=>{h.useEffect(()=>{e.clearReset()},[e])},uZ=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||nM(n,[e.error,r])),dZ=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},fZ=(e,t)=>e.isLoading&&e.isFetching&&!t,hZ=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,gS=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function pZ(e,t,n){var g,b,x,k;const r=iZ(),i=aZ(),s=nZ(),o=s.defaultQueryOptions(e);(b=(g=s.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||b.call(g,o);const a=s.getQueryCache().get(o.queryHash),l=e.subscribed!==!1;o._optimisticResults=r?"isRestoring":l?"optimistic":void 0,dZ(o),lZ(o,i,a),cZ(i);const u=!s.getQueryCache().get(o.queryHash),[f]=h.useState(()=>new t(s,o)),p=f.getOptimisticResult(o),m=!r&&l;if(h.useSyncExternalStore(h.useCallback(w=>{const C=m?f.subscribe(Rr.batchCalls(w)):hi;return f.updateResult(),C},[f,m]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),h.useEffect(()=>{f.setOptions(o)},[o,f]),hZ(o,p))throw gS(o,f,i);if(uZ({result:p,errorResetBoundary:i,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw p.error;if((k=(x=s.getDefaultOptions().queries)==null?void 0:x._experimental_afterQuery)==null||k.call(x,o,p),o.experimental_prefetchInRender&&!ap.isServer()&&fZ(p,r)){const w=u?gS(o,f,i):a==null?void 0:a.promise;w==null||w.catch(hi).finally(()=>{f.updateResult()})}return o.notifyOnChangeProps?p:f.trackResult(p)}function mZ(e,t){return pZ(e,qU)}var me=typeof window<"u"?window:void 0,hr=typeof globalThis<"u"?globalThis:me;typeof self>"u"&&(hr.self=hr),typeof File>"u"&&(hr.File=function(){});var Ni=hr==null?void 0:hr.navigator,Ze=hr==null?void 0:hr.document,Pr=hr==null?void 0:hr.location,jw=hr==null?void 0:hr.fetch,Fw=hr!=null&&hr.XMLHttpRequest&&"withCredentials"in new hr.XMLHttpRequest?hr.XMLHttpRequest:void 0,vS=hr==null?void 0:hr.AbortController,gZ=hr==null?void 0:hr.CompressionStream,ui=Ni==null?void 0:Ni.userAgent,gt=me??{},yS="1.379.1",wr={DEBUG:!1,LIB_VERSION:yS,LIB_NAME:"web",JS_SDK_VERSION:yS};function bS(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(u){return void n(u)}a.done?t(l):Promise.resolve(l).then(r,i)}function $i(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(l){bS(s,r,i,o,a,"next",l)}function a(l){bS(s,r,i,o,a,"throw",l)}o(void 0)}))}}function Oe(){return Oe=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Oe.apply(null,arguments)}function dM(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var eh,xS=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),vZ=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],fM="NativeGzipValidationError",Ow=e=>e.length>=2&&e[0]===31&&e[1]===139,wS=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",wm=e=>{var t=new Error("Native gzip produced invalid output: "+e);throw t.name=fM,t},yZ=(function(){var e=$i((function*(t,n){18>t.size&&wm("too-short");var r=new Uint8Array(yield t.slice(0,10).arrayBuffer());Ow(r)&&r[2]===8||wm("invalid-header");var i=new DataView(yield t.slice(t.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(eh)return eh;eh=[];for(var f=0;256>f;f++){for(var p=f,m=0;8>m;m++)p=1&p?3988292384^p>>>1:p>>>1;eh[f]=p>>>0}return eh})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&wm("invalid-crc");var s=n.length>>>0;i.getUint32(4,!0)!==s&&wm("invalid-size")}));return function(t,n){return e.apply(this,arguments)}})();function Vw(){return Vw=$i((function*(e,t,n){t===void 0&&(t=!0);try{var r=new TextEncoder().encode(e),i=new CompressionStream("gzip"),s=i.writable.getWriter(),o=s.write(r).then((()=>s.close())).catch((function(){var u=$i((function*(f){try{yield s.abort(f)}catch{}throw f}));return function(f){return u.apply(this,arguments)}})()),a=new Response(i.readable).blob(),[l]=yield Promise.all([a,o]);return yield yZ(l,r),l}catch(u){if(n!=null&&n.rethrow)throw u;return t&&console.error("Failed to gzip compress data",u),null}})),Vw.apply(this,arguments)}var bZ=["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"],_S=function(e,t){if(t===void 0&&(t=[]),!e)return!1;var n=e.toLowerCase();return bZ.concat(t).some((r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1}))};function At(e,t){return e.indexOf(t)!==-1}var bv=function(e){return e.trim()},Hw=function(e){return e.replace(/^\$/,"")},hM=Object.prototype,pM=hM.hasOwnProperty,xv=hM.toString,sn=Array.isArray||function(e){return xv.call(e)==="[object Array]"},zo=e=>typeof e=="function",Yn=e=>e===Object(e)&&!sn(e),Ku=e=>{if(Yn(e)){for(var t in e)if(pM.call(e,t))return!1;return!0}return!1},We=e=>e===void 0,Nn=e=>xv.call(e)=="[object String]",Bw=e=>Nn(e)&&e.trim().length===0,es=e=>e===null,Kt=e=>We(e)||es(e),Hi=e=>xv.call(e)=="[object Number]"&&e==e,Fo=e=>Hi(e)&&e>0,oo=e=>xv.call(e)==="[object Boolean]",xZ=e=>e instanceof FormData,wZ=e=>At(vZ,e);function mM(e){return e===null||typeof e!="object"}function Kg(e,t){return{}.toString.call(e)==="[object "+t+"]"}function B8(e){return typeof Event<"u"&&(function(t,n){try{return t instanceof n}catch{return!1}})(e,Event)}var _Z=[!0,"true",1,"1","yes"],pb=e=>At(_Z,e),kZ=[!1,"false",0,"0","no"];function ao(e,t,n,r,i){return t>n&&(r.warn("min cannot be greater than max."),t=n),Hi(e)?e>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t>e?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),ao(i||n,t,n,r))}class CZ{constructor(t){this.$t={},this.zt=t.zt,this.Zt=ao(t.bucketSize,0,100,t.Gt),this.Qt=ao(t.refillRate,0,this.Zt,t.Gt),this.Jt=ao(t.refillInterval,0,864e5,t.Gt)}Kt(t,n){var r=Math.floor((n-t.lastAccess)/this.Jt);r>0&&(t.tokens=Math.min(t.tokens+r*this.Qt,this.Zt),t.lastAccess=t.lastAccess+r*this.Jt)}consumeRateLimit(t){var n,r=Date.now(),i=String(t),s=this.$t[i];return s?this.Kt(s,r):this.$t[i]=s={tokens:this.Zt,lastAccess:r},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.zt)==null||n.call(this,t)),s.tokens===0)}stop(){this.$t={}}}var _m,kS,mb,Li="Mobile",Yg="iOS",Ko="Android",Md="Tablet",gM=Ko+" "+Md,vM="iPad",yM="Apple",bM=yM+" Watch",Bh="Safari",$d="BlackBerry",xM="Samsung",wM=xM+"Browser",_M=xM+" Internet",wc="Chrome",EZ=wc+" OS",kM=wc+" "+Yg,z8="Internet Explorer",CM=z8+" "+Li,U8="Opera",SZ=U8+" Mini",Z8="Edge",EM="Microsoft "+Z8,cd="Firefox",SM=cd+" "+Yg,lp="Nintendo",cp="PlayStation",ud="Xbox",AM=Ko+" "+Li,TM=Li+" "+Bh,Eh="Windows",zw=Eh+" Phone",CS="Nokia",Uw="Ouya",PM="Generic",AZ=PM+" "+Li.toLowerCase(),IM=PM+" "+Md.toLowerCase(),Zw="Konqueror",RM="Oculus Browser",Xg="Vivaldi",MM="Yandex",Qg="Whale",Ww="DuckDuckGo",$M="Pale Moon",Jg="Waterfox",zh="Brave",Hn="(\\d+(\\.\\d+)?)",gb=new RegExp("Version/"+Hn),TZ=new RegExp(ud,"i"),PZ=new RegExp(cp+" \\w+","i"),IZ=new RegExp(lp+" \\w+","i"),W8=new RegExp($d+"|PlayBook|BB10","i"),RZ={"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"},DM=function(e,t,n){t=t||"";var r=(function(i){return i!=null&&i.brave?zh:null})(n);return r||(At(e," OPR/")&&At(e,"Mini")?SZ:At(e," OPR/")?U8:W8.test(e)?$d:At(e,"IE"+Li)||At(e,"WPDesktop")?CM:At(e,"OculusBrowser")?RM:At(e,wM)?_M:At(e,Z8)||At(e,"Edg/")?EM:At(e,Xg+"/")?Xg:At(e,"YaBrowser/")?MM:At(e,Qg+"/")?Qg:At(e,Ww+"/")||At(e,"Ddg/")?Ww:At(e,"FBIOS")?"Facebook "+Li:At(e,"UCWEB")||At(e,"UCBrowser")?"UC Browser":At(e,"CriOS")?kM:At(e,"CrMo")||At(e,wc)?wc:At(e,Ko)&&At(e,Bh)?AM:At(e,"FxiOS")?SM:At(e.toLowerCase(),Zw.toLowerCase())?Zw:At(e,zh+"/")?zh:((i,s)=>s&&At(s,yM)||(function(o){return At(o,Bh)&&!At(o,wc)&&!At(o,Ko)})(i))(e,t)?At(e,Li)?TM:Bh:At(e,"PaleMoon/")?$M:At(e,Jg+"/")?Jg:At(e,cd)?cd:At(e,"MSIE")||At(e,"Trident/")?z8:At(e,"Gecko")?cd:"")},MZ={[CM]:[new RegExp("rv:"+Hn)],[EM]:[new RegExp(Z8+"?\\/"+Hn)],[wc]:[new RegExp("("+wc+"|CrMo)\\/"+Hn)],[kM]:[new RegExp("CriOS\\/"+Hn)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Hn)],[Bh]:[gb],[TM]:[gb],[U8]:[new RegExp("(Opera|OPR)\\/"+Hn)],[cd]:[new RegExp(cd+"\\/"+Hn)],[SM]:[new RegExp("FxiOS\\/"+Hn)],[Zw]:[new RegExp("Konqueror[:/]?"+Hn,"i")],[$d]:[new RegExp($d+" "+Hn),gb],[AM]:[new RegExp("android\\s"+Hn,"i")],[_M]:[new RegExp(wM+"\\/"+Hn)],[RM]:[new RegExp("OculusBrowser\\/"+Hn)],[Xg]:[new RegExp(Xg+"\\/"+Hn)],[MM]:[new RegExp("YaBrowser\\/"+Hn)],[Qg]:[new RegExp(Qg+"\\/"+Hn)],[zh]:[new RegExp(zh+"\\/"+Hn)],[Ww]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Hn)],[$M]:[new RegExp("PaleMoon\\/"+Hn)],[Jg]:[new RegExp(Jg+"\\/"+Hn)],[z8]:[new RegExp("(rv:|MSIE )"+Hn)],Mozilla:[new RegExp("rv:"+Hn)]},$Z=function(e,t,n){var r=DM(e,t,n),i=MZ[r];if(We(i))return null;for(var s=0;i.length>s;s++){var o=e.match(i[s]);if(o)return parseFloat(o[o.length-2])}return null},ES=[[new RegExp(ud+"; "+ud+" (.*?)[);]","i"),e=>[ud,e&&e[1]||""]],[new RegExp(lp,"i"),[lp,""]],[new RegExp(cp,"i"),[cp,""]],[W8,[$d,""]],[new RegExp(Eh,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[zw,""];if(new RegExp(Li).test(t)&&!/IEMobile\b/.test(t))return[Eh+" "+Li,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var r=RZ[n[1]]||"";return/arm/i.test(t)&&(r="RT"),[Eh,r]}return[Eh,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[Yg,[e[3],e[4],e[5]||"0"].join(".")]:[Yg,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=We(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ko+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ko+")","i"),e=>e&&e[2]?[Ko,[e[2],e[3],e[4]||"0"].join(".")]:[Ko,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[EZ,""]],[/Linux|debian/i,["Linux",""]]],SS=function(e){return IZ.test(e)?lp:PZ.test(e)?cp:TZ.test(e)?ud:new RegExp(Uw,"i").test(e)?Uw:new RegExp("("+zw+"|WPDesktop)","i").test(e)?zw:/iPad/.test(e)?vM:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?bM:W8.test(e)?$d:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(CS,"i").test(e)?CS:/(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(Li).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)?Ko:gM:new RegExp("(pda|"+Li+")","i").test(e)?AZ:new RegExp(Md,"i").test(e)&&!new RegExp(Md+" pc","i").test(e)?IM:""},DZ=e=>e instanceof Error,NM={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},NZ=NM.info;function LM(e){if(oo(e))return{boolValue:e};if(typeof e=="number")return Number.isFinite(e)?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:{stringValue:String(e)};if(typeof e=="string")return{stringValue:e};if(sn(e))return{arrayValue:{values:e.map((t=>LM(t)))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function AS(e){var t=[];for(var n in e){var r=e[n];es(r)||We(r)||t.push({key:n,value:LM(r)})}return t}function LZ(e){var t=globalThis._posthogChunkIds;if(t){var n=Object.keys(t);return mb&&n.length===kS||(kS=n.length,mb=n.reduce(((r,i)=>{_m||(_m={});var s=_m[i];if(s)r[s[0]]=s[1];else for(var o=e(i),a=o.length-1;a>=0;a--){var l=o[a],u=l==null?void 0:l.filename,f=t[i];if(u&&f){r[u]=f,_m[i]=[u,f];break}}return r}),{})),mb}}class jZ{constructor(t,n,r){r===void 0&&(r=[]),this.coercers=t,this.stackParser=n,this.modifiers=r}buildFromUnknown(t,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(t),s=this.buildParsingContext(n),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(t){var n=this;return $i((function*(){for(var r of t)r.stacktrace&&r.stacktrace.frames&&sn(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,i;return t.cause!=null&&(r=this.parseStacktrace(t.cause,n)),t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?n.skipFirstLines:0),n.chunkIdMap)),Oe({},t,{cause:r,stack:i})}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 $i((function*(){var r=t;for(var i of n.modifiers)r=yield i(r);return r}))()}convertToExceptionList(t,n){var r,i,s,o={type:t.type,value:t.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(s=t.synthetic)!==null&&s!==void 0&&s}};t.stack&&(o.stacktrace={type:"raw",frames:t.stack});var a=[o];return t.cause!=null&&a.push(...this.convertToExceptionList(t.cause,Oe({},n,{handled:!0}))),a}buildParsingContext(t){var n;return{chunkIdMap:LZ(this.stackParser),skipFirstLines:(n=t.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(t,n,r){r===void 0&&(r=0);var i=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(t,n,o);return this.applyCoercers(s,a)}};return Oe({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:t,apply:s=>i(s,r),next:s=>i(s,r+1)})}}var Dd="?";function Gw(e,t,n,r,i){var s={platform:e,filename:t,function:n==="<anonymous>"?Dd:n,in_app:!0};return We(r)||(s.lineno=r),We(i)||(s.colno=i),s}var jM=(e,t)=>{var n=e.indexOf("safari-extension")!==-1,r=e.indexOf("safari-web-extension")!==-1;return n||r?[e.indexOf("@")!==-1?e.split("@")[0]:Dd,n?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},FZ=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,OZ=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,VZ=/\((\S*)(?::(\d+))(?::(\d+))\)/,HZ=(e,t)=>{var n=FZ.exec(e);if(n){var[,r,i,s]=n;return Gw(t,r,Dd,+i,+s)}var o=OZ.exec(e);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=VZ.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=jM(o[1]||Dd,o[2]);return Gw(t,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},BZ=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zZ=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,UZ=(e,t)=>{var n=BZ.exec(e);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=zZ.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],s=n[1]||Dd;return[s,i]=jM(s,i),Gw(t,i,s,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},TS=/\(error: (.*)\)/;class ZZ{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,n){var r=Nn(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 Kg(t,"DOMException")}isDOMError(t){return Kg(t,"DOMError")}}class WZ{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 String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(t){return t.stacktrace||t.stack||void 0}}class GZ{constructor(){}match(t){return Kg(t,"ErrorEvent")&&t.error!=null}coerce(t,n){var r;return n.apply(t.error)||{type:"ErrorEvent",value:t.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}var qZ=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class KZ{match(t){return typeof t=="string"}coerce(t,n){var r,[i,s]=this.getInfos(t);return{type:i??"Error",value:s??t,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(t){var n="Error",r=t,i=t.match(qZ);return i&&(n=i[1],r=i[2]),[n,r]}}var YZ=["fatal","error","warning","log","info","debug"];function FM(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 i=n.slice(0,r).join(", ");if(t>=i.length)return r===n.length?i:i.length>t?i.slice(0,t)+"...":i}return""}class XZ{match(t){return typeof t=="object"&&t!==null}coerce(t,n){var r,i=this.getErrorPropertyFromObject(t);return i?n.apply(i):{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 B8(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: "+FM(t)}isSeverityLevel(t){return Nn(t)&&!Bw(t)&&YZ.indexOf(t)>=0}getErrorPropertyFromObject(t){for(var n in t)if({}.hasOwnProperty.call(t,n)){var r=t[n];if(DZ(r))return r}}getObjectClassName(t){try{var n=Object.getPrototypeOf(t);return n?n.constructor.name:void 0}catch{return}}}class QZ{match(t){return B8(t)}coerce(t,n){var r,i=t.constructor.name;return{type:i,value:i+" captured as exception with keys: "+FM(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class JZ{match(t){return mM(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}}}class eW{match(t){return Kg(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!B8(t))return!1;try{var n=t.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(t,n){var r,i=this.getUnhandledRejectionReason(t);return mM(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}}var e1="$message",t1="$timestamp",tW=new Set([e1,t1]),vb={enabled:!0,max_bytes:32768};function n1(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:vb.enabled,max_bytes:rW(e.max_bytes,vb.max_bytes)}:Oe({},vb)}class nW{constructor(t){this.Yt=[],this.Xt=0,this.qt=n1(t)}setConfig(t){this.qt=n1(t),this.er()}add(t){var n=(function(i){var s=(function(f){var p=new WeakSet;try{return JSON.stringify(f,((m,g)=>{if(typeof g=="bigint")return g.toString();if(typeof g!="function"&&typeof g!="symbol"){if(g instanceof Date)return g.toISOString();if(g instanceof Error)return{name:g.name,message:g.message,stack:g.stack};if(g&&typeof g=="object"){if(p.has(g))return"[Circular]";p.add(g)}return g}}))}catch{return}})(i);if(s)try{var o=JSON.parse(s);if(!Yn(o))return;var a=o,l=a[e1],u=a[t1];return!Nn(l)||l.trim().length===0||!Nn(u)&&!Hi(u)?void 0:{step:a,json:s}}catch{return}})(t);if(n){var r=(function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var s=encodeURIComponent(i),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);r>this.qt.max_bytes||(this.Yt.push({step:n.step,bytes:r}),this.Xt+=r,this.er())}}getAttachable(){return this.Yt.map((t=>t.step))}clear(){this.Yt=[],this.Xt=0}size(){return this.Yt.length}er(){for(;this.Xt>this.qt.max_bytes&&this.Yt.length>0;){var t=this.Yt.shift();t&&(this.Xt-=t.bytes)}}}function rW(e,t){if(!Hi(e)||e===1/0||e===-1/0)return t;var n=Math.floor(e);return 0>n?t:n}var OM=function(e,t){var{debugEnabled:n}=t===void 0?{}:t,r={k(i){if(me&&(wr.DEBUG||gt.POSTHOG_DEBUG||n)&&!We(me.console)&&me.console){for(var s=("__rrweb_original__"in me.console[i])?me.console[i].__rrweb_original__:me.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(e,...a)}},debug(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("debug",...s)},info(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("log",...s)},warn(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("warn",...s)},error(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("error",...s)},critical(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];console.error(e,...s)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>OM(e+" "+i,s)};return r},Ue=OM("[PostHog.js]"),Ln=Ue.createLogger,iW=Ln("[ExternalScriptsLoader]"),yb=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return iW.warn(t+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=Ze==null?void 0:Ze.querySelectorAll("script");if(r){for(var i,s=function(){if(r[o].src===t){var l=r[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;r.length>o;o++)if(i=s())return i.v}var a=()=>{if(!Ze)return n("document not found");var l=Ze.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=t,l.onload=p=>{l.__posthog_loading_callback_fired=!0,n(void 0,p)},l.onerror=p=>n(p),e.config.prepare_external_dependency_script&&(l=e.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")Ze.head.appendChild(l);else{var u,f=Ze.querySelectorAll("body > script");f.length>0?(u=f[0].parentNode)==null||u.insertBefore(l,f[0]):Ze.body.appendChild(l)}};Ze!=null&&Ze.body?a():Ze==null||Ze.addEventListener("DOMContentLoaded",a)};gt.__PosthogExtensions__=gt.__PosthogExtensions__||{},gt.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{if(t!=="remote-config"){var r;if(e.config.__preview_external_dependency_versioned_paths)r=e.requestRouter.endpointFor("assets","/static/"+e.version+"/"+t+".js");else{var i="/static/"+t+".js?v="+e.version;if(t==="toolbar"){var s=3e5;i=i+"&t="+Math.floor(Date.now()/s)*s}r=e.requestRouter.endpointFor("assets",i)}yb(e,r,n)}else{var o=e.requestRouter.endpointFor("assets","/array/"+e.config.token+"/config.js");yb(e,o,n)}},gt.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var r=e.requestRouter.endpointFor("api",t);yb(e,r,n)};var VM="$people_distinct_id",r1="$device_id",Sh="__alias",Ah="__timers",qw="$autocapture_disabled_server_side",Kw="$heatmaps_enabled_server_side",Yw="$exception_capture_enabled_server_side",Xw="$error_tracking_suppression_rules",Qw="$error_tracking_capture_extension_exceptions",Jw="$web_vitals_enabled_server_side",G8="$dead_clicks_enabled_server_side",e4="$product_tours_enabled_server_side",t4="$web_vitals_allowed_metrics",lc="$session_recording_remote_config",HM="$replay_override_sampling",BM="$replay_override_linked_flag",zM="$replay_override_url_trigger",UM="$replay_override_event_trigger",Yu="$sesid",q8="$session_is_sampled",Xu="$enabled_feature_flags",bg="$active_feature_flags",Th="$early_access_features",n4="$feature_flag_details",r4="$feature_flag_payloads",i4="$feature_flag_request_id",Oo="$override_feature_flags",zu="$override_feature_flag_payloads",Ph="$stored_person_properties",nc="$stored_group_properties",s4="$surveys",o4="$surveys_activated",xg="ph_product_tours",Uh="$flag_call_reported",a4="$flag_call_reported_session_id",l4="$feature_flag_errors",i1="$feature_flag_evaluated_at",xs="$user_state",c4="$client_session_props",u4="$capture_rate_limit",d4="$initial_campaign_params",f4="$initial_referrer_info",s1="$initial_person_info",o1="$epp",ZM="__POSTHOG_TOOLBAR__",km="$posthog_cookieless",WM="$sdk_debug_extensions_init_method",GM="$sdk_debug_extensions_init_time_ms",qM="$sdk_debug_recording_script_not_loaded",K8="PostHog loadExternalDependency extension not found.",rc="on_reject",Go="always",_u="anonymous",ku="identified",h4="identified_only",a1="visibilitychange",l1="beforeunload",Uu="$pageview",bb="$pageleave",xb="$identify",PS="$groupidentify";function Cm(e,t){sn(e)&&e.forEach(t)}function Rn(e,t){if(!Kt(e))if(sn(e))e.forEach(t);else if(xZ(e))e.forEach(((r,i)=>t(r,i)));else for(var n in e)pM.call(e,n)&&t(e[n],n)}var qn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;t>r;r++)n[r-1]=arguments[r];for(var i of n)for(var s in i)i[s]!==void 0&&(e[s]=i[s]);return e};function wg(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 IS=function(e){try{return e()}catch{return}},sW=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),r=0;t>r;r++)n[r]=arguments[r];return e.apply(this,n)}catch(i){Ue.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ue.critical(i)}}},Y8=function(e){var t={};return Rn(e,(function(n,r){(Nn(n)&&n.length>0||Hi(n))&&(t[r]=n)})),t},oW=["herokuapp.com","vercel.app","netlify.app"];function aW(e){var t=e==null?void 0:e.hostname;if(!Nn(t))return!1;var n=t.split(".").slice(-2).join(".");for(var r of oW)if(n===r)return!1;return!0}function Wn(e,t,n,r){var{capture:i=!1,passive:s=!0}=r??{};e==null||e.addEventListener(t,n,{capture:i,passive:s})}function KM(e){return e.name==="ph_toolbar_internal"}Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return Hi(e)&&isFinite(e)&&Math.floor(e)===e});class c1{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||0>t||0>n||0>r||0>i||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/Math.pow(2,8),s[5]=t,s[6]=112|n>>>8,s[7]=n,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new c1(s)}toString(){for(var t="",n=0;this.bytes.length>n;n++)t=t+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),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 c1(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;16>n;n++){var r=this.bytes[n]-t.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class lW{constructor(){this.S=0,this.C=0,this.I=new cW}generate(){var t=this.generateOrAbort();if(We(t)){this.S=0;var n=this.generateOrAbort();if(We(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.S)this.S=t,this.T();else{if(this.S>=t+1e4)return;this.C++,this.C>4398046511103&&(this.S++,this.T())}return c1.fromFieldsV7(this.S,Math.trunc(this.C/Math.pow(2,30)),this.C&Math.pow(2,30)-1,this.I.nextUint32())}T(){this.C=1024*this.I.nextUint32()+(1023&this.I.nextUint32())}}var RS,YM=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};me&&!We(me.crypto)&&crypto.getRandomValues&&(YM=e=>crypto.getRandomValues(e));class cW{constructor(){this.M=new Uint32Array(8),this.R=1/0}nextUint32(){return this.M.length>this.R||(YM(this.M),this.R=0),this.M[this.R++]}}var Ga=()=>uW().toString(),uW=()=>(RS||(RS=new lW)).generate(),th="",dW=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,io={O:()=>!!Ze,D(e){Ue.error("cookieStore error: "+e)},A(e){if(Ze){try{for(var t=e+"=",n=Ze.cookie.split(";").filter((s=>s.length)),r=0;n.length>r;r++){for(var i=n[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}},F(e){var t;try{t=JSON.parse(io.A(e))||{}}catch{}return t},N(e,t,n,r,i){if(Ze)try{var s="",o="",a=(function(f,p){if(p){var m=(function(b,x){if(x===void 0&&(x=Ze),th)return th;if(!x||["localhost","127.0.0.1"].includes(b))return"";for(var k=b.split("."),w=Math.min(k.length,8),C="dmn_chk_"+Ga();!th&&w--;){var E=k.slice(w).join("."),A=C+"=1;domain=."+E+";path=/";x.cookie=A+";max-age=3",x.cookie.includes(C)&&(x.cookie=A+";max-age=0",th=E)}return th})(f);if(!m){var g=(b=>{var x=b.match(dW);return x?x[0]:""})(f);g!==m&&Ue.info("Warning: cookie subdomain discovery mismatch",g,m),m=g}return m?"; domain=."+m:""}return""})(Ze.location.hostname,r);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&Ue.warn("cookieStore warning: large cookie, len="+u.length),Ze.cookie=u,u}catch{return}},q(e,t){if(Ze!=null&&Ze.cookie)try{io.N(e,"",-1,t)}catch{return}}},wb=null,Bn={O(){if(!es(wb))return wb;var e=!0;if(We(me))e=!1;else try{var t="__mplssupport__";Bn.N(t,"xyz"),Bn.A(t)!=='"xyz"'&&(e=!1),Bn.q(t)}catch{e=!1}return e||Ue.error("localStorage unsupported; falling back to cookie store"),wb=e,e},D(e){Ue.error("localStorage error: "+e)},A(e){try{return me==null?void 0:me.localStorage.getItem(e)}catch(t){Bn.D(t)}return null},F(e){try{return JSON.parse(Bn.A(e))||{}}catch{}return null},N(e,t){try{me==null||me.localStorage.setItem(e,JSON.stringify(t))}catch(n){Bn.D(n)}},q(e){try{me==null||me.localStorage.removeItem(e)}catch(t){Bn.D(t)}}},fW=[r1,"distinct_id",Yu,q8,o1,s1,xs],Em={},hW={O:()=>!0,D(e){Ue.error("memoryStorage error: "+e)},A:e=>Em[e]||null,F:e=>Em[e]||null,N(e,t){Em[e]=t},q(e){delete Em[e]}},Wl=null,Ir={O(){if(!es(Wl))return Wl;if(Wl=!0,We(me))Wl=!1;else try{var e="__support__";Ir.N(e,"xyz"),Ir.A(e)!=='"xyz"'&&(Wl=!1),Ir.q(e)}catch{Wl=!1}return Wl},D(e){Ue.error("sessionStorage error: ",e)},A(e){try{return me==null?void 0:me.sessionStorage.getItem(e)}catch(t){Ir.D(t)}return null},F(e){try{return JSON.parse(Ir.A(e))||null}catch{}return null},N(e,t){try{me==null||me.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){Ir.D(n)}},q(e){try{me==null||me.sessionStorage.removeItem(e)}catch(t){Ir.D(t)}}};class pW{constructor(t){this._instance=t}get qt(){return this._instance.config}get consent(){return this.rr()?0:this.ir}isOptedOut(){return this.qt.cookieless_mode===Go||this.isRejected()||this.consent===-1&&this.qt.cookieless_mode===rc}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.qt.opt_out_capturing_by_default}optInOut(t){this.nr.N(this.sr,t?1:0,this.qt.cookie_expiration,this.qt.cross_subdomain_cookie,this.qt.secure_cookie)}reset(){this.nr.q(this.sr,this.qt.cross_subdomain_cookie)}get sr(){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 ir(){var t=this.nr.A(this.sr);return pb(t)?1:At(kZ,t)?0:-1}get nr(){var t=this.qt.opt_out_capturing_persistence_type,n=t==="localStorage"?Bn:io;if(!this.ar||this.ar!==n){this.ar=n;var r=t==="localStorage"?io:Bn;r.A(this.sr)&&(this.ar.A(this.sr)||this.optInOut(pb(r.A(this.sr))),r.q(this.sr,this.qt.cross_subdomain_cookie))}return this.ar}rr(){return!!this.qt.respect_dnt&&[Ni==null?void 0:Ni.doNotTrack,Ni==null?void 0:Ni.msDoNotTrack,gt.doNotTrack].some((t=>pb(t)))}}var Sm=Ln("[Dead Clicks]"),mW=()=>!0,gW=e=>{var t,n=!((t=e.instance.persistence)==null||!t.get_property(G8)),r=e.instance.config.capture_dead_clicks;return oo(r)?r:!!Yn(r)||n};class MS{get lazyLoadedDeadClicksAutocapture(){return this.ur}constructor(t,n,r){this.instance=t,this.isEnabled=n,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(t){"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[G8]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.lr((()=>{this.hr()})):this.stop()}lr(t){var n,r;(n=gt.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&t(),(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(i=>{i?Sm.error("failed to load script",i):t()}))}hr(){var t;if(Ze){if(!this.ur&&(t=gt.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture){var n=Yn(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.ur=gt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.ur.start(Ze),Sm.info("starting...")}}else Sm.error("`document` not found. Cannot start.")}stop(){this.ur&&(this.ur.stop(),this.ur=void 0,Sm.info("stopping..."))}}var _b=Ln("[SegmentIntegration]"),XM="posthog-js";function QM(e,t){var{organization:n,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=t===void 0?{}:t;return a=>{var l,u,f,p,m;if(s!=="*"&&!s.includes(a.level)||!e.__loaded)return a;a.tags||(a.tags={});var g=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());a.tags["PostHog Person URL"]=g,e.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var b,x=((l=a.exception)==null?void 0:l.values)||[],k=x.map((C=>Oe({},C,{stacktrace:C.stacktrace?Oe({},C.stacktrace,{type:"raw",frames:(C.stacktrace.frames||[]).map((E=>Oe({},E,{platform:"web:javascript"})))}):void 0}))),w={$exception_message:((u=x[0])==null?void 0:u.value)||a.message,$exception_type:(f=x[0])==null?void 0:f.type,$exception_level:a.level,$exception_list:k,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=x[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(m=x[0])==null?void 0:m.type,$sentry_tags:a.tags};return n&&r&&(w.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+a.event_id),o&&((b=e.exceptions)==null||b.sendExceptionEvent(w)),a}}class vW{constructor(t,n,r,i,s,o){this.name=XM,this.setupOnce=function(a){a(QM(t,{organization:n,projectId:r,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class $S{constructor(t){this.cr=(n,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(Ue.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:i}),this.dr=void 0,this._instance.scrollManager.resetContext())},this._instance=t,this.vr()}vr(){var t;this.pr=(t=this._instance.sessionManager)==null?void 0:t.onSessionId(this.cr)}destroy(){var t;(t=this.pr)==null||t.call(this),this.pr=void 0}doPageView(t,n){var r,i=this.gr(t,n);return this.dr={pathname:(r=me==null?void 0:me.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:t},this._instance.scrollManager.resetContext(),i}doPageLeave(t){var n;return this.gr(t,(n=this.dr)==null?void 0:n.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this.dr)==null?void 0:t.pageViewId}}gr(t,n){var r=this.dr;if(!r)return{$pageview_id:n};var i={$pageview_id:n,$prev_pageview_id:r.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:f,maxContentY:p}=s;if(!(We(o)||We(a)||We(l)||We(u)||We(f)||We(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),f=Math.ceil(f),p=Math.ceil(p);var m=o>1?ao(a/o,0,1,Ue):1,g=o>1?ao(l/o,0,1,Ue):1,b=u>1?ao(f/u,0,1,Ue):1,x=u>1?ao(p/u,0,1,Ue):1;i=qn(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:m,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:g,$prev_pageview_last_content:f,$prev_pageview_last_content_percentage:b,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:x})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(t.getTime()-r.timestamp.getTime())/1e3),i}}var yW={[VM]:{exposure:"hidden"},[Sh]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ah]:{exposure:"hidden"},[qw]:{exposure:"event"},[Kw]:{exposure:"hidden"},[Yw]:{exposure:"event"},[Xw]:{exposure:"hidden"},[Qw]:{exposure:"event"},[Jw]:{exposure:"event"},[G8]:{exposure:"event"},[e4]:{exposure:"hidden"},[t4]:{exposure:"event"},[lc]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yu]:{exposure:"hidden"},[q8]:{exposure:"event"},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},[Xu]:{exposure:"derived",shouldSkipFromEventProperties:(e,t)=>t(),transformToEventProperties(e){if(!Yn(e))return{};for(var t={},n=Object.keys(e),r=0;n.length>r;r++)t["$feature/"+n[r]]=e[n[r]];return t}},[bg]:{exposure:"event"},[Th]:{exposure:"hidden"},[n4]:{exposure:"hidden"},[r4]:{exposure:"event"},[i4]:{exposure:"event"},[Oo]:{exposure:"event"},[zu]:{exposure:"hidden"},[Ph]:{exposure:"hidden"},[nc]:{exposure:"hidden"},[s4]:{exposure:"hidden"},[o4]:{exposure:"event"},[xg]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Uh]:{exposure:"hidden"},[a4]:{exposure:"hidden"},[l4]:{exposure:"hidden"},[i1]:{exposure:"hidden"},[xs]:{exposure:"hidden"},[c4]:{exposure:"hidden"},[u4]:{exposure:"hidden"},[d4]:{exposure:"hidden"},[f4]:{exposure:"hidden"},[s1]:{exposure:"hidden"},[o1]:{exposure:"hidden"},[HM]:{exposure:"event"},[BM]:{exposure:"event"},[zM]:{exposure:"event"},[UM]:{exposure:"event"},[WM]:{exposure:"event"},[GM]:{exposure:"event"},[qM]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},bW=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],u1=e=>{var t=Ze==null?void 0:Ze.createElement("a");return We(t)?null:(t.href=e,t)},up=function(e,t){for(var n,r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var s=r[i].split("=");if(s[0]===t){n=s;break}}if(!sn(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{Ue.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},dp=function(e,t,n){if(!e||!t||!t.length)return e;for(var r=e.split("#"),i=r[1],s=(r[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],f=0;l.length>f;f++){var p=l[f].split("=");sn(p)&&(t.includes(p[0])?u.push(p[0]+"="+n):u.push(l[f]))}var m=a;return o!=null&&(m+="?"+u.join("&")),i!=null&&(m+="#"+i),m},d1=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},Am="https?://(.*)",Nd=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],xW=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Nd],fp="<masked>",wW=["li_fat_id"];function JM(e,t,n){if(!Ze)return{};var r,i=t?[...Nd,...n||[]]:[],s=e9(dp(Ze.URL,i,fp),e),o=(r={},Rn(wW,(function(a){var l=io.A(a);r[a]=l||null})),r);return qn(o,s)}function e9(e,t){var n=xW.concat(t||[]),r={};return Rn(n,(function(i){var s=up(e,i);r[i]=s||null})),r}function t9(e){var t=(function(s){return s?s.search(Am+"google.([^/?]*)")===0?"google":s.search(Am+"bing.com")===0?"bing":s.search(Am+"yahoo.com")===0?"yahoo":s.search(Am+"duckduckgo.com")===0?"duckduckgo":null:null})(e),n=t!="yahoo"?"q":"p",r={};if(!es(t)){r.$search_engine=t;var i=Ze?up(Ze.referrer,n):"";i.length&&(r.ph_keyword=i)}return r}function DS(){return navigator.language||navigator.userLanguage}var f1="$direct";function n9(){return(Ze==null?void 0:Ze.referrer)||f1}function r9(e,t){var n=e?[...Nd,...t||[]]:[],r=Pr==null?void 0:Pr.href.substring(0,1e3);return{r:n9().substring(0,1e3),u:r?dp(r,n,fp):void 0}}function i9(e){var t,{r:n,u:r}=e,i={$referrer:n,$referring_domain:n==null?void 0:n==f1?f1:(t=u1(n))==null?void 0:t.host};if(r){i.$current_url=r;var s=u1(r);i.$host=s==null?void 0:s.host,i.$pathname=s==null?void 0:s.pathname;var o=e9(r);qn(i,o)}if(n){var a=t9(n);qn(i,a)}return i}function s9(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function _W(){try{return new Date().getTimezoneOffset()}catch{return}}var kW=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class kb{constructor(t,n){if(this.qt=t,this.props={},this.mr=!1,this.yr=(i=>{var s="";return i.token&&(s=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+s+"_posthog"})(t),this.nr=this.br(t),this.load(),t.debug&&Ue.info("Persistence loaded",t.persistence,Oe({},this.props)),this.update_config(t,t,n),this.save(),me){var r=()=>this.flush();Wn(me,"beforeunload",r,{capture:!1}),Wn(me,"pagehide",r,{capture:!1})}}_r(){var t,n=(t=this.qt)==null?void 0:t.persistence_save_debounce_ms;return Hi(n)&&n>0?n:0}isDisabled(){return!!this.wr}br(t){kW.indexOf(t.persistence.toLowerCase())===-1&&(Ue.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=(function(i){i===void 0&&(i=[]);var s=[...fW,...i];return Oe({},Bn,{F(o){try{var a={};try{a=io.F(o)||{}}catch{}var l=qn(a,JSON.parse(Bn.A(o)||"{}"));return Bn.N(o,l),l}catch{}return null},N(o,a,l,u,f,p){try{Bn.N(o,a,void 0,void 0,p);var m={};s.forEach((g=>{a[g]&&(m[g]=a[g])})),Object.keys(m).length&&io.N(o,m,l,u,f,p)}catch(g){Bn.D(g)}},q(o,a){try{me==null||me.localStorage.removeItem(o),io.q(o,a)}catch(l){Bn.D(l)}}})})(t.cookie_persisted_properties||[]),r=t.persistence.toLowerCase();return r==="localstorage"&&Bn.O()?Bn:r==="localstorage+cookie"&&n.O()?n:r==="sessionstorage"&&Ir.O()?Ir:r==="memory"?hW:r==="cookie"?io:n.O()?n:io}Sr(t){var n=t??this.qt.feature_flag_cache_ttl_ms;if(!n||0>=n)return!1;var r=this.props[i1];return!r||typeof r!="number"||Date.now()-r>n}properties(){var t={};return Rn(this.props,((n,r)=>{var i=(s=>{var o=yW[s];if(o)return o;for(var[a,l]of bW)if(s.indexOf(a)===0)return l})(r);if((i==null?void 0:i.exposure)==="derived"){if(i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(n,r===Xu?()=>this.Sr():()=>!1))return;i.transformToEventProperties&&qn(t,i.transformToEventProperties(n))}else i&&i.exposure!=="event"||(t[r]=n)})),t}load(){if(!this.wr){var t=this.nr.F(this.yr);t&&(this.props=qn({},t))}}refreshKey(t){if(!this.wr){var n=this.nr.F(this.yr);n&&t in n?this.kr(t,n[t]):this.Cr(t)}}save(){if(!this.wr){var t=this._r();t>0?We(this.Ir)&&(this.Ir=setTimeout((()=>{this.Ir=void 0,this.Tr()}),t)):this.Tr()}}flush(){We(this.Ir)||(clearTimeout(this.Ir),this.Ir=void 0,this.Tr())}Tr(){if(!this.wr){try{var t=JSON.stringify(this.props)+"|"+this.Er+"|"+this.Mr+"|"+this.Rr;if(t===this.Pr)return;this.Pr=t}catch{}this.nr.N(this.yr,this.props,this.Er,this.Mr,this.Rr,this.qt.debug)}}remove(){We(this.Ir)||(clearTimeout(this.Ir),this.Ir=void 0),this.nr.q(this.yr,!1),this.nr.q(this.yr,!0),this.Pr=void 0}clear(){this.remove(),this.props={}}register_once(t,n,r){if(Yn(t)){We(n)&&(n="None"),this.Er=We(r)?this.Or:r;var i=!1;if(Rn(t,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.kr(o,s),i=!0)})),i)return this.save(),!0}return!1}register(t,n){if(Yn(t)){this.Er=We(n)?this.Or:n;var r=!1;if(Rn(t,((i,s)=>{t.hasOwnProperty(s)&&this.props[s]!==i&&(this.kr(s,i),r=!0)})),r)return this.save(),!0}return!1}unregister(t){t in this.props&&(this.Cr(t),this.save())}update_campaign_params(){if(!this.mr){var t=JM(this.qt.custom_campaign_params,this.qt.mask_personal_data_properties,this.qt.custom_personal_data_properties);Ku(Y8(t))||this.register(t),this.mr=!0}}update_search_keyword(){var t;this.register((t=Ze==null?void 0:Ze.referrer)?t9(t):{})}update_referrer_info(){var t;this.register_once({$referrer:n9(),$referring_domain:Ze!=null&&Ze.referrer&&((t=u1(Ze.referrer))==null?void 0:t.host)||f1},void 0)}set_initial_person_info(){this.props[d4]||this.props[f4]||this.register_once({[s1]:r9(this.qt.mask_personal_data_properties,this.qt.custom_personal_data_properties)},void 0)}get_initial_props(){var t={};Rn([f4,d4],(o=>{var a=this.props[o];a&&Rn(a,(function(l,u){t["$initial_"+Hw(u)]=l}))}));var n,r,i=this.props[s1];if(i){var s=(n=i9(i),r={},Rn(n,(function(o,a){r["$initial_"+Hw(a)]=o})),r);qn(t,s)}return t}safe_merge(t){return Rn(this.props,(function(n,r){r in t||(t[r]=n)})),t}update_config(t,n,r){if(this.Or=this.Er=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||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every(((f,p)=>f===u[p]))})(t.cookie_persisted_properties||[],n.cookie_persisted_properties||[])){var i=this.br(t),s=this.props;this.clear(),this.nr=i,this.props=s,this.save()}}set_disabled(t){this.wr=t,this.wr?this.remove():this.save()}set_cross_subdomain(t){t!==this.Mr&&(this.Mr=t,this.remove(),this.save())}set_secure(t){t!==this.Rr&&(this.Rr=t,this.remove(),this.save())}set_event_timer(t,n){var r=this.props[Ah]||{};r[t]=n,this.kr(Ah,r),this.save()}remove_event_timer(t){var n=this.props[Ah]||{},r=n[t];return We(r)||(delete n[t],this.kr(Ah,n),this.save()),r}get_property(t){return this.props[t]}set_property(t,n){this.kr(t,n),this.save()}kr(t,n){this.props[t]=n}Cr(t){delete this.props[t]}}var nh={Activation:"events",Cancellation:"cancelEvents"},Cb={Popover:"popover",API:"api",Widget:"widget"},Ih={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Eb={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},p4={Popover:"popover",Inline:"inline"},CW={SHOWN:"product tour shown"},NS={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},LS=Ln("[RateLimiter]");class EW{constructor(t){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var r=n.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((i=>{LS.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void LS.warn('could not rate limit - continuing. Error: "'+(i==null?void 0:i.message)+'"',{text:r})}},this.instance=t,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var t;return((t=this.instance.config.rate_limiting)==null?void 0:t.events_per_second)||10}get captureEventsBurstLimit(){var t;return Math.max(((t=this.instance.config.rate_limiting)==null?void 0:t.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(t){var n,r,i;t===void 0&&(t=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(n=(r=this.instance.persistence)==null?void 0:r.get_property(u4))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;return u||t||(l.tokens=Math.max(0,l.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 "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(u4,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var rh=Ln("[RemoteConfig]");class o9{constructor(t){this._instance=t}get remoteConfig(){var t;return(t=gt._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.config}Lr(t){var n,r;(n=gt.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>t(this.remoteConfig))):t()}Fr(t){this._instance._send_request({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 rh.info("Using preloaded remote config",this.remoteConfig),this.Ar(this.remoteConfig),void this.Nr();if(this._instance.Dr())return void rh.warn("Remote config is disabled. Falling back to local config.");this.Lr((t=>{if(!t)return rh.info("No config found after loading remote JS config. Falling back to JSON."),void this.Fr((n=>{this.Ar(n),this.Nr()}));this.Ar(t),this.Nr()}))}catch(t){rh.error("Error loading remote config",t)}}stop(){this.$r&&(clearInterval(this.$r),this.$r=void 0)}refresh(){!this._instance.Dr()&&Ze&&Ze.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Nr(){var t;if(!this.$r){var n=(t=this._instance.config.remote_config_refresh_interval_ms)!==null&&t!==void 0?t:3e5;n!==0&&(this.$r=setInterval((()=>{this.refresh()}),n))}}Ar(t){var n;t||rh.error("Failed to fetch remote config from PostHog."),this._instance.Ar(t??{}),(t==null?void 0:t.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||(n=this._instance.featureFlags)==null||n.ensureFlagsLoaded())}}var no={GZipJS:"gzip-js",Base64:"base64"},ts=Uint8Array,vi=Uint16Array,Ld=Uint32Array,X8=new ts([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]),Q8=new ts([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]),jS=new ts([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a9=function(e,t){for(var n=new vi(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var i=new Ld(n[30]);for(r=1;30>r;++r)for(var s=n[r];n[r+1]>s;++s)i[s]=s-n[r]<<5|r;return[n,i]},l9=a9(X8,2),m4=l9[1];l9[0][28]=258,m4[258]=28;for(var FS=a9(Q8,0)[1],c9=new vi(32768),Mn=0;32768>Mn;++Mn){var Cu=(43690&Mn)>>>1|(21845&Mn)<<1;c9[Mn]=((65280&(Cu=(61680&(Cu=(52428&Cu)>>>2|(13107&Cu)<<2))>>>4|(3855&Cu)<<4))>>>8|(255&Cu)<<8)>>>1}var Zh=function(e,t,n){for(var r=e.length,i=0,s=new vi(t);r>i;++i)++s[e[i]-1];var o,a=new vi(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;for(o=new vi(r),i=0;r>i;++i)o[i]=c9[a[e[i]-1]++]>>>15-e[i];return o},Ic=new ts(288);for(Mn=0;144>Mn;++Mn)Ic[Mn]=8;for(Mn=144;256>Mn;++Mn)Ic[Mn]=9;for(Mn=256;280>Mn;++Mn)Ic[Mn]=7;for(Mn=280;288>Mn;++Mn)Ic[Mn]=8;var h1=new ts(32);for(Mn=0;32>Mn;++Mn)h1[Mn]=5;var SW=Zh(Ic,9),AW=Zh(h1,5),u9=function(e){return(e/8>>0)+(7&e&&1)},d9=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var r=new(e instanceof vi?vi:e instanceof Ld?Ld:ts)(n-t);return r.set(e.subarray(t,n)),r},Mo=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8},ih=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8,e[r+2]|=n>>>16},Sb=function(e,t){for(var n=[],r=0;e.length>r;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,s=n.slice();if(!i)return[new ts(0),0];if(i==1){var o=new ts(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(R,P){return R.f-P.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,f=1,p=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};f!=i-1;)a=n[n[p].f>n[u].f?u++:p++],l=n[u!=f&&n[p].f>n[u].f?u++:p++],n[f++]={s:-1,f:a.f+l.f,l:a,r:l};var m=s[0].s;for(r=1;i>r;++r)s[r].s>m&&(m=s[r].s);var g=new vi(m+1),b=g4(n[f-1],g,0);if(b>t){r=0;var x=0,k=b-t,w=1<<k;for(s.sort((function(R,P){return g[P.s]-g[R.s]||R.f-P.f}));i>r;++r){var C=s[r].s;if(t>=g[C])break;x+=w-(1<<b-g[C]),g[C]=t}for(x>>>=k;x>0;){var E=s[r].s;t>g[E]?x-=1<<t-g[E]++-1:++r}for(;r>=0&&x;--r){var A=s[r].s;g[A]==t&&(--g[A],++x)}b=t}return[new ts(g),b]},g4=function(e,t,n){return e.s==-1?Math.max(g4(e.l,t,n+1),g4(e.r,t,n+1)):t[e.s]=n},OS=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new vi(++t),r=0,i=e[0],s=1,o=function(l){n[r++]=l},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[n.subarray(0,r),t]},sh=function(e,t){for(var n=0,r=0;t.length>r;++r)n+=e[r]*t[r];return n},v4=function(e,t,n){var r=n.length,i=u9(t+2);e[i]=255&r,e[i+1]=r>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;r>s;++s)e[i+s+4]=n[s];return 8*(i+4+r)},VS=function(e,t,n,r,i,s,o,a,l,u,f){Mo(t,f++,n),++i[256];for(var p=Sb(i,15),m=p[0],g=p[1],b=Sb(s,15),x=b[0],k=b[1],w=OS(m),C=w[0],E=w[1],A=OS(x),R=A[0],P=A[1],I=new vi(19),T=0;C.length>T;++T)I[31&C[T]]++;for(T=0;R.length>T;++T)I[31&R[T]]++;for(var L=Sb(I,7),M=L[0],D=L[1],O=19;O>4&&!M[jS[O-1]];--O);var F,Z,V,U,K=u+5<<3,W=sh(i,Ic)+sh(s,h1)+o,G=sh(i,m)+sh(s,x)+o+14+3*O+sh(I,M)+(2*I[16]+3*I[17]+7*I[18]);if(W>=K&&G>=K)return v4(t,f,e.subarray(l,l+u));if(Mo(t,f,1+(W>G)),f+=2,W>G){F=Zh(m,g),Z=m,V=Zh(x,k),U=x;var j=Zh(M,D);for(Mo(t,f,E-257),Mo(t,f+5,P-1),Mo(t,f+10,O-4),f+=14,T=0;O>T;++T)Mo(t,f+3*T,M[jS[T]]);f+=3*O;for(var H=[C,R],B=0;2>B;++B){var N=H[B];for(T=0;N.length>T;++T)Mo(t,f,j[q=31&N[T]]),f+=M[q],q>15&&(Mo(t,f,N[T]>>>5&127),f+=N[T]>>>12)}}else F=SW,Z=Ic,V=AW,U=h1;for(T=0;a>T;++T)if(r[T]>255){var q;ih(t,f,F[257+(q=r[T]>>>18&31)]),f+=Z[q+257],q>7&&(Mo(t,f,r[T]>>>23&31),f+=X8[q]);var X=31&r[T];ih(t,f,V[X]),f+=U[X],X>3&&(ih(t,f,r[T]>>>5&8191),f+=Q8[X])}else ih(t,f,F[r[T]]),f+=Z[r[T]];return ih(t,f,F[256]),f+Z[256]},TW=new Ld([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),PW=(function(){for(var e=new Ld(256),t=0;256>t;++t){for(var n=t,r=9;--r;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e})(),Ab=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function IW(e,t){t===void 0&&(t={});var n=(function(){var p=4294967295;return{p(m){for(var g=p,b=0;m.length>b;++b)g=PW[255&g^m[b]]^g>>>8;p=g},d(){return 4294967295^p}}})(),r=e.length;n.p(e);var i,s,o,a,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),l=8,(function(p,m,g,b,x,k){var w=p.length,C=new ts(b+w+5*(1+Math.floor(w/7e3))+x),E=C.subarray(b,C.length-x),A=0;if(!m||8>w)for(var R=0;w>=R;R+=65535){var P=R+65535;w>P?A=v4(E,A,p.subarray(R,P)):(E[R]=!0,A=v4(E,A,p.subarray(R,w)))}else{for(var I=TW[m-1],T=I>>>13,L=8191&I,M=(1<<g)-1,D=new vi(32768),O=new vi(M+1),F=Math.ceil(g/3),Z=2*F,V=function(Ae){return(p[Ae]^p[Ae+1]<<F^p[Ae+2]<<Z)&M},U=new Ld(25e3),K=new vi(288),W=new vi(32),G=0,j=0,H=(R=0,0),B=0,N=0;w>R;++R){var q=V(R),X=32767&R,te=O[q];if(D[X]=te,O[q]=X,R>=B){var ie=w-R;if((G>7e3||H>24576)&&ie>423){A=VS(p,E,0,U,K,W,j,H,N,R-N,A),H=G=j=0,N=R;for(var Y=0;286>Y;++Y)K[Y]=0;for(Y=0;30>Y;++Y)W[Y]=0}var J=2,ue=0,be=L,Me=X-te&32767;if(ie>2&&q==V(R-Me))for(var _e=Math.min(T,ie)-1,ke=Math.min(32767,R),$e=Math.min(258,ie);ke>=Me&&--be&&X!=te;){if(p[R+J]==p[R+J-Me]){for(var Qe=0;$e>Qe&&p[R+Qe]==p[R+Qe-Me];++Qe);if(Qe>J){if(J=Qe,ue=Me,Qe>_e)break;var He=Math.min(Me,Qe-2),ze=0;for(Y=0;He>Y;++Y){var ye=R-Me+Y+32768&32767,nt=ye-D[ye]+32768&32767;nt>ze&&(ze=nt,te=ye)}}}Me+=(X=te)-(te=D[X])+32768&32767}if(ue){U[H++]=268435456|m4[J]<<18|FS[ue];var $t=31&m4[J],ve=31&FS[ue];j+=X8[$t]+Q8[ve],++K[257+$t],++W[ve],B=R+J,++G}else U[H++]=p[R],++K[p[R]]}}A=VS(p,E,!0,U,K,W,j,H,N,R-N,A)}return d9(C,0,b+u9(A)+x)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),f=u.length;return(function(p,m){var g=m.filename;if(p[0]=31,p[1]=139,p[2]=8,p[8]=2>m.level?4:m.level==9?2:0,p[9]=3,m.mtime!=0&&Ab(p,4,Math.floor(new Date(m.mtime||Date.now())/1e3)),g){p[3]=8;for(var b=0;g.length>=b;++b)p[b+10]=g.charCodeAt(b)}})(u,t),Ab(u,f-8,n.d()),Ab(u,f-4,r),u}var RW=!!Fw||!!jw,f9="text/plain",_g=!1,MW=(e,t)=>{var[n,r]=e.split("#"),[i,s]=n.split("?");if(!s)return e;var o=s.split("&").filter((a=>a.split("=")[0]!==t)).join("&");return i+(o?"?"+o:"")+(r?"#"+r:"")},wv=function(e,t,n){var r;n===void 0&&(n=!0);var[i,s]=e.split("?"),o=Oe({},t),a=(r=s==null?void 0:s.split("&").map((u=>{var f,[p,m]=u.split("="),g=n&&(f=o[p])!==null&&f!==void 0?f:m;return delete o[p],p+"="+g})))!==null&&r!==void 0?r:[],l=(function(u,f){var p,m;f===void 0&&(f="&");var g=[];return Rn(u,(function(b,x){We(b)||We(x)||x==="undefined"||(p=encodeURIComponent((k=>k instanceof File)(b)?b.name:b.toString()),m=encodeURIComponent(x),g[g.length]=m+"="+p)})),g.join(f)})(o);return l&&a.push(l),i+"?"+a.join("&")},Qu=(e,t)=>JSON.stringify(e,((n,r)=>typeof r=="bigint"?r.toString():r),t),HS=e=>{if(e.tr)return e.tr;var{data:t,compression:n}=e;if(t){if(n===no.GZipJS){var r=IW((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var f=new ts(a.length+(a.length>>>1)),p=0,m=function(k){f[p++]=k},g=0;u>g;++g){if(p+5>f.length){var b=new ts(p+8+(u-g<<1));b.set(f),f=b}var x=a.charCodeAt(g);128>x?m(x):2048>x?(m(192|x>>>6),m(128|63&x)):x>55295&&57344>x?(m(240|(x=65536+(1047552&x)|1023&a.charCodeAt(++g))>>>18),m(128|x>>>12&63),m(128|x>>>6&63),m(128|63&x)):(m(224|x>>>12),m(128|x>>>6&63),m(128|63&x))}return d9(f,0,p)})(Qu(t)),{mtime:0});return{contentType:f9,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(n===no.Base64){var i=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Qu(t)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Qu(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Qu(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Tb=e=>{var t,n,r,i=HS(e);return!i||(n=e.compression,r=up(e.url,"compression"),n!==xS.GZipJS&&r!==xS.GZipJS&&r!=="gzip")||((t=i.body)instanceof ArrayBuffer?Ow(new Uint8Array(t)):ArrayBuffer.isView(t)&&Ow(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)))?{url:e.url,encodedBody:i}:(_g=!0,{url:MW(e.url,"compression"),encodedBody:HS(Oe({},e,{compression:void 0,tr:void 0}))})},$W=(function(){var e=$i((function*(t){var n=Qu(t.data),r=yield(function(s,o,a){return Vw.apply(this,arguments)})(n,wr.DEBUG,{rethrow:!0});if(!r)return t;var i=yield r.arrayBuffer();return Oe({},t,{tr:{contentType:f9,body:i,estimatedSize:i.byteLength}})}));return function(t){return e.apply(this,arguments)}})(),BS=(e,t)=>wv(e,{_:new Date().getTime().toString(),ver:wr.JS_SDK_VERSION,compression:t}),kg=[];jw&&kg.push({transport:"fetch",method(e){var t,{url:n,encodedBody:r}=Tb(e),{contentType:i,body:s,estimatedSize:o}=r??{},a=new Headers;Rn(e.headers,(function(f,p){a.append(p,f)})),i&&a.append("Content-Type",i);var l=null;if(vS){var u=new vS;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),e.timeout)}}jw(n,Oe({method:(e==null?void 0:e.method)||"GET",headers:a,keepalive:e.method==="POST"&&52428.8>(o||0),body:s,signal:(t=l)==null?void 0:t.signal},e.fetchOptions)).then((f=>f.text().then((p=>{var m={statusCode:f.status,text:p};if(f.status===200)try{m.json=JSON.parse(p)}catch(g){Ue.error(g)}e.callback==null||e.callback(m)})))).catch((f=>{Ue.error(f),e.callback==null||e.callback({statusCode:0,error:f})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Fw&&kg.push({transport:"XHR",method(e){var t=new Fw,{url:n,encodedBody:r}=Tb(e);t.open(e.method||"GET",n,!0);var{contentType:i,body:s}=r??{};Rn(e.headers,(function(o,a){t.setRequestHeader(a,o)})),i&&t.setRequestHeader("Content-Type",i),e.timeout&&(t.timeout=e.timeout),e.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var o={statusCode:t.status,text:t.responseText};if(t.status===200)try{o.json=JSON.parse(t.responseText)}catch{}e.callback==null||e.callback(o)}},t.send(s)}}),Ni!=null&&Ni.sendBeacon&&kg.push({transport:"sendBeacon",method(e){try{var{url:t,encodedBody:n}=Tb(e),r=wv(t,{beacon:"1"}),{contentType:i,body:s}=n??{};if(!s)return;var o=s instanceof Blob?s:new Blob([s],{type:i});Ni.sendBeacon(r,o)}catch{}}});var y4=3e3;class DW{constructor(t,n){this.qr=!0,this.jr=[],this.Hr=ao((n==null?void 0:n.flush_interval_ms)||y4,250,5e3,Ue.createLogger("flush interval"),y4),this.Ur=t}enqueue(t){this.jr.push(t),this.Br||this.zr()}unload(){this.Vr();var t=this.jr.length>0?this.Wr():{},n=Object.values(t);[...n.filter((r=>r.url.indexOf("/e")===0)),...n.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Ur(Oe({},r,{transport:"sendBeacon"}))}))}enable(){this.qr=!1,this.zr()}zr(){var t=this;this.qr||(this.Br=setTimeout((()=>{if(this.Vr(),this.jr.length>0){var n=this.Wr(),r=function(){var s=n[i],o=new Date().getTime();s.data&&sn(s.data)&&Rn(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),t.Ur(s)};for(var i in n)r()}}),this.Hr))}Vr(){clearTimeout(this.Br),this.Br=void 0}Wr(){var t={};return Rn(this.jr,(n=>{var r,i=n,s=(i?i.batchKey:null)||i.url;We(t[s])&&(t[s]=Oe({},i,{data:[]})),(r=t[s].data)==null||r.push(i.data)})),this.jr=[],t}}var NW=["retriesPerformedSoFar"];class LW{constructor(t){this.Zr=!1,this.Gr=3e3,this.jr=[],this._instance=t,this.jr=[],this.Qr=!0,!We(me)&&"onLine"in me.navigator&&(this.Qr=me.navigator.onLine,this.Jr=()=>{this.Qr=!0,this.Kr()},this.Yr=()=>{this.Qr=!1},Wn(me,"online",this.Jr),Wn(me,"offline",this.Yr))}get length(){return this.jr.length}retriableRequest(t){var{retriesPerformedSoFar:n}=t,r=dM(t,NW);Fo(n)&&(r.url=wv(r.url,{retry_count:n})),this._instance._send_request(Oe({},r,{callback:i=>{i.statusCode===200||i.statusCode>=400&&500>i.statusCode||(n??0)>=10?r.callback==null||r.callback(i):this.Xr(Oe({retriesPerformedSoFar:n},r))}}))}Xr(t){var n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),f=Math.random()-.5;return Math.ceil(u+f*(u-l))})(n),i=Date.now()+r;this.jr.push({retryAt:i,requestOptions:t});var s="Enqueued failed request for retry in "+r;navigator.onLine||(s+=" (Browser is offline)"),Ue.warn(s),this.Zr||(this.Zr=!0,this.ei())}ei(){if(this.ti&&clearTimeout(this.ti),this.jr.length===0)return this.Zr=!1,void(this.ti=void 0);this.ti=setTimeout((()=>{this.Qr&&this.jr.length>0&&this.Kr(),this.ei()}),this.Gr)}Kr(){var t=Date.now(),n=[],r=this.jr.filter((s=>t>s.retryAt||(n.push(s),!1)));if(this.jr=n,r.length>0)for(var{requestOptions:i}of r)this.retriableRequest(i)}unload(){for(var{requestOptions:t}of(this.ti&&(clearTimeout(this.ti),this.ti=void 0),this.Zr=!1,We(me)||(this.Jr&&(me.removeEventListener("online",this.Jr),this.Jr=void 0),this.Yr&&(me.removeEventListener("offline",this.Yr),this.Yr=void 0)),this.jr))try{this._instance._send_request(Oe({},t,{transport:"sendBeacon"}))}catch(n){Ue.error(n)}this.jr=[]}}class jW{constructor(t){this.ri=()=>{var n,r,i,s;this.ii||(this.ii={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+((o==null?void 0:o.clientHeight)||0),f=(o==null?void 0:o.scrollHeight)||0;this.ii.lastScrollY=Math.ceil(a),this.ii.maxScrollY=Math.max(a,(n=this.ii.maxScrollY)!==null&&n!==void 0?n:0),this.ii.maxScrollHeight=Math.max(l,(r=this.ii.maxScrollHeight)!==null&&r!==void 0?r:0),this.ii.lastContentY=u,this.ii.maxContentY=Math.max(u,(i=this.ii.maxContentY)!==null&&i!==void 0?i:0),this.ii.maxContentHeight=Math.max(f,(s=this.ii.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=t}get ni(){return this._instance.config.scroll_root_selector}getContext(){return this.ii}resetContext(){var t=this.ii;return setTimeout(this.ri,0),t}startMeasuringScrollPosition(){Wn(me,"scroll",this.ri,{capture:!0}),Wn(me,"scrollend",this.ri,{capture:!0}),Wn(me,"resize",this.ri)}scrollElement(){if(!this.ni)return me==null?void 0:me.document.documentElement;var t=sn(this.ni)?this.ni:[this.ni];for(var n of t){var r=me==null?void 0:me.document.querySelector(n);if(r)return r}}scrollY(){if(this.ni){var t=this.scrollElement();return t&&t.scrollTop||0}return me&&(me.scrollY||me.pageYOffset||me.document.documentElement.scrollTop)||0}scrollX(){if(this.ni){var t=this.scrollElement();return t&&t.scrollLeft||0}return me&&(me.scrollX||me.pageXOffset||me.document.documentElement.scrollLeft)||0}}var FW=e=>r9(e==null?void 0:e.config.mask_personal_data_properties,e==null?void 0:e.config.custom_personal_data_properties);class zS{constructor(t,n,r,i){this.si=s=>{var o=this.oi();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.ai(this._instance)};this.ui.register({[c4]:a})}},this._instance=t,this.li=n,this.ui=r,this.ai=i||FW,this.li.onSessionId(this.si)}oi(){return this.ui.props[c4]}getSetOnceProps(){var t,n=(t=this.oi())==null?void 0:t.props;return n?"r"in n?i9(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 Rn(Y8(this.getSetOnceProps()),((n,r)=>{r==="$current_url"&&(r="url"),t["$session_entry_"+Hw(r)]=n})),t}}class J8{constructor(){this.hi={}}on(t,n){return this.hi[t]||(this.hi[t]=[]),this.hi[t].push(n),()=>{this.hi[t]=this.hi[t].filter((r=>r!==n))}}emit(t,n){for(var r of this.hi[t]||[])r(n);for(var i of this.hi["*"]||[])i(t,n)}}var Pb=Ln("[SessionId]");class US{on(t,n){return this.ci.on(t,n)}constructor(t,n,r){var i;if(this.di=null,this.vi=[],this.fi=void 0,this.ci=new J8,this.pi=(u,f)=>!(!Fo(u)||!Fo(f))&&Math.abs(u-f)>this.sessionTimeoutMs,!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.cookieless_mode===Go)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.qt=t.config,this.ui=t.persistence,this.gi=void 0,this.mi=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.yi=n||Ga,this.bi=r||Ga;var s=this.qt.persistence_name||this.qt.token;if(this._sessionTimeoutMs=1e3*ao(this.qt.session_idle_timeout_seconds||1800,60,36e3,Pb.createLogger("session_idle_timeout_seconds"),1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.wi(),this.xi="ph_"+s+"_window_id",this.Si="ph_"+s+"_primary_window_exists",this.ki()){var o=Ir.F(this.xi),a=Ir.F(this.Si);o&&!a?this.gi=o:Ir.q(this.xi),Ir.N(this.Si,!0)}if((i=this.qt.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var f=this.qt.bootstrap.sessionID.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})();this.Ci(this.qt.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Pb.error("Invalid sessionID in bootstrap",u)}this.Ii()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return We(this.vi)&&(this.vi=[]),this.vi.push(t),this.mi&&t(this.mi,this.gi),()=>{this.vi=this.vi.filter((n=>n!==t))}}ki(){return this.qt.persistence!=="memory"&&!this.ui.wr&&Ir.O()}Ti(t){t!==this.gi&&(this.gi=t,this.ki()&&Ir.N(this.xi,t))}Ei(){return this.gi?this.gi:this.ki()?Ir.F(this.xi):null}Mi(t){var n=this.di;return!es(n)&&!es(t)&&5e3>Math.abs(t-n)}Ci(t,n,r){var i=n!==this._sessionActivityTimestamp,s=!(t!==this.mi||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.mi=t,s&&!i||s&&this.Mi(n)||(this.di=n,this.ui.register({[Yu]:[n,t,r]}))}Ri(){var t,n=(t=this.qt)==null?void 0:t.persistence_save_debounce_ms;return Fo(n)&&n>0}Pi(){var t;if(!es(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.di){this.Ri()?this.ui.refreshKey(Yu):(this.ui.flush(),this.ui.load());var[,n,r]=this.Oi();n===this.mi&&r===this._sessionStartTimestamp&&(this.di=this._sessionActivityTimestamp,this.ui.register({[Yu]:[this._sessionActivityTimestamp,(t=this.mi)!==null&&t!==void 0?t:null,this._sessionStartTimestamp]}),this.ui.flush())}}Li(){var[t]=this.Oi(),n=Fo(t)?t:0,r=Fo(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,r)}Oi(){var t=this.ui.props[Yu];return sn(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this.di=null,clearTimeout(this.Fi),this.Fi=void 0,this.Ci(null,null,null)}destroy(){this.Pi(),clearTimeout(this.Fi),this.Fi=void 0,this.fi&&me&&(me.removeEventListener(l1,this.fi,{capture:!1}),this.fi=void 0),this.vi=[]}Ii(){this.fi=()=>{this.Pi(),this.ki()&&Ir.q(this.Si)},Wn(me,l1,this.fi,{capture:!1})}checkAndGetSessionAndWindowId(t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),this.qt.cookieless_mode===Go)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[,i,s]=this.Oi(),o=this.Li(),a=this.Ei(),l=Fo(s)&&Math.abs(r-s)>864e5,u=!1,f=!i,p=!f&&!t&&this.pi(r,o);f||p||l?(i=this.yi(),a=this.bi(),Pb.info("new session ID generated",{sessionId:i,windowId:a,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}}),s=r,u=!0):a||(a=this.bi(),u=!0);var m=Fo(o)&&t&&!l?o:r,g=Fo(s)?s:new Date().getTime();return this.Ti(a),this.Ci(i,m,g),t||this.wi(),u&&this.vi.forEach((b=>b(i,a,u?{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}:void 0))),{sessionId:i,windowId:a,sessionStartTimestamp:g,changeReason:u?{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:o}}wi(){clearTimeout(this.Fi),this.Fi=setTimeout((()=>{var t=this.Li();if(this.pi(new Date().getTime(),t)){var n=this.mi;this.resetSessionId(),this.ci.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}}var h9=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&_S(n,t))return!0;try{var r=e==null?void 0:e.userAgentData;if(r!=null&&r.brands&&r.brands.some((i=>_S(i==null?void 0:i.brand,t))))return!0}catch{}return!!e.webdriver},p1=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 ZS(e,t,n){return Qu({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}var p9={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=>p1(n,r))))),not_regex:(e,t)=>t.every((n=>e.every((r=>!p1(n,r))))),icontains:(e,t)=>t.map(Tm).some((n=>e.map(Tm).some((r=>n.includes(r))))),not_icontains:(e,t)=>t.map(Tm).every((n=>e.map(Tm).every((r=>!n.includes(r))))),gt:(e,t)=>t.some((n=>{var r=parseFloat(n);return!isNaN(r)&&e.some((i=>r>parseFloat(i)))})),lt:(e,t)=>t.some((n=>{var r=parseFloat(n);return!isNaN(r)&&e.some((i=>r<parseFloat(i)))}))},Tm=e=>e.toLowerCase();function m9(e,t){return!e||Object.entries(e).every((n=>{var[r,i]=n,s=t==null?void 0:t[r];if(We(s)||es(s))return!1;var o=[String(s)],a=p9[i.operator];return!!a&&a(i.values,o)}))}var b4="custom",WS="i.posthog.com",OW=/^\/static\//;class VW{constructor(t){this.Ai={},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 flagsApiHost(){var t=this.instance.config.flags_api_host;return t?t.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var t,n=(t=this.instance.config.ui_host)==null?void 0:t.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+WS,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.Ai[this.apiHost]||(this.Ai[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":b4),this.Ai[this.apiHost]}Ni(t){var n=this.instance.config.__preview_external_dependency_versioned_paths;if(typeof n=="string"&&OW.test(t))return n.trim().replace(/\/$/,"")||void 0}endpointFor(t,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),t==="ui")return this.uiHost+n;if(t==="flags")return this.flagsApiHost+n;if(t==="assets"){var r=this.Ni(n);if(r)return""+r+n}if(this.region===b4)return this.apiHost+n;var i=WS+n;switch(t){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}var bn=Ln("[Surveys]"),x4="seenSurvey_",HW=[Cb.Popover,Cb.Widget,Cb.API],BW={ignoreConditions:!1,ignoreDelay:!1,displayType:p4.Popover},zW=Ln("[PostHog ExternalIntegrations]"),UW={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class ZW{constructor(t){this._instance=t}lr(t,n){var r;(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,t,(i=>{if(i)return zW.error("failed to load script",i);n()}))}startIfEnabledOrStop(){var t=this,n=function(o){var a,l,u;!i||(a=gt.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||t.lr(UW[o],(()=>{var f;(f=gt.__PosthogExtensions__)==null||(f=f.integrations)==null||(f=f[o])==null||f.start(t._instance)})),!i&&(l=gt.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=gt.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[r,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n(r)}}}var Eu,Wh={},Ib=0,w4=()=>{},GS='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',oh="Surveys module not available",qS="sanitize_properties is deprecated. Use before_send instead",g9="Invalid value for property_denylist config: ",Zu="posthog",v9=!RW&&(ui==null?void 0:ui.indexOf("MSIE"))===-1&&(ui==null?void 0:ui.indexOf("Mozilla"))===-1,KS=e=>{var t;return Oe({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:aW(Ze==null?void 0:Ze.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:w4,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,debug:Pr&&Nn(Pr==null?void 0:Pr.search)&&Pr.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_conversations:!1,disable_product_tours:!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,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){Ue.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:h4,before_send:void 0,request_queue_config:{flush_interval_ms:y4},error_tracking:{},_onCapture:w4,__preview_eager_load_replay:!1},(n=>({rageclick:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0}))(e))},WW=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["store_google","save_campaign_params"],["verbose","debug"]],YS=e=>{var t={};for(var[n,r]of WW)We(e[n])||(t[r]=e[n]);var i=qn({},t,e);return sn(e.property_blacklist)&&(We(e.property_denylist)?i.property_denylist=e.property_blacklist:sn(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ue.error(g9+e.property_denylist)),i};class GW{constructor(){this.__forceAllowLocalhost=!1}get Di(){return this.__forceAllowLocalhost}set Di(t){Ue.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class Xi{$i(t,n){if(t){var r=this.qi.indexOf(t);r!==-1&&this.qi.splice(r,1)}return this.qi.push(n),n.initialize==null||n.initialize(),n}ji(){return this.config.cookieless_mode===Go||this.config.cookieless_mode===rc&&this.consent.isRejected()}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(){var t;this.webPerformance=new GW,this.Hi=!1,this.version=wr.LIB_VERSION,this.Ui=new J8,this.qi=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=KS(),this.SentryIntegration=vW,this.sentryIntegration=r=>(function(i,s){var o=QM(i,s);return{name:XM,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Bi=!1,this.zi=null,this.Vi=null,this.Wi=null,this.scrollManager=new jW(this),this.pageViewManager=new $S(this),this.rateLimiter=new EW(this),this.requestRouter=new VW(this),this.consent=new pW(this),this.externalIntegrations=new ZW(this);var n=(t=Xi.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(r,i,s)=>{var o=Nn(r)?{[r]:i}:r;this.setPersonProperties(o),s==null||s({})},set_once:(r,i,s)=>{var o=Nn(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),s==null||s({})}},this.on("eventCaptured",(r=>Ue.info('send "'+(r==null?void 0:r.event)+'"',r)))}init(t,n,r){if(r&&r!==Zu){var i,s=(i=Wh[r])!==null&&i!==void 0?i:new Xi;return s._init(t,n,r),Wh[r]=s,Wh[Zu][r]=s,s}return this._init(t,n,r)}_init(t,n,r){var i,s;n===void 0&&(n={});var o=Nn(t)?t.trim():"";if(!o)return Ue.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.Zi(n.debug),this.Gi=n,this.Qi=[],n.person_profiles?this.Vi=n.person_profiles:n.process_person&&(this.Vi=n.process_person),this.set_config(qn({},KS(n.defaults),YS(n),{name:r,token:o})),this.config.on_xhr_error&&Ue.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:no.GZipJS;var a=this.Ji();this.persistence=new kb(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new kb(Oe({},this.config,{persistence:"sessionStorage"}),a);var l=Oe({},this.persistence.props),u=Oe({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Ki=new DW((w=>this.Yi(w)),this.config.request_queue_config),this.Xi=new LW(this),this.__request_queue=[];var f=this.ji();if(f||(this.sessionManager=new US(this),this.sessionPropsManager=new zS(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Ue.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.en(f)}),0)):(Ue.info("Initializing extensions synchronously"),this.en(f)),wr.DEBUG=wr.DEBUG||this.config.debug,wr.DEBUG&&Ue.info("Starting in debug mode",{this:this,config:n,thisC:Oe({},this.config),p:l,s:u}),!this.config.identity_distinct_id||(i=n.bootstrap)!=null&&i.distinctID||(n.bootstrap=Oe({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var p=n.bootstrap.distinctID,m=this.get_distinct_id(),g=this.persistence.get_property(xs);if(n.bootstrap.isIdentifiedID&&m!=null&&m!==p&&g===_u)this.identify(p);else if(n.bootstrap.isIdentifiedID&&m!=null&&m!==p&&g===ku)Ue.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ga()),x=n.bootstrap.isIdentifiedID?b:p;this.persistence.set_property(xs,n.bootstrap.isIdentifiedID?ku:_u),this.register({distinct_id:p,$device_id:x})}}if(f)this.register_once({distinct_id:km,$device_id:null},"");else if(!this.get_distinct_id()){var k=this.config.get_device_id(Ga());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(xs,_u)}return Wn(me,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(w,C){var E=w.config.segment;if(!E)return C();(function(A,R){var P=A.config.segment;if(!P)return R();var I=L=>{var M=()=>L.anonymousId()||Ga();A.config.get_device_id=M,L.id()&&(A.register({distinct_id:L.id(),$device_id:M()}),A.persistence.set_property(xs,ku)),R()},T=P.user();"then"in T&&zo(T.then)?T.then(I):I(T)})(w,(()=>{E.register((A=>{Promise&&Promise.resolve||_b.warn("This browser does not have Promise support, and can not use the segment integration");var R=(P,I)=>{if(!I)return P;P.event.userId||P.event.anonymousId===A.get_distinct_id()||(_b.info("No userId set, resetting PostHog"),A.reset()),P.event.userId&&P.event.userId!==A.get_distinct_id()&&(_b.info("UserId set, identifying with PostHog"),A.identify(P.event.userId));var T=A.calculateEventProperties(I,P.event.properties);return P.event.properties=Object.assign({},T,P.event.properties),P};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:P=>R(P,P.event.event),page:P=>R(P,Uu),identify:P=>R(P,xb),screen:P=>R(P,"$screen")}})(w)).then((()=>{C()}))}))})(this,(()=>this.tn())):this.tn(),zo(this.config._onCapture)&&this.config._onCapture!==w4&&(Ue.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(w=>this.config._onCapture(w.event,w)))),this.config.ip&&Ue.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}en(t){var n,r,i,s,o,a,l,u=performance.now(),f=Oe({},Xi.__defaultExtensionClasses,this.config.__extensionClasses),p=[];f.featureFlags&&this.qi.push(this.featureFlags=(n=this.featureFlags)!==null&&n!==void 0?n:new f.featureFlags(this)),f.exceptions&&this.qi.push(this.exceptions=(r=this.exceptions)!==null&&r!==void 0?r:new f.exceptions(this)),f.historyAutocapture&&this.qi.push(this.historyAutocapture=new f.historyAutocapture(this)),f.tracingHeaders&&this.qi.push(new f.tracingHeaders(this)),f.siteApps&&this.qi.push(this.siteApps=new f.siteApps(this)),f.sessionRecording&&!t&&this.qi.push(this.sessionRecording=new f.sessionRecording(this)),this.config.disable_scroll_properties||p.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),f.autocapture&&this.qi.push(this.autocapture=new f.autocapture(this)),f.surveys&&this.qi.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new f.surveys(this)),f.logs&&this.qi.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new f.logs(this)),f.conversations&&this.qi.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new f.conversations(this)),f.productTours&&this.qi.push(this.productTours=new f.productTours(this)),f.heatmaps&&this.qi.push(this.heatmaps=new f.heatmaps(this)),f.webVitalsAutocapture&&this.qi.push(this.webVitalsAutocapture=new f.webVitalsAutocapture(this)),f.exceptionObserver&&this.qi.push(this.exceptionObserver=new f.exceptionObserver(this)),f.deadClicksAutocapture&&this.qi.push(this.deadClicksAutocapture=new f.deadClicksAutocapture(this,gW)),f.toolbar&&this.qi.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new f.toolbar(this)),f.experiments&&this.qi.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new f.experiments(this)),this.qi.forEach((m=>{m.initialize&&p.push((()=>{m.initialize==null||m.initialize()}))})),p.push((()=>{if(this.rn){var m=this.rn;this.rn=void 0,this.Ar(m)}})),this.nn(p,u)}nn(t,n){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&t.length>0)return void setTimeout((()=>{this.nn(t,n)}),0);var r=t.shift();if(r)try{r()}catch(s){Ue.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-n);this.register_for_session({[WM]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[GM]:i}),this.config.__preview_deferred_init_extensions&&Ue.info("PostHog extensions initialized ("+i+"ms)")}Ar(t){var n;if(!Ze||!Ze.body)return Ue.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Ar(t)}),500);this.config.__preview_deferred_init_extensions&&(this.rn=t),this.sn=t,this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=At(t.supportedCompression,no.GZipJS)?no.GZipJS:At(t.supportedCompression,no.Base64)?no.Base64:void 0),(n=t.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this.Vi?this.Vi:h4}),this.qi.forEach((r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(t)))}tn(){try{this.config.loaded(this)}catch(r){Ue.critical("`loaded` function failed",r)}if(this.an(),this.config.internal_or_test_user_hostname&&Pr!=null&&Pr.hostname){var t=Pr.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?t===n:n.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.ji())&&this.un()}),1),this.ln=new o9(this),this.ln.load()}an(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.Ki)==null||t.enable())}_dom_loaded(){this.is_capturing()&&Cm(this.__request_queue,(t=>this.Yi(t))),this.__request_queue=[],this.an()}_handle_unload(){var t,n,r,i;(t=this.surveys)==null||t.handlePageUnload(),this.config.request_batching?(this.hn()&&this.capture(bb),(n=this.logs)==null||n.flushLogs("sendBeacon"),(r=this.Ki)==null||r.unload(),(i=this.Xi)==null||i.unload()):this.hn()&&this.capture(bb,null,{transport:"sendBeacon"})}_send_request(t){this.__loaded&&(v9?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=wv(t.url,{ip:this.config.ip?1:0}),t.headers=Oe({},this.config.request_headers,t.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,i,s,o=Oe({},n);o.timeout=o.timeout||6e4,o.url=BS(o.url,o.compression);var a=(r=o.transport)!==null&&r!==void 0?r:"fetch",l=kg.filter((f=>!o.disableTransport||!f.transport||!o.disableTransport.includes(f.transport))),u=(i=(s=(function(f,p){for(var m=0;f.length>m;m++)if(f[m].transport===a)return f[m]})(l))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");a!=="sendBeacon"&&o.data&&o.compression===no.GZipJS&&gZ&&!_g?$W(o).then((f=>{u(f)})).catch((f=>{if(wS(f))return _g=!0,void u(Oe({},o,{compression:void 0,url:BS(n.url,void 0)}));(p=>{if(!p||typeof p!="object")return!1;var m="name"in p?String(p.name):"";return wS(p)||m===fM})(f)&&(_g=!0),u(o)})):u(o)})(Oe({},t,{callback:n=>{var r,i;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,n),t.callback==null||t.callback(n)}}))))}Yi(t){this.Xi?this.Xi.retriableRequest(t):this._send_request(t)}_execute_array(t){Ib++;try{var n,r=[],i=[],s=[];Cm(t,(a=>{if(a)if(sn(n=a[0]))s.push(a);else if(zo(a))try{a.call(this)}catch(l){Ue.error("Error executing queued PostHog call",a,l)}else sn(a)&&n==="alias"?r.push(a):sn(a)&&n.indexOf("capture")!==-1&&zo(this[n])?s.push(a):i.push(a)}));var o=function(a,l){Cm(a,(function(u){try{if(sn(u[0])){var f=l;Rn(u,(function(p){f=f[p[0]].apply(f,p.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(p){Ue.error("Error executing queued PostHog call",u,p)}}))};o(r,this),o(i,this),o(s,this)}finally{Ib--}}push(t){if(Ib>0&&sn(t)&&Nn(t[0])){var n=Xi.prototype[t[0]];zo(n)&&n.apply(this,t.slice(1))}else this._execute_array([t])}capture(t,n,r){var i,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Ki){if(this.is_capturing())if(!We(t)&&Nn(t)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var f=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(f==null||!f.isRateLimited){n!=null&&n.$current_url&&!Nn(n==null?void 0:n.$current_url)&&(Ue.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),t!=="$exception"||r!=null&&r.cn||Ue.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&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 p=new Date,m=(r==null?void 0:r.timestamp)||p,g=(r==null?void 0:r.uuid)||Ga(),b={uuid:g,event:t,properties:this.calculateEventProperties(t,n||{},m,g)};t===Uu&&this.config.__preview_capture_bot_pageviews&&u&&(b.event="$bot_pageview",b.properties.$browser_type="bot"),f&&(b.properties.$lib_rate_limit_remaining_tokens=f.remainingTokens),r!=null&&r.$set&&(b.$set=r==null?void 0:r.$set);var x,k,w,C=this.dn(r==null?void 0:r.$set_once,t!==PS,t===xb);if(C&&(b.$set_once=C),r!=null&&r._noTruncate||(s=this.config.properties_string_max_length,o=b,a=L=>Nn(L)?L.slice(0,s):L,l=new Set,b=(function L(M,D){return M!==Object(M)?a?a(M):M:l.has(M)?void 0:(l.add(M),sn(M)?(O=[],Cm(M,(F=>{O.push(L(F))}))):(O={},Rn(M,((F,Z)=>{l.has(F)||(O[Z]=L(F))}))),O);var O})(o)),b.timestamp=m,We(r==null?void 0:r.timestamp)||(b.properties.$event_time_override_provided=!0,b.properties.$event_time_override_system_time=p),t===Ih.DISMISSED||t===Ih.SENT){var E=n==null?void 0:n[Eb.SURVEY_ID],A=n==null?void 0:n[Eb.SURVEY_ITERATION];(L=>{try{var M=(D=>((O,F)=>{var Z=""+x4+F.id;return F.current_iteration&&F.current_iteration>0&&(Z=""+x4+F.id+"_"+F.current_iteration),Z})(0,D))(L);if(localStorage.getItem(M))return;localStorage.setItem(M,"true")}catch(D){bn.error("Failed to persist survey seen state",D)}})({id:E,current_iteration:A}),b.$set=Oe({},b.$set,{[(x={id:E,current_iteration:A},k=t===Ih.SENT?"responded":"dismissed",w="$survey_"+k+"/"+x.id,x.current_iteration&&x.current_iteration>0&&(w="$survey_"+k+"/"+x.id+"/"+x.current_iteration),w)]:!0})}else t===Ih.SHOWN&&(b.$set=Oe({},b.$set,{[Eb.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(t===CW.SHOWN){var R=n==null?void 0:n[NS.TOUR_TYPE];R&&(b.$set=Oe({},b.$set,{[NS.TOUR_LAST_SEEN_DATE+"/"+R]:new Date().toISOString()}))}var P=Oe({},b.properties.$set,b.$set);if(Ku(P)||this.setPersonPropertiesForFlags(P),!Kt(this.config.before_send)){var I=this.vn(b);if(!I)return;b=I}this.Ui.emit("eventCaptured",b);var T={method:"POST",url:(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:b,compression:"best-available",batchKey:r==null?void 0:r._batchKey,transport:r==null?void 0:r.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Yi(T):this.Ki.enqueue(T),b}Ue.critical("This capture call is ignored due to client rate limiting.")}}else Ue.error("No event name provided to posthog.capture")}else Ue.uninitializedWarning("posthog.capture")}_addCaptureHook(t){return this.on("eventCaptured",(n=>t(n.event,n)))}calculateEventProperties(t,n,r,i,s){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(t),a=Oe({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.ji()&&(a.$cookieless_mode=!0),t==="$snapshot"){var l=Oe({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Nn(a.distinct_id)&&!Hi(a.distinct_id)||Bw(a.distinct_id))&&Ue.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,f=(function(w,C){var E,A,R,P;if(!ui)return{};var I,T,L,M,D,O,F,Z,V,U=w?[...Nd,...C||[]]:[],[K,W]=(function(H){for(var B=0;ES.length>B;B++){var[N,q]=ES[B],X=N.exec(H),te=X&&(zo(q)?q(X,H):q);if(te)return te}return["",""]})(ui),G=(I=typeof navigator<"u"?navigator:void 0)!=null&&I.brave?{brave:!0}:{},j=qn(Y8({$os:K,$os_version:W,$browser:DM(ui,navigator.vendor,G),$device:SS(ui),$device_type:(L=ui,M={userAgentDataPlatform:(E=navigator)==null||(E=E.userAgentData)==null?void 0:E.platform,maxTouchPoints:(A=navigator)==null?void 0:A.maxTouchPoints,screenWidth:me==null||(R=me.screen)==null?void 0:R.width,screenHeight:me==null||(P=me.screen)==null?void 0:P.height,devicePixelRatio:me==null?void 0:me.devicePixelRatio},V=SS(L),V===vM||V===gM||V==="Kobo"||V==="Kindle Fire"||V===IM?Md:V===lp||V===ud||V===cp||V===Uw?"Console":V===bM?"Wearable":V?Li:(M==null?void 0:M.userAgentDataPlatform)==="Android"&&((D=M==null?void 0:M.maxTouchPoints)!==null&&D!==void 0?D:0)>0?600>Math.min((O=M==null?void 0:M.screenWidth)!==null&&O!==void 0?O:0,(F=M==null?void 0:M.screenHeight)!==null&&F!==void 0?F:0)/((Z=M==null?void 0:M.devicePixelRatio)!==null&&Z!==void 0?Z:1)?Li:Md:"Desktop"),$timezone:s9(),$timezone_offset:_W()}),{$current_url:dp(Pr==null?void 0:Pr.href,U,fp),$host:Pr==null?void 0:Pr.host,$pathname:Pr==null?void 0:Pr.pathname,$raw_user_agent:ui.length>1e3?ui.substring(0,997)+"...":ui,$browser_version:$Z(ui,navigator.vendor,G),$browser_language:DS(),$browser_language_prefix:(T=DS(),typeof T=="string"?T.split("-")[0]:void 0),$screen_height:me==null?void 0:me.screen.height,$screen_width:me==null?void 0:me.screen.width,$viewport_height:me==null?void 0:me.innerHeight,$viewport_width:me==null?void 0:me.innerWidth,$lib:wr.LIB_NAME,$lib_version:wr.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return wr.SDK_DIST_CHANNEL&&(j.$sdk_dist_channel=wr.SDK_DIST_CHANNEL),j})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:m}=this.sessionManager.checkAndGetSessionAndWindowId(s,r.getTime());a.$session_id=p,a.$window_id=m}this.sessionPropsManager&&qn(a,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&qn(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(g=this.Xi)==null?void 0:g.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===b4&&(a.$lib_custom_api_host=this.config.api_host),u=t!==Uu||s?t!==bb||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=qn(a,u),t===Uu&&Ze&&(a.title=Ze.title),!We(o)){var b=r.getTime()-o;a.$duration=parseFloat((b/1e3).toFixed(3))}ui&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=qn({},f,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),sn(this.config.property_denylist)?Rn(this.config.property_denylist,(function(w){delete a[w]})):Ue.error(g9+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&(Ue.error(qS),a=x(a,t));var k=this.fn();return a.$process_person_profile=k,k&&!s&&this.pn("_calculate_event_properties"),a}dn(t,n,r){var i;if(n===void 0&&(n=!0),r===void 0&&(r=!1),!this.persistence||!this.fn()||this.Hi&&!r)return t;var s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=qn({},s,o||{},t||{}),l=this.config.sanitize_properties;return l&&(Ue.error(qS),a=l(a,"$set_once")),n&&(this.Hi=!0),Ku(a)?void 0:a}register(t,n){var r;(r=this.persistence)==null||r.register(t,n)}register_once(t,n,r){var i;(i=this.persistence)==null||i.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)}gn(t,n){this.register({[t]:n})}getFeatureFlag(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(t,n)}getFeatureFlagPayload(t){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(t)}getFeatureFlagResult(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(t,n)}isFeatureEnabled(t,n){var r;return(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(t,n)}reloadFeatureFlags(){var t;(t=this.featureFlags)==null||t.reloadFeatureFlags()}updateFlags(t,n,r){var i;(i=this.featureFlags)==null||i.updateFlags(t,n,r)}updateEarlyAccessFeatureEnrollment(t,n,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(t,n,r)}getEarlyAccessFeatures(t,n,r){var i;return n===void 0&&(n=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(t,n,r)}on(t,n){return this.Ui.on(t,n)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:oh}),()=>{})}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?this.surveys.getSurveys(t,n):t([],{isLoaded:!1,error:oh})}getActiveMatchingSurveys(t,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(t,n):t([],{isLoaded:!1,error:oh})}renderSurvey(t,n){var r;(r=this.surveys)==null||r.renderSurvey(t,n)}displaySurvey(t,n){var r;n===void 0&&(n=BW),(r=this.surveys)==null||r.displaySurvey(t,n)}cancelPendingSurvey(t){var n;(n=this.surveys)==null||n.cancelPendingSurvey(t)}canRenderSurvey(t){var n,r;return(n=(r=this.surveys)==null?void 0:r.canRenderSurvey(t))!==null&&n!==void 0?n:{visible:!1,disabledReason:oh}}canRenderSurveyAsync(t,n){var r,i;return n===void 0&&(n=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(t,n))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:oh})}mn(t){return!t||Bw(t)?(Ue.critical("Unique user id has not been set in posthog.identify"),!1):t===km?(Ue.critical('The string "'+t+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(Ue.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.'),!1)}identify(t,n,r){if(!this.__loaded||!this.persistence)return Ue.uninitializedWarning("posthog.identify");if(Hi(t)&&(t=t.toString(),Ue.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.mn(t)&&this.pn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:t}),this.get_property(r1)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),t!==i&&t!==this.get_property(Sh)&&(this.unregister(Sh),this.register({distinct_id:t}));var s,o=(this.persistence.get_property(xs)||_u)===_u;t!==i&&o?(this.persistence.set_property(xs,ku),this.setPersonPropertiesForFlags({$set:n||{},$set_once:r||{}},!1),this.capture(xb,{distinct_id:t,$anon_distinct_id:i},{$set:n||{},$set_once:r||{}}),this.Wi=ZS(t,n,r),(s=this.featureFlags)==null||s.setAnonymousDistinctId(i)):(n||r)&&this.setPersonProperties(n,r),t!==i&&(this.reloadFeatureFlags(),this.unregister(Uh))}}setPersonProperties(t,n){if((t||n)&&this.pn("posthog.setPersonProperties")){var r=ZS(this.get_distinct_id(),t,n);this.Wi!==r?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:n||{}},!0),this.capture("$set",{$set:t||{},$set_once:n||{}}),this.Wi=r):Ue.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(t,n,r){if(t&&n){var i=this.getGroups(),s=i[t]!==n;if(s&&this.resetGroupPropertiesForFlags(t),this.register({$groups:Oe({},i,{[t]:n})}),s||r){var o={$group_type:t,$group_key:n};r&&(o.$group_set=r),this.capture(PS,o)}r&&this.setGroupPropertiesForFlags({[t]:r}),s&&!r&&this.reloadFeatureFlags()}else Ue.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(t,n)}resetPersonPropertiesForFlags(){var t;(t=this.featureFlags)==null||t.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),this.pn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(t,n))}resetGroupPropertiesForFlags(t){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(t)}reset(t){var n,r,i,s,o,a,l,u;if(Ue.info("reset"),!this.__loaded)return Ue.uninitializedWarning("posthog.reset");var f,p=this.get_property(r1),m=this.get_property(lc);if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),We(m)||(f=this.persistence)==null||f.register({[lc]:m}),(i=this.surveys)==null||i.reset(),(s=this.ln)==null||s.stop(),(o=this.featureFlags)==null||o.reset(),(a=this.conversations)==null||a.reset(),(l=this.persistence)==null||l.set_property(xs,_u),(u=this.sessionManager)==null||u.resetSessionId(),this.Wi=null,this.config.cookieless_mode===Go)this.register_once({distinct_id:km,$device_id:null},"");else{var g=this.config.get_device_id(Ga());this.register_once({distinct_id:g,$device_id:t?g:p},"")}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}setIdentity(t,n){var r;this.config.identity_distinct_id=t,this.config.identity_hash=n,this.alias(t),(r=this.conversations)==null||r.yn()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,(t=this.conversations)==null||t.bn()}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),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(t!=null&&t.withTimestamp&&r){var s,o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(t,n){return t===this.get_property(VM)?(Ue.critical("Attempting to create alias for existing People user - aborting."),-2):this.pn("posthog.alias")?(We(n)&&(n=this.get_distinct_id()),t!==n?(this.gn(Sh,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(Ue.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n=Oe({},this.config);if(Yn(t)){var r,i,s,o,a,l,u,f,p,m;qn(this.config,YS(t));var g=this.Ji();(r=this.persistence)==null||r.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new kb(Oe({},this.config,{persistence:"sessionStorage"}),g);var b=this.Zi(this.config.debug);oo(b)&&(this.config.debug=b),oo(this.config.debug)&&(this.config.debug?(wr.DEBUG=!0,Bn.O()&&Bn.N("ph_debug",!0),Ue.info("set_config",{config:t,oldConfig:n,newConfig:Oe({},this.config)})):(wr.DEBUG=!1,Bn.O()&&Bn.q("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.exceptions)==null||s.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(l=this.heatmaps)==null||l.startIfEnabled(),(u=this.exceptionObserver)==null||u.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this._n(),(m=this.externalIntegrations)==null||m.startIfEnabledOrStop()}}_overrideSDKInfo(t,n){wr.LIB_NAME=t,wr.LIB_VERSION=n}startSessionRecording(t){var n,r,i,s,o,a=t===!0,l={sampling:a||!(t==null||!t.sampling),linked_flag:a||!(t==null||!t.linked_flag),url_trigger:a||!(t==null||!t.url_trigger),event_trigger:a||!(t==null||!t.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.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){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(t,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(Oe({},i,n))}}addExceptionStep(t,n){var r;(r=this.exceptions)==null||r.addExceptionStep(t,n)}captureLog(t){var n;(n=this.logs)==null||n.captureLog(t)}get logger(){var t,n;return(t=(n=this.logs)==null?void 0:n.logger)!==null&&t!==void 0?t:Xi.wn}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var n,r;return(n=(r=this.toolbar)==null?void 0:r.loadToolbar(t))!==null&&n!==void 0&&n}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:Zu;return n!==Zu&&(n=Zu+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)==null?void 0:t.get_property(xs))===ku||((n=this.sessionPersistence)==null?void 0:n.get_property(xs))===ku}fn(){var t,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===h4&&!this._isIdentified()&&Ku(this.getGroups())&&((t=this.persistence)==null||(t=t.props)==null||!t[Sh])&&((n=this.persistence)==null||(n=n.props)==null||!n[o1]))}hn(){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.fn()||this.pn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.pn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}pn(t){return this.config.person_profiles==="never"?(Ue.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gn(o1,!0),!0)}Ji(){if(this.config.cookieless_mode==="always")return!0;var t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==rc)}_n(){var t,n,r,i,s=this.Ji();return((t=this.persistence)==null?void 0:t.wr)!==s&&((r=this.persistence)==null||r.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.wr)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(t){var n;if(this.config.cookieless_mode!==Go){if(this.ji()){var r,i,s,o,a;this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new US(this),this.pageViewManager=new $S(this),this.persistence&&(this.sessionPropsManager=new zS(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Xi.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.$i(this.sessionRecording,new u(this)),this.sn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.sn)))}var f,p;this.consent.optInOut(!0),this._n(),this.an(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==rc&&((f=this.surveys)==null||f.loadIfEnabled()),(We(t==null?void 0:t.captureEventName)||t!=null&&t.captureEventName)&&this.capture((p=t==null?void 0:t.captureEventName)!==null&&p!==void 0?p:"$opt_in",t==null?void 0:t.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.un()}else Ue.warn(GS)}opt_out_capturing(){var t,n,r;this.config.cookieless_mode!==Go?(this.config.cookieless_mode===rc&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._n(),this.config.cookieless_mode===rc&&(this.register({distinct_id:km,$device_id:null}),(t=this.sessionRecording)==null||t.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.un(),this.an())):Ue.warn(GS)}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===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Go||(this.config.cookieless_mode===rc?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._n()}_is_bot(){return Ni?h9(Ni,this.config.custom_blocked_useragents):void 0}un(){Ze&&(Ze.visibilityState==="visible"?this.Bi||(this.Bi=!0,this.capture(Uu,{title:Ze.title},{send_instantly:!0}),this.zi&&(Ze.removeEventListener(a1,this.zi),this.zi=null)):this.zi||(this.zi=this.un.bind(this),Wn(Ze,a1,this.zi)))}debug(t){t===!1?(me==null||me.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(me==null||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}))}Dr(){var t,n,r,i,s,o,a=this.Gi||{};return"advanced_disable_flags"in a?!!a.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ue.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",i=Ue,s=(n="advanced_disable_flags")in(t=a)&&!Kt(t[n]),o=r in t&&!Kt(t[r]),s?t[n]:!!o&&(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]))}vn(t){if(Kt(this.config.before_send))return t;var n=sn(this.config.before_send)?this.config.before_send:[this.config.before_send],r=t;for(var i of n){if(r=i(r),Kt(r)){var s="Event '"+t.event+"' was rejected in beforeSend function";return wZ(t.event)?Ue.warn(s+". This can cause unexpected behavior."):Ue.info(s),null}r.properties&&!Ku(r.properties)||Ue.warn("Event '"+t.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var t;return(t=this.pageViewManager.dr)==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)})}Zi(t){var n=oo(t)&&!t,r=Bn.O()&&Bn.A("ph_debug")==="true";return!n&&(!!r||t)}}Xi.__defaultExtensionClasses={},Xi.wn={trace:Eu=()=>{},debug:Eu,info:Eu,warn:Eu,error:Eu,fatal:Eu},(function(e,t){for(var n=0;t.length>n;n++)e.prototype[t[n]]=sW(e.prototype[t[n]])})(Xi,["identify"]);var qW=1,KW=3,YW=11;function XS(e){return e instanceof Element&&(e.id===ZM||!(e.closest==null||!e.closest(".toolbar-global-fade-container")))}function Rc(e){return!!e&&e.nodeType===qW}function As(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function y9(e){return!!e&&e.nodeType===KW}function b9(e){return!!e&&e.nodeType===YW&&Rc(e.host)}function e3(e){return e?bv(e).split(/\s+/):[]}function QS(e){var t=me==null?void 0:me.location.href;return!!(t&&e&&e.some((n=>t.match(n))))}function m1(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 e3(t)}function x9(e){return Kt(e)?null:bv(e).split(/(\s+)/).filter((t=>Gh(t))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function hp(e){var t="";return k4(e)&&!_9(e)&&e.childNodes&&e.childNodes.length&&Rn(e.childNodes,(function(n){var r;y9(n)&&n.textContent&&(t+=(r=x9(n.textContent))!==null&&r!==void 0?r:"")})),bv(t)}function JS(e){return We(e.target)?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var t3=["a","button","form","input","select","textarea","label"];function e5(e,t){if(We(t))return!0;var n,r=function(s){if(t.some((o=>s.matches(o))))return{v:!0}};for(var i of e)if(n=r(i))return n.v;return!1}function w9(e){var t=e.parentNode;return!(!t||!Rc(t))&&t}var XW=["next","previous","prev",">","<"],t5=[".ph-no-rageclick",".ph-no-capture"],_4=e=>!e||As(e,"html")||!Rc(e),n5=(e,t)=>{if(!me||_4(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[e],i=e;i.parentNode&&!As(i,"body");)if(b9(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var s=w9(i);if(!s)break;if(t||t3.indexOf(s.tagName.toLowerCase())>-1)n=!0;else{var o=me.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(s),i=s}return{parentIsUsefulElement:n,targetElementList:r}};function k4(e){for(var t=e;t.parentNode&&!As(t,"body");t=t.parentNode){var n=m1(t);if(At(n,"ph-sensitive")||At(n,"ph-no-capture"))return!1}if(At(m1(e),"ph-include"))return!0;var r=e.type||"";if(Nn(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=e.name||e.id||"";return!Nn(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function _9(e){return!!(As(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||As(e,"select")||As(e,"textarea")||e.getAttribute("contenteditable")==="true")}var k9="(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})",QW=new RegExp("^(?:"+k9+")$"),JW=new RegExp(k9),C9="\\d{3}-?\\d{2}-?\\d{4}",eG=new RegExp("^("+C9+")$"),tG=new RegExp("("+C9+")");function Gh(e,t){return t===void 0&&(t=!0),!(Kt(e)||Nn(e)&&(e=bv(e),(t?QW:JW).test((e||"").replace(/[- ]/g,""))||(t?eG:tG).test(e)))}function r5(e){var t=hp(e);return Gh(t=(t+" "+E9(e)).trim())?t:""}function E9(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Rn(e.childNodes,(function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=hp(n);t=(t+" "+i).trim(),n.childNodes&&n.childNodes.length&&(t=(t+" "+E9(n)).trim())}catch(s){Ue.error("[AutoCapture]",s)}})),t}function i5(e){return e.replace(/"|\\"/g,'\\"')}function nG(e){var t=e.attr__class;return t?sn(t)?t:e3(t):void 0}class s5{constructor(t){this.disabled=t===!1;var n=Yn(t)?t:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(t,n,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(t-i.x)+Math.abs(n-i.y)<this.thresholdPx&&this.timeoutMs>r-i.timestamp){if(this.clicks.push({x:t,y:n,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:t,y:n,timestamp:r}];return!1}}var Rb="$copy_autocapture",Mb=Ln("[AutoCapture]");function $b(e,t){return t.length>e?t.slice(0,e)+"...":t}function rG(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!Rc(t));return t}function iG(e,t){var n,r,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=t;if(!Rc(e))return{props:{}};for(var u=[e],f=e;f.parentNode&&!As(f,"body");)if(b9(f.parentNode))u.push(f.parentNode.host),f=f.parentNode.host;else{if(!Rc(f.parentNode))break;u.push(f.parentNode),f=f.parentNode}var p,m,g=[],b={},x=!1,k=!1;if(Rn(u,(R=>{var P=k4(R);if(As(R,"a")){var I=R.getAttribute("href");x=P&&!!I&&Gh(I)&&I}At(m1(R),"ph-no-capture")&&(k=!0),g.push((function(L,M,D,O){var F=L.tagName.toLowerCase(),Z={tag_name:F};t3.indexOf(F)>-1&&!D&&(Z.$el_text=F.toLowerCase()==="a"||F.toLowerCase()==="button"?$b(1024,r5(L)):$b(1024,hp(L)));var V=m1(L);V.length>0&&(Z.classes=V.filter((function(G){return G!==""}))),Rn(L.attributes,(function(G){var j;if((!_9(L)||["name","id","class","aria-label"].indexOf(G.name)!==-1)&&(O==null||!O.includes(G.name))&&!M&&Gh(G.value)&&(!Nn(j=G.name)||j.substring(0,10)!=="_ngcontent"&&j.substring(0,7)!=="_nghost")){var H=G.value;G.name==="class"&&(H=e3(H).join(" ")),Z["attr__"+G.name]=$b(1024,H)}}));for(var U=1,K=1,W=L;W=rG(W);)U++,W.tagName===L.tagName&&K++;return Z.nth_child=U,Z.nth_of_type=K,Z})(R,s,o,a));var T=(function(L){if(!k4(L))return{};var M={};return Rn(L.attributes,(function(D){if(D.name&&D.name.indexOf("data-ph-capture-attribute")===0){var O=D.name.replace("data-ph-capture-attribute-",""),F=D.value;O&&F&&Gh(F)&&(M[O]=F)}})),M})(R);qn(b,T)})),k)return{props:{},explicitNoCapture:k};if(o||(g[0].$el_text=As(e,"a")||As(e,"button")?r5(e):hp(e)),x){var w,C;g[0].attr__href=x;var E=(w=u1(x))==null?void 0:w.host,A=me==null||(C=me.location)==null?void 0:C.host;E&&A&&E!==A&&(p=x)}return{props:qn({$event_type:i.type,$ce_version:1},l?{}:{$elements:g},{$elements_chain:(m=g,(function(R){return R.map((P=>{var I,T,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var M of(P.attr_class.sort(),P.attr_class))L+="."+M.replace(/"/g,"");var D=Oe({},P.text?{text:P.text}:{},{"nth-child":(I=P.nth_child)!==null&&I!==void 0?I:0,"nth-of-type":(T=P.nth_of_type)!==null&&T!==void 0?T:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),O={};return wg(D).sort(((F,Z)=>{var[V]=F,[U]=Z;return V.localeCompare(U)})).forEach((F=>{var[Z,V]=F;return O[i5(Z.toString())]=i5(V.toString())})),(L+=":")+wg(O).map((F=>{var[Z,V]=F;return Z+'="'+V+'"'})).join("")})).join(";")})((function(R){return R.map((P=>{var I,T,L={text:(I=P.$el_text)==null?void 0:I.slice(0,400),tag_name:P.tag_name,href:(T=P.attr__href)==null?void 0:T.slice(0,2048),attr_class:nG(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return wg(P).filter((M=>{var[D]=M;return D.indexOf("attr__")===0})).forEach((M=>{var[D,O]=M;return L.attributes[D]=O})),L}))})(m)))},(n=g[0])!=null&&n.$el_text?{$el_text:(r=g[0])==null?void 0:r.$el_text}:{},p&&i.type==="click"?{$external_click_url:p}:{},b)}}var ah=Ln("[ExceptionAutocapture]");function o5(e,t,n){try{if(!(t in e))return()=>{};var r=e[t],i=n(r);return zo(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=i,()=>{e[t]===i&&(e[t]=r)}}catch{return()=>{}}}var sG=Ln("[TracingHeaders]"),Gl=Ln("[Web Vitals]"),a5=9e5,l5="disabled",c5="lazy_loading",lh="awaiting_config",Pm="missing_config";Ln("[SessionRecording]"),Ln("[SessionRecording]");var C4="[SessionRecording]",$o=Ln(C4),oG=Ln("[Heatmaps]");function u5(e){return Yn(e)&&"clientX"in e&&"clientY"in e&&Hi(e.clientX)&&Hi(e.clientY)}var d5=Ln("[Product Tours]"),aG=["$set_once","$set"],Na=Ln("[SiteApps]"),f5="Error while initializing PostHog app with config id ";function Su(e,t,n){if(Kt(e))return!1;switch(n){case"exact":return e===t;case"contains":var r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}class lG{constructor(t){this.xn=new J8,this.Sn=(n,r)=>this.kn(n,r)&&this.Cn(n,r)&&this.In(n,r)&&this.Tn(n,r),this.kn=(n,r)=>r==null||!r.event||(n==null?void 0:n.event)===(r==null?void 0:r.event),this._instance=t,this.En=new Set,this.Mn=new Set}init(){var t,n;We((t=this._instance)==null?void 0:t._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((r,i)=>{this.on(r,i)}))}register(t){var n,r;if(!We((n=this._instance)==null?void 0:n._addCaptureHook)&&(t.forEach((o=>{var a,l;(a=this.Mn)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var f;(f=this.En)==null||f.add((u==null?void 0:u.event)||"")}))})),(r=this._instance)!=null&&r.autocapture)){var i,s=new Set;t.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l==null?void 0:l.selector)}))})),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(t,n){var r;n!=null&&t.length!=0&&(this.En.has(t)||this.En.has(n==null?void 0:n.event))&&this.Mn&&((r=this.Mn)==null?void 0:r.size)>0&&this.Mn.forEach((i=>{this.Rn(n,i)&&this.xn.emit("actionCaptured",i.name)}))}Pn(t){this.onAction("actionCaptured",(n=>t(n)))}Rn(t,n){if((n==null?void 0:n.steps)==null)return!1;for(var r of n.steps)if(this.Sn(t,r))return!0;return!1}onAction(t,n){return this.xn.on(t,n)}Cn(t,n){if(n!=null&&n.url){var r,i=t==null||(r=t.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!Su(i,n.url,n.url_matching||"contains"))return!1}return!0}In(t,n){return!!this.On(t,n)&&!!this.Ln(t,n)&&!!this.Fn(t,n)}On(t,n){var r;if(n==null||!n.href)return!0;var i=this.An(t);if(i.length>0)return i.some((a=>Su(a.href,n.href,n.href_matching||"exact")));var s,o=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!o&&Su((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}Ln(t,n){var r;if(n==null||!n.text)return!0;var i=this.An(t);if(i.length>0)return i.some((u=>Su(u.text,n.text,n.text_matching||"exact")||Su(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(s=(function(u){for(var f,p=[],m=/(?::|")text="(.*?)"/g;!Kt(f=m.exec(u));)p.includes(f[1])||p.push(f[1]);return p})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>Su(u,o,a))))}Fn(t,n){var r,i;if(n==null||!n.selector)return!0;var s=t==null||(r=t.properties)==null?void 0:r.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(t==null||(i=t.properties)==null?void 0:i.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}An(t){var n;return(t==null||(n=t.properties)==null?void 0:n.$elements)==null?[]:t==null?void 0:t.properties.$elements}Tn(t,n){return n==null||!n.properties||n.properties.length===0||m9(n.properties.reduce(((r,i)=>{var s=sn(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:s,operator:i.operator||"exact"},r}),{}),t==null?void 0:t.properties)}}class cG{constructor(t){this._instance=t,this.Nn=new Map,this.Dn=new Map,this.$n=new Map}qn(t,n){return!!t&&m9(t.propertyFilters,n==null?void 0:n.properties)}jn(t,n){var r=new Map;return t.forEach((i=>{var s;(s=i.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}}))})),r}Hn(t,n,r){var i=(r===nh.Activation?this.Nn:this.Dn).get(t),s=[];return this.Un((o=>{s=o.filter((a=>i==null?void 0:i.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===t));return this.qn(l,n)}))}register(t){var n;We((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Bn(t),this.zn(t))}zn(t){var n=t.filter((r=>{var i,s;return((i=r.conditions)==null?void 0:i.actions)&&((s=r.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Vn==null&&(this.Vn=new lG(this._instance),this.Vn.init(),this.Vn.Pn((r=>{this.onAction(r)}))),n.forEach((r=>{var i,s,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(s=r.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Vn)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var f=this.$n.get(u.name);f&&f.push(r.id),this.$n.set(u.name,f||[r.id])}})))})))}Bn(t){var n,r=t.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),i=t.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&i.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.Nn=this.jn(t,nh.Activation),this.Dn=this.jn(t,nh.Cancellation))}onEvent(t,n){var r,i=this.le(),s=this.Wn(),o=this.Zn(),a=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[s])||[];if(o===t&&n&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:t,eventPayload:n,existingActivatedItems:a});var f=(n==null||(l=n.properties)==null?void 0:l.$survey_id)||(n==null||(u=n.properties)==null?void 0:u.$product_tour_id);if(f){var p=a.indexOf(f);0>p||(a.splice(p,1),this.Gn(a))}}else{if(this.Dn.has(t)){var m=this.Hn(t,n,nh.Cancellation);m.length>0&&(i.info("cancel event matched, cancelling items",{event:t,itemsToCancel:m.map((b=>b.id))}),m.forEach((b=>{var x=a.indexOf(b.id);0>x||a.splice(x,1),this.Qn(b.id)})),this.Gn(a))}if(this.Nn.has(t)){i.info("event name matched",{event:t,eventPayload:n,items:this.Nn.get(t)});var g=this.Hn(t,n,nh.Activation);this.Gn(a.concat(g.map((b=>b.id))||[]))}}}onAction(t){var n,r=this.Wn(),i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[r])||[];this.$n.has(t)&&this.Gn(i.concat(this.$n.get(t)||[]))}Gn(t){var n=this.le(),r=[...new Set(t)].filter((i=>!this.Jn(i)));n.info("updating activated items",{activatedItems:r}),this.Kn(r)}getActivatedIds(){var t,n=this.Wn();return((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[]}getEventToItemsMap(){return this.Nn}Yn(){return this.Vn}}class uG extends cG{constructor(t){super(t)}Wn(){return o4}Zn(){return Ih.SHOWN}Un(t){var n;(n=this._instance)==null||n.getSurveys(t)}Qn(t){var n;(n=this._instance)==null||n.cancelPendingSurvey(t)}le(){return bn}Kn(t){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[o4]:t})}Jn(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Db="SDK is not enabled or survey functionality is not yet loaded",h5="Disabled. Not loading surveys.",dG=me!=null&&me.location?d1(me.location.hash,"__posthog")||d1(location.hash,"state"):null,p5="_postHogToolbarParams",m5=Ln("[Toolbar]"),Sr=Ln("[FeatureFlags]"),ql=Ln("[FeatureFlags]",{debugEnabled:!0}),Nb=`" failed. Feature flags didn't load in time.`,g5=e=>{for(var t={},n=0;e.length>n;n++)t[e[n]]=!0;return t},v5=e=>{var t={};for(var[n,r]of wg(e||{}))r&&(t[n]=r);return t},Do=Ln("[Error tracking]"),y5="Refusing to render web experiment since the viewer is a likely bot",fG={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&&p1(t.href,e),not_regex:(e,t)=>!!me&&!p1(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class Vr{get qt(){return this._instance.config}constructor(t){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments((i=>{Vr.Xn("retrieved web experiments from the server"),n.es=new Map,i.forEach((s=>{if(s.feature_flag_key){var o;n.es&&(Vr.Xn("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.es)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);Nn(a)&&s.variants[a]&&n.ts(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Vr.rs(u)&&n.ts(s.name,l,u.transforms)}}))}),r)},this._instance=t,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(t){if(this._is_bot())Vr.Xn(y5);else if(!this.qt.disable_web_experiments){if(Kt(this.es))return this.es=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Vr.Xn("applying feature flags",t),t.forEach((n=>{var r;if(this.es&&(r=this.es)!=null&&r.has(n)){var i,s=this._instance.getFeatureFlag(n),o=(i=this.es)==null?void 0:i.get(n);s&&o!=null&&o.variants[s]&&this.ts(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var t=Vr.getWindowLocation();if(t!=null&&t.search){var n=up(t==null?void 0:t.search,"__experiment_id"),r=up(t==null?void 0:t.search,"__experiment_variant");n&&r&&(Vr.Xn("previewing web experiments "+n+" && "+r),this.getWebExperiments((i=>{this.ns(parseInt(n),r,i)}),!1,!0))}}loadIfEnabled(){this.qt.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,n,r){if(this.qt.disable_web_experiments&&!r)return t([]);var i=this._instance.get_property("$web_experiments");if(i&&!n)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.qt.token),method:"GET",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}ns(t,n,r){var i=r.filter((s=>s.id===t));i&&i.length>0&&(Vr.Xn("Previewing web experiment ["+i[0].name+"] with variant ["+n+"]"),this.ts(i[0].name,n,i[0].variants[n].transforms))}static rs(t){return!Kt(t.conditions)&&Vr.ss(t)&&Vr.os(t)}static ss(t){var n;if(Kt(t.conditions)||Kt((n=t.conditions)==null?void 0:n.url))return!0;var r,i,s,o=Vr.getWindowLocation();return!!o&&((r=t.conditions)==null||!r.url||fG[(i=(s=t.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](t.conditions.url,o))}static getWindowLocation(){return me==null?void 0:me.location}static os(t){var n;if(Kt(t.conditions)||Kt((n=t.conditions)==null?void 0:n.utm))return!0;var r=JM();if(r.utm_source){var i,s,o,a,l,u,f,p,m=(i=t.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=t.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==r.utm_campaign,g=(o=t.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=t.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,b=(l=t.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=t.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,x=(f=t.conditions)==null||(f=f.utm)==null||!f.utm_term||((p=t.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==r.utm_term;return m&&b&&x&&g}return!1}static Xn(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;n>i;i++)r[i-1]=arguments[i];Ue.info("[WebExperiments] "+t,r)}ts(t,n,r){this._is_bot()?Vr.Xn(y5):n!=="control"?r.forEach((i=>{if(i.selector){var s;Vr.Xn("applying transform of variant "+n+" for experiment "+t+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o==null||o.forEach((a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)}))}})):Vr.Xn("Control variants leave the page unmodified.")}_is_bot(){return Ni&&this._instance?h9(Ni,this.qt.custom_blocked_useragents):void 0}}var Ki=Ln("[Conversations]"),Kl="Conversations not available yet.",_v={featureFlags:class{constructor(e){this.us=!1,this.ls=!1,this.hs=!1,this.cs=!1,this.ds=!1,this.vs=!1,this.fs=!1,this.ps=!1,this._instance=e,this.featureFlagEventHandlers=[]}get qt(){return this._instance.config}get ui(){return this._instance.persistence}gs(e){return this._instance.get_property(e)}ys(){var e,t;return(e=(t=this.ui)==null?void 0:t.Sr(this.qt.feature_flag_cache_ttl_ms))!==null&&e!==void 0&&e}bs(){return!!this.ys()&&(this.ps||this.hs||(this.ps=!0,Sr.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_s(){var e,t=(e=this.qt.evaluation_contexts)!==null&&e!==void 0?e:this.qt.evaluation_environments;return!this.qt.evaluation_environments||this.qt.evaluation_contexts||this.fs||(Sr.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.fs=!0),t!=null&&t.length?t.filter((n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||Sr.error("Invalid evaluation context found:",n,"Expected non-empty string"),r})):[]}ws(){return this._s().length>0}xs(){var e=this.qt.flag_keys;if(!We(e)){if(sn(e))return e.filter((t=>{var n=t&&typeof t=="string"&&t.trim().length>0;return n||Sr.error("Invalid flag key found:",t,"Expected non-empty string"),n}));Sr.error("Invalid flag_keys found:",e,"Expected array of non-empty strings")}}initialize(){var e,t,{config:n}=this._instance,r=(e=(t=n.bootstrap)==null?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(r).length){var i,s,o=(i=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,f)=>(u[f]=r[f]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,f)=>(o[f]&&(u[f]=o[f]),u)),{});this.receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l})}}updateFlags(e,t,n){var r=n!=null&&n.merge?this.getFlagVariants():{},i=n!=null&&n.merge?this.getFlagPayloads():{},s=Oe({},r,e),o=Oe({},i,t),a={};for(var[l,u]of Object.entries(s)){var f=typeof u=="string";a[l]={key:l,enabled:!!f||!!u,variant:f?u:void 0,reason:void 0,metadata:We(o==null?void 0:o[l])?void 0:{id:0,version:void 0,description:void 0,payload:o[l]}}}this.receivedFeatureFlags({flags:a})}get hasLoadedFlags(){return this.ls}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this.gs(n4),t=this.gs(Oo),n=this.gs(zu);if(!n&&!t)return e||{};var r=qn({},e||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var s of i){var o,a,l=r[s],u=t==null?void 0:t[s],f=We(u)?(o=l==null?void 0:l.enabled)!==null&&o!==void 0&&o:!!u,p=We(u)?l.variant:typeof u=="string"?u:void 0,m=n==null?void 0:n[s],g=Oe({},l,{enabled:f,variant:f?p??(l==null?void 0:l.variant):void 0});f!==(l==null?void 0:l.enabled)&&(g.original_enabled=l==null?void 0:l.enabled),p!==(l==null?void 0:l.variant)&&(g.original_variant=l==null?void 0:l.variant),m&&(g.metadata=Oe({},l==null?void 0:l.metadata,{payload:m,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[s]=g}return this.us||(Sr.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:r}),this.us=!0),r}getFlagVariants(){var e=this.gs(Xu),t=this.gs(Oo);if(!t)return e||{};for(var n=qn({},e),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.us||(Sr.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.us=!0),n}getFlagPayloads(){var e=this.gs(r4),t=this.gs(zu);if(!t)return e||{};for(var n=qn({},e||{}),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.us||(Sr.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.us=!0),n}reloadFeatureFlags(){this.cs||this.qt.advanced_disable_feature_flags||this.Ss||(this._instance.Ui.emit("featureFlagsReloading",!0),this.Ss=setTimeout((()=>{this.ks()}),5))}Cs(){clearTimeout(this.Ss),this.Ss=void 0}ensureFlagsLoaded(){this.ls||this.hs||this.Ss||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.cs=e}ks(e){var t;if(this.Cs(),!this._instance.Dr())if(this.hs)this.ds=!0;else{var n=this.qt.token,r=this.gs(r1),i={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:Oe({},((t=this.ui)==null?void 0:t.get_initial_props())||{},this.gs(Ph)||{}),group_properties:this.gs(nc),timezone:s9()};es(r)||We(r)||(i.$device_id=r),(e!=null&&e.disableFlags||this.qt.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.ws()&&(i.evaluation_contexts=this._s());var s=this.xs();We(s)||(i.flag_keys=s);var o=!!this.qt.advanced_only_evaluate_survey_feature_flags,a=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+(this.qt.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":""));this.hs=!0,this._instance._send_request({method:"POST",url:a,data:i,compression:this.qt.disable_compression?void 0:no.Base64,timeout:this.qt.feature_flag_request_timeout_ms,callback:l=>{var u,f,p,m=!0;if(l.statusCode===200&&(this.ds||(this.$anon_distinct_id=void 0),m=!1),this.hs=!1,!i.disable_flags||this.ds){this.vs=!m;var g=[];l.error?l.error instanceof Error?g.push(l.error.name==="AbortError"?"timeout":"connection_error"):g.push("unknown_error"):l.statusCode!==200&&g.push("api_error_"+l.statusCode),(u=l.json)!=null&&u.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var b,x=!((f=l.json)==null||(f=f.quotaLimited)==null||!f.includes("feature_flags"));x&&g.push("quota_limited"),(p=this.ui)==null||p.register({[l4]:g}),x?Sr.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."):(i.disable_flags||this.receivedFeatureFlags((b=l.json)!==null&&b!==void 0?b:{},m,{partialResponse:o}),this.ds&&(this.ds=!1,this.ks()))}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),!t.fresh||this.vs)if(this.ls||this.getFlags()&&this.getFlags().length>0){if(!this.bs()){var r=this.getFeatureFlagResult(e,t);return(n=r==null?void 0:r.variant)!==null&&n!==void 0?n:r==null?void 0:r.enabled}}else Sr.warn('getFeatureFlag for key "'+e+Nb)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t==null?void 0:t.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),!t.fresh||this.vs)if(this.ls||this.getFlags()&&this.getFlags().length>0){if(!this.bs()){var n=this.getFlagVariants(),r=e in n,i=n[e],s=this.getFlagPayloads()[e],o=String(i),a=this.gs(i4)||void 0,l=this.gs(i1)||void 0,u=this.gs(Uh)||{};if(this.qt.advanced_feature_flags_dedup_per_session){var f,p=this._instance.get_session_id(),m=this.gs(a4);p&&p!==m&&(u={},(f=this.ui)==null||f.register({[Uh]:u,[a4]:p}))}if((t.send_event||!("send_event"in t))&&(!(e in u)||!u[e].includes(o))){var g,b,x,k,w,C,E,A,R,P;sn(u[e])?u[e].push(o):u[e]=[o],(g=this.ui)==null||g.register({[Uh]:u});var I=this.getFeatureFlagDetails(e),T=[...(b=this.gs(l4))!==null&&b!==void 0?b:[]];We(i)&&T.push("flag_missing");var L={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:l,$feature_flag_bootstrapped_response:((x=this.qt.bootstrap)==null||(x=x.featureFlags)==null?void 0:x[e])||null,$feature_flag_bootstrapped_payload:((k=this.qt.bootstrap)==null||(k=k.featureFlagPayloads)==null?void 0:k[e])||null,$used_bootstrap_value:!this.vs};We(I==null||(w=I.metadata)==null?void 0:w.version)||(L.$feature_flag_version=I.metadata.version);var M,D=(C=I==null||(E=I.reason)==null?void 0:E.description)!==null&&C!==void 0?C:I==null||(A=I.reason)==null?void 0:A.code;D&&(L.$feature_flag_reason=D),I!=null&&(R=I.metadata)!=null&&R.id&&(L.$feature_flag_id=I.metadata.id),We(I==null?void 0:I.original_variant)&&We(I==null?void 0:I.original_enabled)||(L.$feature_flag_original_response=We(I.original_variant)?I.original_enabled:I.original_variant),I!=null&&(P=I.metadata)!=null&&P.original_payload&&(L.$feature_flag_original_payload=I==null||(M=I.metadata)==null?void 0:M.original_payload),T.length&&(L.$feature_flag_error=T.join(",")),this._instance.capture("$feature_flag_called",L)}if(r){var O=s;if(!We(s))try{O=JSON.parse(s)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:O}}}}else Sr.warn('getFeatureFlagResult for key "'+e+Nb)}getRemoteConfigPayload(e,t){var n=this.qt.token,r={distinct_id:this._instance.get_distinct_id(),token:n};this.ws()&&(r.evaluation_contexts=this._s());var i=this.xs();We(i)||(r.flag_keys=i),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:r,compression:this.qt.disable_compression?void 0:no.Base64,timeout:this.qt.feature_flag_request_timeout_ms,callback(s){var o,a=(o=s.json)==null?void 0:o.featureFlagPayloads;t((a==null?void 0:a[e])||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),!t.fresh||this.vs){if(this.ls||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return We(n)?void 0:!!n}Sr.warn('isFeatureEnabled for key "'+e+Nb)}}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t,n){if(this.ui){this.ls=!0;var r=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,f,p){l===void 0&&(l={}),u===void 0&&(u={}),f===void 0&&(f={});var m=(T=>{var L=T.flags;return L?(T.featureFlags=Object.fromEntries(Object.keys(L).map((M=>{var D;return[M,(D=L[M].variant)!==null&&D!==void 0?D:L[M].enabled]}))),T.featureFlagPayloads=Object.fromEntries(Object.keys(L).filter((M=>L[M].enabled)).filter((M=>{var D;return(D=L[M].metadata)==null?void 0:D.payload})).map((M=>{var D;return[M,(D=L[M].metadata)==null?void 0:D.payload]})))):Sr.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),T})(o),g=m.flags,b=m.featureFlags,x=m.featureFlagPayloads;if(b){var k=o.requestId,w=o.evaluatedAt;if(sn(b)){Sr.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var C={};if(b)for(var E=0;b.length>E;E++)C[b[E]]=!0;a&&a.register({[bg]:b,[Xu]:C})}else{var A=b,R=x,P=g;if(p!=null&&p.partialResponse)A=Oe({},l,A),R=Oe({},u,R),P=Oe({},f,P);else if(o.errorsWhileComputingFlags)if(g){var I=new Set(Object.keys(g).filter((T=>{var L;return!((L=g[T])!=null&&L.failed)})));A=Oe({},l,Object.fromEntries(Object.entries(A).filter((T=>{var[L]=T;return I.has(L)})))),R=Oe({},u,Object.fromEntries(Object.entries(R||{}).filter((T=>{var[L]=T;return I.has(L)})))),P=Oe({},f,Object.fromEntries(Object.entries(P||{}).filter((T=>{var[L]=T;return I.has(L)}))))}else A=Oe({},l,A),R=Oe({},u,R),P=Oe({},f,P);a&&a.register(Oe({[bg]:Object.keys(v5(A)),[Xu]:A||{},[r4]:R||{},[n4]:P||{}},k?{[i4]:k}:{},w?{[i1]:w}:{}))}}})(e,this.ui,r,i,s,n),t||(this.ps=!1),this.Is(t)}}override(e,t){t===void 0&&(t=!1),Sr.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this.ui)return Sr.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this.ui.unregister(Oo),this.ui.unregister(zu),this.Is(),ql.info("All overrides cleared");if(sn(e)){var t=g5(e);return this.ui.register({[Oo]:t}),this.Is(),ql.info("Flag overrides set",{flags:e})}if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.us=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this.ui.unregister(Oo),ql.info("Flag overrides cleared");else if(r.flags){if(sn(r.flags)){var i=g5(r.flags);this.ui.register({[Oo]:i})}else this.ui.register({[Oo]:r.flags});ql.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this.ui.unregister(zu),ql.info("Payload overrides cleared")):r.payloads&&(this.ui.register({[zu]:r.payloads}),ql.info("Payload overrides set",{payloads:r.payloads}))),void this.Is()}if(e&&typeof e=="object")return this.ui.register({[Oo]:e}),this.Is(),ql.info("Flag overrides set",{flags:e});Sr.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ls){var{flags:t,flagVariants:n}=this.Ts();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var r,i=(this.gs(Th)||[]).find((l=>l.flagKey===e)),s={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),n&&(o.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",o),this.setPersonPropertiesForFlags(s,!1);var a=Oe({},this.getFlagVariants(),{[e]:t});(r=this.ui)==null||r.register({[bg]:Object.keys(v5(a)),[Xu]:a}),this.Is()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var r=this.gs(Th),i=n?"&"+n.map((s=>"stage="+s)).join("&"):"";if(r&&!t)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this.qt.token+i),method:"GET",callback:s=>{var o,a;if(s.json){var l=s.json.earlyAccessFeatures;return(o=this.ui)==null||o.unregister(Th),(a=this.ui)==null||a.register({[Th]:l}),e(l)}}})}Ts(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((n=>t[n])),flagVariants:Object.keys(t).filter((n=>t[n])).reduce(((n,r)=>(n[r]=t[r],n)),{})}}Is(e){var{flags:t,flagVariants:n}=this.Ts();this.featureFlagEventHandlers.forEach((r=>r(t,n,{errorsLoading:e})))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.gs(Ph)||{},r=(e==null?void 0:e.$set)||(e!=null&&e.$set_once?{}:e),i=e==null?void 0:e.$set_once,s={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in n||(s[o]=i[o]));this._instance.register({[Ph]:Oe({},n,s,r)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Ph)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.gs(nc)||{};Object.keys(n).length!==0&&Object.keys(n).forEach((r=>{n[r]=Oe({},n[r],e[r]),delete e[r]})),this._instance.register({[nc]:Oe({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this.gs(nc)||{};this._instance.register({[nc]:Oe({},t,{[e]:{}})})}else this._instance.unregister(nc)}reset(){this.ls=!1,this.hs=!1,this.cs=!1,this.ds=!1,this.vs=!1,this.$anon_distinct_id=void 0,this.Cs(),this.us=!1}}},hG={sessionRecording:class{get qt(){return this._instance.config}get ui(){return this._instance.persistence}get started(){var e;return!((e=this.Es)==null||!e.isStarted)}get status(){var e,t;return this.Ms===lh||this.Ms===Pm?this.Ms:(e=(t=this.Es)==null?void 0:t.status)!==null&&e!==void 0?e:this.Ms}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ms=l5,this.Rs=void 0,this._instance=e,!this._instance.sessionManager)throw $o.error("started without valid sessionManager"),new Error(C4+" started without valid sessionManager. This is a bug.");if(this.qt.cookieless_mode===Go)throw new Error(C4+' cannot be used with cookieless_mode="always"')}initialize(){this.startIfEnabledOrStop()}get Ps(){var e,t=!((e=this._instance.get_property(lc))==null||!e.enabled),n=!this.qt.disable_session_recording,r=this.qt.disable_session_recording||this._instance.consent.isOptedOut();return me&&t&&n&&!r}startIfEnabledOrStop(e){var t;if(!this.Ps||(t=this.Es)==null||!t.isStarted){var n=!We(Object.assign)&&!We(Array.from);this.Ps&&n?(this.Os(e),$o.info("starting")):(this.Ms=l5,this.stopRecording())}}Os(e){var t,n,r;this.Ps&&(this.Ms!==lh&&this.Ms!==Pm&&(this.Ms=c5),gt!=null&&(t=gt.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=gt.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Ls(e):(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.Fs,(i=>{if(i)return $o.error("could not load recorder",i);this.Ls(e)})))}stopRecording(){var e,t;(e=this.Rs)==null||e.call(this),this.Rs=void 0,(t=this.Es)==null||t.stop()}As(){var e,t;(e=this.Rs)==null||e.call(this),this.Rs=void 0,(t=this.Es)==null||t.discard()}Ns(){var e;(e=this.ui)==null||e.unregister(q8)}Ds(e,t){if(Kt(e))return null;var n,r=Hi(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?($o.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):r}$s(e){if(this.ui){var t,n,r=this.ui,i=()=>{var s,o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.Ds((s=this.qt.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.Ds(o==null?void 0:o.sampleRate,"remote config sampleRate"),u=a??l;Kt(u)&&this.Ns();var f=o==null?void 0:o.minimumDurationMilliseconds;r.register({[lc]:Oe({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:Oe({capturePerformance:e.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:u,minimumDurationMilliseconds:We(f)?null:f,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers,version:o==null?void 0:o.version,triggerGroups:o==null?void 0:o.triggerGroups})})};i(),(t=this.Rs)==null||t.call(this),this.Rs=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(e){return"sessionRecording"in e?e.sessionRecording===!1?(this.$s(e),void this.As()):(this.$s(e),void this.startIfEnabledOrStop()):(this.Ms===lh&&(this.Ms=Pm,$o.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var n;t===void 0&&(t="log"),(n=this.Es)!=null&&n.log?this.Es.log(e,t):$o.warn("log called before recorder was ready")}get Fs(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(lc);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}qs(){var e,t,n=this._instance.get_property(lc);if(!n)return!1;try{t=typeof n=="object"?n:JSON.parse(n)}catch(i){return $o.warn("persisted remote config for session recording is invalid and will be ignored",i),!1}var r=(e=t.cache_timestamp)!==null&&e!==void 0?e:Date.now();return 36e5>=Date.now()-r}Ls(e){var t,n;if((t=gt.__PosthogExtensions__)==null||!t.initSessionRecording)return $o.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[qM]:!0});if(this.Es||(this.Es=(n=gt.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Es._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.qs())return this.Ms===Pm||this.Ms===lh?void 0:(this.Ms=lh,$o.info("persisted remote config is stale, requesting fresh config before starting"),void new o9(this._instance).load());this.Ms=c5,this.Es.start(e)}onRRwebEmit(e){var t;(t=this.Es)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Es||(t=this.ui)==null||t.register({[BM]:!0}),(e=this.Es)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Es||(t=this.ui)==null||t.register({[HM]:!0}),(e=this.Es)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Es||(n=this.ui)==null||n.register({[e==="url"?zM:UM]:!0}),(t=this.Es)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Es)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Es)==null||!n.tryAddCustomEvent(e,t))}}},pG={autocapture:class{constructor(e){this.js=!1,this.Hs=null,this.Us=!1,this.instance=e,this.rageclicks=new s5(e.config.rageclick),this.Bs=null}initialize(){this.startIfEnabled()}get qt(){var e,t,n=Yn(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map((r=>new RegExp(r))),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map((r=>new RegExp(r))),n}zs(){if(this.isBrowserSupported()){if(me&&Ze){var e=n=>{n=n||(me==null?void 0:me.event);try{this.Vs(n)}catch(r){Mb.error("Failed to capture event",r)}};if(Wn(Ze,"submit",e,{capture:!0}),Wn(Ze,"change",e,{capture:!0}),Wn(Ze,"click",e,{capture:!0}),this.qt.capture_copied_text){var t=n=>{n=n||(me==null?void 0:me.event);try{this.Vs(n,Rb)}catch(r){Mb.error("Failed to capture copy/cut event",r)}};Wn(Ze,"copy",t,{capture:!0}),Wn(Ze,"cut",t,{capture:!0})}}}else Mb.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.js&&(this.zs(),this.js=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.Us=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[qw]:!!e.autocapture_opt_out}),this.Hs=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.Bs=e}getElementSelectors(e){var t,n=[];return(t=this.Bs)==null||t.forEach((r=>{var i=Ze==null?void 0:Ze.querySelectorAll(r);i==null||i.forEach((s=>{e===s&&n.push(r)}))})),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[qw];if(es(this.Hs)&&!oo(n)&&!this.instance.Dr())return!1;var r=(t=this.Hs)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!r}Vs(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,r=JS(e);y9(r)&&(r=r.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&(function(p,m){if(!me||_4(p))return!1;var g,b,x;if(oo(m)?(g=!!m&&t5,b=void 0):(g=(x=m==null?void 0:m.css_selector_ignorelist)!==null&&x!==void 0?x:t5,b=m==null?void 0:m.content_ignorelist),g===!1)return!1;var{targetElementList:k}=n5(p,!1);return!(function(w,C){if(w===!1||We(w))return!1;var E;if(w===!0)E=XW;else{if(!sn(w))return!1;if(w.length>10)return Ue.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;E=w.map((A=>A.toLowerCase()))}return C.some((A=>{var{safeText:R,ariaLabel:P}=A;return E.some((I=>R.includes(I)||P.includes(I)))}))})(b,k.map((w=>{var C;return{safeText:hp(w).toLowerCase(),ariaLabel:((C=w.getAttribute("aria-label"))==null?void 0:C.toLowerCase().trim())||""}})))&&!e5(k,g)})(r,this.instance.config.rageclick)&&this.Vs(e,"$rageclick");var i=t===Rb;if(r&&(function(p,m,g,b,x){var k,w,C,E;if(g===void 0&&(g=void 0),!me||_4(p)||(k=g)!=null&&k.url_allowlist&&!QS(g.url_allowlist)||(w=g)!=null&&w.url_ignorelist&&QS(g.url_ignorelist))return!1;if((C=g)!=null&&C.dom_event_allowlist){var A=g.dom_event_allowlist;if(A&&!A.some((L=>m.type===L)))return!1}var{parentIsUsefulElement:R,targetElementList:P}=n5(p,b);if(!(function(L,M){var D=M==null?void 0:M.element_allowlist;if(We(D))return!0;var O,F=function(V){if(D.some((U=>V.tagName.toLowerCase()===U)))return{v:!0}};for(var Z of L)if(O=F(Z))return O.v;return!1})(P,g)||!e5(P,(E=g)==null?void 0:E.css_selector_allowlist))return!1;var I=me.getComputedStyle(p);if(I&&I.getPropertyValue("cursor")==="pointer"&&m.type==="click")return!0;var T=p.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(x||["submit"]).indexOf(m.type)>=0;case"input":case"select":case"textarea":return(x||["change","click"]).indexOf(m.type)>=0;default:return R?(x||["click"]).indexOf(m.type)>=0:(x||["click"]).indexOf(m.type)>=0&&(t3.indexOf(T)>-1||p.getAttribute("contenteditable")==="true")}})(r,e,this.qt,i,i?["copy","cut"]:void 0)){var{props:s,explicitNoCapture:o}=iG(r,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.qt.element_attribute_ignorelist,elementsChainAsString:this.Us});if(o)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(s.$element_selectors=a),t===Rb){var l,u=x9(me==null||(l=me.getSelection())==null?void 0:l.toString()),f=e.type||"clipboard";if(!u)return!1;s.$selected_content=u,s.$copy_type=f}return this.instance.capture(t,s),!0}}}isBrowserSupported(){return zo(Ze==null?void 0:Ze.querySelectorAll)}},historyAutocapture:class{constructor(e){var t;this._instance=e,this.Ws=(me==null||(t=me.location)==null?void 0:t.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ue.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.Zs&&this.Zs(),this.Zs=void 0,Ue.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(me&&me.history){var n=this;(e=me.history.pushState)!=null&&e.__posthog_wrapped__||o5(me.history,"pushState",(r=>function(i,s,o){r.call(this,i,s,o),n.Gs("pushState")})),(t=me.history.replaceState)!=null&&t.__posthog_wrapped__||o5(me.history,"replaceState",(r=>function(i,s,o){r.call(this,i,s,o),n.Gs("replaceState")})),this.Qs()}}Gs(e){try{var t,n=me==null||(t=me.location)==null?void 0:t.pathname;if(!n)return;n!==this.Ws&&this.isEnabled&&this._instance.capture(Uu,{navigation_type:e}),this.Ws=n}catch(r){Ue.error("Error capturing "+e+" pageview",r)}}Qs(){if(!this.Zs){var e=()=>{this.Gs("popstate")};Wn(me,"popstate",e),this.Zs=()=>{me&&me.removeEventListener("popstate",e)}}}},heatmaps:class{get qt(){return this.instance.config}constructor(e){var t;this.Js=!1,this.js=!1,this.Ks=null,this.instance=e,this.Js=!((t=this.instance.persistence)==null||!t.props[Kw]),this.rageclicks=new s5(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return Yn(this.qt.capture_heatmaps)&&this.qt.capture_heatmaps.flush_interval_milliseconds&&(e=this.qt.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return Kt(this.qt.capture_heatmaps)?Kt(this.qt.enable_heatmaps)?this.Js:this.qt.enable_heatmaps:this.qt.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.js)return;oG.info("starting..."),this.Ys(),this.At()}else{var e;clearInterval((e=this.Ks)!==null&&e!==void 0?e:void 0),this.Xs(),this.getAndClearBuffer()}}onRemoteConfig(e){if("heatmaps"in e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Kw]:t}),this.Js=t,this.startIfEnabled()}}getAndClearBuffer(){var e=this.M;return this.M=void 0,e}eo(e){this.Mt(e.originalEvent,"deadclick")}At(){this.Ks&&clearInterval(this.Ks),this.Ks=(Ze==null?void 0:Ze.visibilityState)==="visible"?setInterval(this.Kr.bind(this),this.flushIntervalMilliseconds):null}Ys(){me&&Ze&&(this.ro=this.Kr.bind(this),Wn(me,l1,this.ro),this.io=e=>this.Mt(e||(me==null?void 0:me.event)),Wn(Ze,"click",this.io,{capture:!0}),this.no=e=>this.so(e||(me==null?void 0:me.event)),Wn(Ze,"mousemove",this.no,{capture:!0}),this.oo=new MS(this.instance,mW,this.eo.bind(this)),this.oo.startIfEnabledOrStop(),this.ao=this.At.bind(this),Wn(Ze,a1,this.ao),this.js=!0)}Xs(){var e;me&&Ze&&(this.ro&&me.removeEventListener(l1,this.ro),this.io&&Ze.removeEventListener("click",this.io,{capture:!0}),this.no&&Ze.removeEventListener("mousemove",this.no,{capture:!0}),this.ao&&Ze.removeEventListener(a1,this.ao),clearTimeout(this.uo),(e=this.oo)==null||e.stop(),this.js=!1)}lo(e,t){var n=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&Rc(u)&&!As(u,"body");){if(u===l)return!1;if(At(a,me==null?void 0:me.getComputedStyle(u).position))return!0;u=w9(u)}return!1})(JS(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:r),y:e.clientY+(s?0:n),target_fixed:s,type:t}}Mt(e,t){var n;if(t===void 0&&(t="click"),!XS(e.target)&&u5(e)){var r=this.lo(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.ho(Oe({},r,{type:"rageclick"})),this.ho(r)}}so(e){!XS(e.target)&&u5(e)&&(clearTimeout(this.uo),this.uo=setTimeout((()=>{this.ho(this.lo(e,"mousemove"))}),500))}ho(e){if(me){var t=me.location.href,n=this.qt.custom_personal_data_properties,r=this.qt.mask_personal_data_properties?[...Nd,...n||[]]:[],i=dp(t,r,fp);this.M=this.M||{},this.M[i]||(this.M[i]=[]),this.M[i].push(e)}}Kr(){this.M&&!Ku(this.M)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:MS,webVitalsAutocapture:class{constructor(e){var t;this.Js=!1,this.js=!1,this.M={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.co=()=>{clearTimeout(this.do),this.M.metrics.length!==0&&(this._instance.capture("$web_vitals",this.M.metrics.reduce(((n,r)=>Oe({},n,{["$web_vitals_"+r.name+"_event"]:Oe({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{})),this.M={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.ht=n=>{var r;this.M=this.M||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var i=this.vo();if(!We(i))if(Kt(n==null?void 0:n.name)||Kt(n==null?void 0:n.value))Gl.error("Invalid metric received",n);else if(!this.fo||this.fo>n.value){this.M.url!==i&&(this.co(),this.do=setTimeout(this.co,this.flushToCaptureTimeoutMs)),We(this.M.url)&&(this.M.url=i),this.M.firstMetricTimestamp=We(this.M.firstMetricTimestamp)?Date.now():this.M.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var s=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),o=Oe({},n,{$current_url:i,timestamp:Date.now()});We(s)||(o.$session_id=s.sessionId,o.$window_id=s.windowId),this.M.metrics.push(o),this.M.metrics.length===this.allowedMetrics.length&&this.co()}else Gl.error("Ignoring metric with value >= "+this.fo,n)},this.po=()=>{if(!this.js){var n,r,i,s,o=gt.__PosthogExtensions__;We(o)||We(o.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:r,onFCP:i,onINP:s}=o.postHogWebVitalsCallbacks),n&&r&&i&&s?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.ht.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&r(this.ht.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.ht.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&s(this.ht.bind(this)),this.js=!0):Gl.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.Js=!((t=this._instance.persistence)==null||!t.props[Jw]),this.startIfEnabled()}get mo(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,n=Yn(this.mo)?(e=this.mo)==null?void 0:e.web_vitals_allowed_metrics:void 0;return Kt(n)?((t=this._instance.persistence)==null?void 0:t.props[t4])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(Yn(this.mo)?this.mo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=Yn(this.mo)?this.mo.web_vitals_attribution:void 0;return e!=null&&e}get fo(){var e=Yn(this.mo)&&Hi(this.mo.__web_vitals_max_value)?this.mo.__web_vitals_max_value:a5;return e>0&&6e4>=e?a5:e}get isEnabled(){var e=Pr==null?void 0:Pr.protocol;if(e!=="http:"&&e!=="https:")return Gl.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=Yn(this.mo)?this.mo.web_vitals:oo(this.mo)?this.mo:void 0;return oo(t)?t:this.Js}startIfEnabled(){this.isEnabled&&!this.js&&(Gl.info("enabled, starting..."),this.lr(this.po))}onRemoteConfig(e){if("capturePerformance"in e){var t=Yn(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=Yn(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Jw]:t}),this._instance.persistence.register({[t4]:n})),this.Js=t,this.startIfEnabled()}}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks?e():(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.useAttribution?"web-vitals-with-attribution":"web-vitals",(r=>{r?Gl.error("failed to load script",r):e()}))}vo(){var e=me?me.location.href:void 0;if(e){var t=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...Nd,...t||[]]:[];return dp(e,n,fp)}Gl.error("Could not determine current URL")}}},mG={exceptionObserver:class{constructor(e){var t,n,r;this.po=()=>{var i;if(me&&this.isEnabled&&(i=gt.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var s=gt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,o=gt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=gt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.yo&&this.qt.capture_unhandled_errors&&(this.yo=s(this.captureException.bind(this))),!this.bo&&this.qt.capture_unhandled_rejections&&(this.bo=o(this.captureException.bind(this))),!this._o&&this.qt.capture_console_errors&&(this._o=a(this.captureException.bind(this)))}catch(l){ah.error("failed to start",l),this.wo()}}},this._instance=e,this.xo=!((t=this._instance.persistence)==null||!t.props[Yw]),this.So=new CZ({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(r=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10,refillInterval:1e4,Gt:ah}),this.qt=this.ko(),this.startIfEnabledOrStop()}ko(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Yn(e)?t=Oe({},t,e):(We(e)?this.xo:e)&&(t=Oe({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.qt.capture_console_errors||this.qt.capture_unhandled_errors||this.qt.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ah.info("enabled"),this.wo(),this.lr(this.po)):this.wo()}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return ah.error("failed to load script",r);e()}))}wo(){var e,t,n;(e=this.yo)==null||e.call(this),this.yo=void 0,(t=this.bo)==null||t.call(this),this.bo=void 0,(n=this._o)==null||n.call(this),this._o=void 0}onRemoteConfig(e){"autocaptureExceptions"in e&&(this.xo=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Yw]:this.xo}),this.qt=this.ko(),this.startIfEnabledOrStop())}onConfigChange(){this.qt=this.ko()}captureException(e){var t,n,r,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.So.consumeRateLimit(i)?ah.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(e)}},exceptions:class{constructor(e){var t,n;this.Co=[],this.Io=new jZ([new ZZ,new eW,new GZ,new WZ,new QZ,new XZ,new KZ,new JZ],(function(r){for(var i=arguments.length,s=new Array(i>1?i-1:0),o=1;i>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],f=a.split(`
|
|
17
|
+
*/var sS;function TU(){if(sS)return Jf;sS=1;var e=j8(),t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,i=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,s={key:!0,ref:!0,__self:!0,__source:!0};function o(a,l,u){var f,p={},m=null,g=null;u!==void 0&&(m=""+u),l.key!==void 0&&(m=""+l.key),l.ref!==void 0&&(g=l.ref);for(f in l)r.call(l,f)&&!s.hasOwnProperty(f)&&(p[f]=l[f]);if(a&&a.defaultProps)for(f in l=a.defaultProps,l)p[f]===void 0&&(p[f]=l[f]);return{$$typeof:t,type:a,key:m,ref:g,props:p,_owner:i.current}}return Jf.Fragment=n,Jf.jsx=o,Jf.jsxs=o,Jf}var oS;function PU(){return oS||(oS=1,fb.exports=TU()),fb.exports}var y=PU(),h=j8();const xe=Wc(h),QR=SU({__proto__:null,default:xe},[h]);var Gp=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},fc,Ya,bd,FR,IU=(FR=class extends Gp{constructor(){super();_t(this,fc);_t(this,Ya);_t(this,bd);tt(this,bd,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){se(this,Ya)||this.setEventListener(se(this,bd))}onUnsubscribe(){var t;this.hasListeners()||((t=se(this,Ya))==null||t.call(this),tt(this,Ya,void 0))}setEventListener(t){var n;tt(this,bd,t),(n=se(this,Ya))==null||n.call(this),tt(this,Ya,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){se(this,fc)!==t&&(tt(this,fc,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof se(this,fc)=="boolean"?se(this,fc):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},fc=new WeakMap,Ya=new WeakMap,bd=new WeakMap,FR),F8=new IU,RU={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Xa,L8,OR,MU=(OR=class{constructor(){_t(this,Xa,RU);_t(this,L8,!1)}setTimeoutProvider(e){tt(this,Xa,e)}setTimeout(e,t){return se(this,Xa).setTimeout(e,t)}clearTimeout(e){se(this,Xa).clearTimeout(e)}setInterval(e,t){return se(this,Xa).setInterval(e,t)}clearInterval(e){se(this,Xa).clearInterval(e)}},Xa=new WeakMap,L8=new WeakMap,OR),ac=new MU;function $U(e){setTimeout(e,0)}var DU=typeof window>"u"||"Deno"in globalThis;function hi(){}function NU(e,t){return typeof e=="function"?e(t):e}function kw(e){return typeof e=="number"&&e>=0&&e!==1/0}function JR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function al(e,t){return typeof e=="function"?e(t):e}function Mi(e,t){return typeof e=="function"?e(t):e}function aS(e,t){const{type:n="all",exact:r,fetchStatus:i,predicate:s,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==O8(o,t.options))return!1}else if(!op(t.queryKey,o))return!1}if(n!=="all"){const l=t.isActive();if(n==="active"&&!l||n==="inactive"&&l)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||i&&i!==t.state.fetchStatus||s&&!s(t))}function lS(e,t){const{exact:n,status:r,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(n){if(sp(t.options.mutationKey)!==sp(s))return!1}else if(!op(t.options.mutationKey,s))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function O8(e,t){return((t==null?void 0:t.queryKeyHashFn)||sp)(e)}function sp(e){return JSON.stringify(e,(t,n)=>Ew(n)?Object.keys(n).sort().reduce((r,i)=>(r[i]=n[i],r),{}):n)}function op(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>op(e[n],t[n])):!1}var LU=Object.prototype.hasOwnProperty;function eM(e,t,n=0){if(e===t)return e;if(n>500)return t;const r=cS(e)&&cS(t);if(!r&&!(Ew(e)&&Ew(t)))return t;const s=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,l=r?new Array(a):{};let u=0;for(let f=0;f<a;f++){const p=r?f:o[f],m=e[p],g=t[p];if(m===g){l[p]=m,(r?f<s:LU.call(e,p))&&u++;continue}if(m===null||g===null||typeof m!="object"||typeof g!="object"){l[p]=g;continue}const b=eM(m,g,n+1);l[p]=b,b===m&&u++}return s===a&&u===s?e:l}function Cw(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function cS(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ew(e){if(!uS(e))return!1;const t=e.constructor;if(t===void 0)return!0;const n=t.prototype;return!(!uS(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function uS(e){return Object.prototype.toString.call(e)==="[object Object]"}function jU(e){return new Promise(t=>{ac.setTimeout(t,e)})}function Sw(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?eM(e,t):t}function FU(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function OU(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var V8=Symbol();function tM(e,t){return!e.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!e.queryFn||e.queryFn===V8?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nM(e,t){return typeof e=="function"?e(...t):!!e}function VU(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??(i=t()),r||(r=!0,i.aborted?n():i.addEventListener("abort",n,{once:!0})),i)}),e}var ap=(()=>{let e=()=>DU;return{isServer(){return e()},setIsServer(t){e=t}}})();function Aw(){let e,t;const n=new Promise((i,s)=>{e=i,t=s});n.status="pending",n.catch(()=>{});function r(i){Object.assign(n,i),delete n.resolve,delete n.reject}return n.resolve=i=>{r({status:"fulfilled",value:i}),e(i)},n.reject=i=>{r({status:"rejected",reason:i}),t(i)},n}var HU=$U;function BU(){let e=[],t=0,n=a=>{a()},r=a=>{a()},i=HU;const s=a=>{t?e.push(a):i(()=>{n(a)})},o=()=>{const a=e;e=[],a.length&&i(()=>{r(()=>{a.forEach(l=>{n(l)})})})};return{batch:a=>{let l;t++;try{l=a()}finally{t--,t||o()}return l},batchCalls:a=>(...l)=>{s(()=>{a(...l)})},schedule:s,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{i=a}}}var Rr=BU(),xd,Qa,wd,VR,zU=(VR=class extends Gp{constructor(){super();_t(this,xd,!0);_t(this,Qa);_t(this,wd);tt(this,wd,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){se(this,Qa)||this.setEventListener(se(this,wd))}onUnsubscribe(){var t;this.hasListeners()||((t=se(this,Qa))==null||t.call(this),tt(this,Qa,void 0))}setEventListener(t){var n;tt(this,wd,t),(n=se(this,Qa))==null||n.call(this),tt(this,Qa,t(this.setOnline.bind(this)))}setOnline(t){se(this,xd)!==t&&(tt(this,xd,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return se(this,xd)}},xd=new WeakMap,Qa=new WeakMap,wd=new WeakMap,VR),qg=new zU;function UU(e){return Math.min(1e3*2**e,3e4)}function rM(e){return(e??"online")==="online"?qg.isOnline():!0}var Tw=class extends Error{constructor(e){super("CancelledError"),this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function iM(e){let t=!1,n=0,r;const i=Aw(),s=()=>i.status!=="pending",o=x=>{var k;if(!s()){const w=new Tw(x);m(w),(k=e.onCancel)==null||k.call(e,w)}},a=()=>{t=!0},l=()=>{t=!1},u=()=>F8.isFocused()&&(e.networkMode==="always"||qg.isOnline())&&e.canRun(),f=()=>rM(e.networkMode)&&e.canRun(),p=x=>{s()||(r==null||r(),i.resolve(x))},m=x=>{s()||(r==null||r(),i.reject(x))},g=()=>new Promise(x=>{var k;r=w=>{(s()||u())&&x(w)},(k=e.onPause)==null||k.call(e)}).then(()=>{var x;r=void 0,s()||(x=e.onContinue)==null||x.call(e)}),b=()=>{if(s())return;let x;const k=n===0?e.initialPromise:void 0;try{x=k??e.fn()}catch(w){x=Promise.reject(w)}Promise.resolve(x).then(p).catch(w=>{var P;if(s())return;const C=e.retry??(ap.isServer()?0:3),E=e.retryDelay??UU,A=typeof E=="function"?E(n,w):E,R=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,w);if(t||!R){m(w);return}n++,(P=e.onFail)==null||P.call(e,n,w),jU(A).then(()=>u()?void 0:g()).then(()=>{t?m(w):b()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r==null||r(),i),cancelRetry:a,continueRetry:l,canStart:f,start:()=>(f()?b():g().then(b),i)}}var hc,HR,sM=(HR=class{constructor(){_t(this,hc)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),kw(this.gcTime)&&tt(this,hc,ac.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ap.isServer()?1/0:300*1e3))}clearGcTimeout(){se(this,hc)!==void 0&&(ac.clearTimeout(se(this,hc)),tt(this,hc,void 0))}},hc=new WeakMap,HR);function ZU(e){return{onFetch:(t,n)=>{var f,p,m,g,b;const r=t.options,i=(m=(p=(f=t.fetchOptions)==null?void 0:f.meta)==null?void 0:p.fetchMore)==null?void 0:m.direction,s=((g=t.state.data)==null?void 0:g.pages)||[],o=((b=t.state.data)==null?void 0:b.pageParams)||[];let a={pages:[],pageParams:[]},l=0;const u=async()=>{let x=!1;const k=E=>{VU(E,()=>t.signal,()=>x=!0)},w=tM(t.options,t.fetchOptions),C=async(E,A,R)=>{if(x)return Promise.reject(t.signal.reason);if(A==null&&E.pages.length)return Promise.resolve(E);const I=(()=>{const D={client:t.client,queryKey:t.queryKey,pageParam:A,direction:R?"backward":"forward",meta:t.options.meta};return k(D),D})(),T=await w(I),{maxPages:L}=t.options,M=R?OU:FU;return{pages:M(E.pages,T,L),pageParams:M(E.pageParams,A,L)}};if(i&&s.length){const E=i==="backward",A=E?WU:dS,R={pages:s,pageParams:o},P=A(r,R);a=await C(R,P,E)}else{const E=e??s.length;do{const A=l===0?o[0]??r.initialPageParam:dS(r,a);if(l>0&&A==null)break;a=await C(a,A),l++}while(l<E)}return a};t.options.persister?t.fetchFn=()=>{var x,k;return(k=(x=t.options).persister)==null?void 0:k.call(x,u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=u}}}function dS(e,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function WU(e,{pages:t,pageParams:n}){var r;return t.length>0?(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n):void 0}var _d,pc,kd,Yi,mc,xr,Bp,gc,Ri,oM,jo,BR,GU=(BR=class extends sM{constructor(t){super();_t(this,Ri);_t(this,_d);_t(this,pc);_t(this,kd);_t(this,Yi);_t(this,mc);_t(this,xr);_t(this,Bp);_t(this,gc);tt(this,gc,!1),tt(this,Bp,t.defaultOptions),this.setOptions(t.options),this.observers=[],tt(this,mc,t.client),tt(this,Yi,se(this,mc).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,tt(this,pc,hS(this.options)),this.state=t.state??se(this,pc),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return se(this,_d)}get promise(){var t;return(t=se(this,xr))==null?void 0:t.promise}setOptions(t){if(this.options={...se(this,Bp),...t},t!=null&&t._type&&tt(this,_d,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=hS(this.options);n.data!==void 0&&(this.setState(fS(n.data,n.dataUpdatedAt)),tt(this,pc,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&se(this,Yi).remove(this)}setData(t,n){const r=Sw(this.state.data,t,this.options);return Xt(this,Ri,jo).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){Xt(this,Ri,jo).call(this,{type:"setState",state:t})}cancel(t){var r,i;const n=(r=se(this,xr))==null?void 0:r.promise;return(i=se(this,xr))==null||i.cancel(t),n?n.then(hi).catch(hi):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return se(this,pc)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Mi(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===V8||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>al(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!JR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=se(this,xr))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=se(this,xr))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),se(this,Yi).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(se(this,xr)&&(se(this,gc)||Xt(this,Ri,oM).call(this)?se(this,xr).cancel({revert:!0}):se(this,xr).cancelRetry()),this.scheduleGc()),se(this,Yi).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Xt(this,Ri,jo).call(this,{type:"invalidate"})}async fetch(t,n){var u,f,p,m,g,b,x,k,w,C,E;if(this.state.fetchStatus!=="idle"&&((u=se(this,xr))==null?void 0:u.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(se(this,xr))return se(this,xr).continueRetry(),se(this,xr).promise}if(t&&this.setOptions(t),!this.options.queryFn){const A=this.observers.find(R=>R.options.queryFn);A&&this.setOptions(A.options)}const r=new AbortController,i=A=>{Object.defineProperty(A,"signal",{enumerable:!0,get:()=>(tt(this,gc,!0),r.signal)})},s=()=>{const A=tM(this.options,n),P=(()=>{const I={client:se(this,mc),queryKey:this.queryKey,meta:this.meta};return i(I),I})();return tt(this,gc,!1),this.options.persister?this.options.persister(A,P,this):A(P)},a=(()=>{const A={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:se(this,mc),state:this.state,fetchFn:s};return i(A),A})(),l=se(this,_d)==="infinite"?ZU(this.options.pages):this.options.behavior;l==null||l.onFetch(a,this),tt(this,kd,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((f=a.fetchOptions)==null?void 0:f.meta))&&Xt(this,Ri,jo).call(this,{type:"fetch",meta:(p=a.fetchOptions)==null?void 0:p.meta}),tt(this,xr,iM({initialPromise:n==null?void 0:n.initialPromise,fn:a.fetchFn,onCancel:A=>{A instanceof Tw&&A.revert&&this.setState({...se(this,kd),fetchStatus:"idle"}),r.abort()},onFail:(A,R)=>{Xt(this,Ri,jo).call(this,{type:"failed",failureCount:A,error:R})},onPause:()=>{Xt(this,Ri,jo).call(this,{type:"pause"})},onContinue:()=>{Xt(this,Ri,jo).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{const A=await se(this,xr).start();if(A===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(A),(g=(m=se(this,Yi).config).onSuccess)==null||g.call(m,A,this),(x=(b=se(this,Yi).config).onSettled)==null||x.call(b,A,this.state.error,this),A}catch(A){if(A instanceof Tw){if(A.silent)return se(this,xr).promise;if(A.revert){if(this.state.data===void 0)throw A;return this.state.data}}throw Xt(this,Ri,jo).call(this,{type:"error",error:A}),(w=(k=se(this,Yi).config).onError)==null||w.call(k,A,this),(E=(C=se(this,Yi).config).onSettled)==null||E.call(C,this.state.data,A,this),A}finally{this.scheduleGc()}}},_d=new WeakMap,pc=new WeakMap,kd=new WeakMap,Yi=new WeakMap,mc=new WeakMap,xr=new WeakMap,Bp=new WeakMap,gc=new WeakMap,Ri=new WeakSet,oM=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},jo=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...aM(r.data,this.options),fetchMeta:t.meta??null};case"success":const i={...r,...fS(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return tt(this,kd,t.manual?i:void 0),i;case"error":const s=t.error;return{...r,error:s,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:s,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Rr.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),se(this,Yi).notify({query:this,type:"updated",action:t})})},BR);function aM(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:rM(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function fS(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function hS(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var ci,tn,zp,Yr,vc,Cd,Zo,Ja,Up,Ed,Sd,yc,bc,el,Ad,gn,Ch,Pw,Iw,Rw,Mw,$w,Dw,Nw,lM,zR,qU=(zR=class extends Gp{constructor(t,n){super();_t(this,gn);_t(this,ci);_t(this,tn);_t(this,zp);_t(this,Yr);_t(this,vc);_t(this,Cd);_t(this,Zo);_t(this,Ja);_t(this,Up);_t(this,Ed);_t(this,Sd);_t(this,yc);_t(this,bc);_t(this,el);_t(this,Ad,new Set);this.options=n,tt(this,ci,t),tt(this,Ja,null),tt(this,Zo,Aw()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(se(this,tn).addObserver(this),pS(se(this,tn),this.options)?Xt(this,gn,Ch).call(this):this.updateResult(),Xt(this,gn,Mw).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Lw(se(this,tn),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Lw(se(this,tn),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Xt(this,gn,$w).call(this),Xt(this,gn,Dw).call(this),se(this,tn).removeObserver(this)}setOptions(t){const n=this.options,r=se(this,tn);if(this.options=se(this,ci).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Mi(this.options.enabled,se(this,tn))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Xt(this,gn,Nw).call(this),se(this,tn).setOptions(this.options),n._defaulted&&!Cw(this.options,n)&&se(this,ci).getQueryCache().notify({type:"observerOptionsUpdated",query:se(this,tn),observer:this});const i=this.hasListeners();i&&mS(se(this,tn),r,this.options,n)&&Xt(this,gn,Ch).call(this),this.updateResult(),i&&(se(this,tn)!==r||Mi(this.options.enabled,se(this,tn))!==Mi(n.enabled,se(this,tn))||al(this.options.staleTime,se(this,tn))!==al(n.staleTime,se(this,tn)))&&Xt(this,gn,Pw).call(this);const s=Xt(this,gn,Iw).call(this);i&&(se(this,tn)!==r||Mi(this.options.enabled,se(this,tn))!==Mi(n.enabled,se(this,tn))||s!==se(this,el))&&Xt(this,gn,Rw).call(this,s)}getOptimisticResult(t){const n=se(this,ci).getQueryCache().build(se(this,ci),t),r=this.createResult(n,t);return YU(this,r)&&(tt(this,Yr,r),tt(this,Cd,this.options),tt(this,vc,se(this,tn).state)),r}getCurrentResult(){return se(this,Yr)}trackResult(t,n){return new Proxy(t,{get:(r,i)=>(this.trackProp(i),n==null||n(i),i==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&se(this,Zo).status==="pending"&&se(this,Zo).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,i))})}trackProp(t){se(this,Ad).add(t)}getCurrentQuery(){return se(this,tn)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=se(this,ci).defaultQueryOptions(t),r=se(this,ci).getQueryCache().build(se(this,ci),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Xt(this,gn,Ch).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),se(this,Yr)))}createResult(t,n){var L;const r=se(this,tn),i=this.options,s=se(this,Yr),o=se(this,vc),a=se(this,Cd),u=t!==r?t.state:se(this,zp),{state:f}=t;let p={...f},m=!1,g;if(n._optimisticResults){const M=this.hasListeners(),D=!M&&pS(t,n),O=M&&mS(t,r,n,i);(D||O)&&(p={...p,...aM(f.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:b,errorUpdatedAt:x,status:k}=p;g=p.data;let w=!1;if(n.placeholderData!==void 0&&g===void 0&&k==="pending"){let M;s!=null&&s.isPlaceholderData&&n.placeholderData===(a==null?void 0:a.placeholderData)?(M=s.data,w=!0):M=typeof n.placeholderData=="function"?n.placeholderData((L=se(this,Sd))==null?void 0:L.state.data,se(this,Sd)):n.placeholderData,M!==void 0&&(k="success",g=Sw(s==null?void 0:s.data,M,n),m=!0)}if(n.select&&g!==void 0&&!w)if(s&&g===(o==null?void 0:o.data)&&n.select===se(this,Up))g=se(this,Ed);else try{tt(this,Up,n.select),g=n.select(g),g=Sw(s==null?void 0:s.data,g,n),tt(this,Ed,g),tt(this,Ja,null)}catch(M){tt(this,Ja,M)}se(this,Ja)&&(b=se(this,Ja),g=se(this,Ed),x=Date.now(),k="error");const C=p.fetchStatus==="fetching",E=k==="pending",A=k==="error",R=E&&C,P=g!==void 0,T={status:k,fetchStatus:p.fetchStatus,isPending:E,isSuccess:k==="success",isError:A,isInitialLoading:R,isLoading:R,data:g,dataUpdatedAt:p.dataUpdatedAt,error:b,errorUpdatedAt:x,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:A&&!P,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:A&&P,isStale:H8(t,n),refetch:this.refetch,promise:se(this,Zo),isEnabled:Mi(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const M=T.data!==void 0,D=T.status==="error"&&!M,O=V=>{D?V.reject(T.error):M&&V.resolve(T.data)},F=()=>{const V=tt(this,Zo,T.promise=Aw());O(V)},Z=se(this,Zo);switch(Z.status){case"pending":t.queryHash===r.queryHash&&O(Z);break;case"fulfilled":(D||T.data!==Z.value)&&F();break;case"rejected":(!D||T.error!==Z.reason)&&F();break}}return T}updateResult(){const t=se(this,Yr),n=this.createResult(se(this,tn),this.options);if(tt(this,vc,se(this,tn).state),tt(this,Cd,this.options),se(this,vc).data!==void 0&&tt(this,Sd,se(this,tn)),Cw(n,t))return;tt(this,Yr,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,s=typeof i=="function"?i():i;if(s==="all"||!s&&!se(this,Ad).size)return!0;const o=new Set(s??se(this,Ad));return this.options.throwOnError&&o.add("error"),Object.keys(se(this,Yr)).some(a=>{const l=a;return se(this,Yr)[l]!==t[l]&&o.has(l)})};Xt(this,gn,lM).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Xt(this,gn,Mw).call(this)}},ci=new WeakMap,tn=new WeakMap,zp=new WeakMap,Yr=new WeakMap,vc=new WeakMap,Cd=new WeakMap,Zo=new WeakMap,Ja=new WeakMap,Up=new WeakMap,Ed=new WeakMap,Sd=new WeakMap,yc=new WeakMap,bc=new WeakMap,el=new WeakMap,Ad=new WeakMap,gn=new WeakSet,Ch=function(t){Xt(this,gn,Nw).call(this);let n=se(this,tn).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(hi)),n},Pw=function(){Xt(this,gn,$w).call(this);const t=al(this.options.staleTime,se(this,tn));if(ap.isServer()||se(this,Yr).isStale||!kw(t))return;const r=JR(se(this,Yr).dataUpdatedAt,t)+1;tt(this,yc,ac.setTimeout(()=>{se(this,Yr).isStale||this.updateResult()},r))},Iw=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(se(this,tn)):this.options.refetchInterval)??!1},Rw=function(t){Xt(this,gn,Dw).call(this),tt(this,el,t),!(ap.isServer()||Mi(this.options.enabled,se(this,tn))===!1||!kw(se(this,el))||se(this,el)===0)&&tt(this,bc,ac.setInterval(()=>{(this.options.refetchIntervalInBackground||F8.isFocused())&&Xt(this,gn,Ch).call(this)},se(this,el)))},Mw=function(){Xt(this,gn,Pw).call(this),Xt(this,gn,Rw).call(this,Xt(this,gn,Iw).call(this))},$w=function(){se(this,yc)!==void 0&&(ac.clearTimeout(se(this,yc)),tt(this,yc,void 0))},Dw=function(){se(this,bc)!==void 0&&(ac.clearInterval(se(this,bc)),tt(this,bc,void 0))},Nw=function(){const t=se(this,ci).getQueryCache().build(se(this,ci),this.options);if(t===se(this,tn))return;const n=se(this,tn);tt(this,tn,t),tt(this,zp,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},lM=function(t){Rr.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(se(this,Yr))}),se(this,ci).getQueryCache().notify({query:se(this,tn),type:"observerResultsUpdated"})})},zR);function KU(e,t){return Mi(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&Mi(t.retryOnMount,e)===!1)}function pS(e,t){return KU(e,t)||e.state.data!==void 0&&Lw(e,t,t.refetchOnMount)}function Lw(e,t,n){if(Mi(t.enabled,e)!==!1&&al(t.staleTime,e)!=="static"){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&H8(e,t)}return!1}function mS(e,t,n,r){return(e!==t||Mi(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&H8(e,n)}function H8(e,t){return Mi(t.enabled,e)!==!1&&e.isStaleByTime(al(t.staleTime,e))}function YU(e,t){return!Cw(e.getCurrentResult(),t)}var Zp,Js,Hr,xc,eo,za,UR,XU=(UR=class extends sM{constructor(t){super();_t(this,eo);_t(this,Zp);_t(this,Js);_t(this,Hr);_t(this,xc);tt(this,Zp,t.client),this.mutationId=t.mutationId,tt(this,Hr,t.mutationCache),tt(this,Js,[]),this.state=t.state||QU(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){se(this,Js).includes(t)||(se(this,Js).push(t),this.clearGcTimeout(),se(this,Hr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){tt(this,Js,se(this,Js).filter(n=>n!==t)),this.scheduleGc(),se(this,Hr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){se(this,Js).length||(this.state.status==="pending"?this.scheduleGc():se(this,Hr).remove(this))}continue(){var t;return((t=se(this,xc))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,a,l,u,f,p,m,g,b,x,k,w,C,E,A,R,P,I;const n=()=>{Xt(this,eo,za).call(this,{type:"continue"})},r={client:se(this,Zp),meta:this.options.meta,mutationKey:this.options.mutationKey};tt(this,xc,iM({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(T,L)=>{Xt(this,eo,za).call(this,{type:"failed",failureCount:T,error:L})},onPause:()=>{Xt(this,eo,za).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>se(this,Hr).canRun(this)}));const i=this.state.status==="pending",s=!se(this,xc).canStart();try{if(i)n();else{Xt(this,eo,za).call(this,{type:"pending",variables:t,isPaused:s}),se(this,Hr).config.onMutate&&await se(this,Hr).config.onMutate(t,this,r);const L=await((a=(o=this.options).onMutate)==null?void 0:a.call(o,t,r));L!==this.state.context&&Xt(this,eo,za).call(this,{type:"pending",context:L,variables:t,isPaused:s})}const T=await se(this,xc).start();return await((u=(l=se(this,Hr).config).onSuccess)==null?void 0:u.call(l,T,t,this.state.context,this,r)),await((p=(f=this.options).onSuccess)==null?void 0:p.call(f,T,t,this.state.context,r)),await((g=(m=se(this,Hr).config).onSettled)==null?void 0:g.call(m,T,null,this.state.variables,this.state.context,this,r)),await((x=(b=this.options).onSettled)==null?void 0:x.call(b,T,null,t,this.state.context,r)),Xt(this,eo,za).call(this,{type:"success",data:T}),T}catch(T){try{await((w=(k=se(this,Hr).config).onError)==null?void 0:w.call(k,T,t,this.state.context,this,r))}catch(L){Promise.reject(L)}try{await((E=(C=this.options).onError)==null?void 0:E.call(C,T,t,this.state.context,r))}catch(L){Promise.reject(L)}try{await((R=(A=se(this,Hr).config).onSettled)==null?void 0:R.call(A,void 0,T,this.state.variables,this.state.context,this,r))}catch(L){Promise.reject(L)}try{await((I=(P=this.options).onSettled)==null?void 0:I.call(P,void 0,T,t,this.state.context,r))}catch(L){Promise.reject(L)}throw Xt(this,eo,za).call(this,{type:"error",error:T}),T}finally{se(this,Hr).runNext(this)}}},Zp=new WeakMap,Js=new WeakMap,Hr=new WeakMap,xc=new WeakMap,eo=new WeakSet,za=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Rr.batch(()=>{se(this,Js).forEach(r=>{r.onMutationUpdate(t)}),se(this,Hr).notify({mutation:this,type:"updated",action:t})})},UR);function QU(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Wo,ks,Wp,ZR,JU=(ZR=class extends Gp{constructor(t={}){super();_t(this,Wo);_t(this,ks);_t(this,Wp);this.config=t,tt(this,Wo,new Set),tt(this,ks,new Map),tt(this,Wp,0)}build(t,n,r){const i=new XU({client:t,mutationCache:this,mutationId:++ym(this,Wp)._,options:t.defaultMutationOptions(n),state:r});return this.add(i),i}add(t){se(this,Wo).add(t);const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n);r?r.push(t):se(this,ks).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(se(this,Wo).delete(t)){const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n);if(r)if(r.length>1){const i=r.indexOf(t);i!==-1&&r.splice(i,1)}else r[0]===t&&se(this,ks).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=xm(t);if(typeof n=="string"){const r=se(this,ks).get(n),i=r==null?void 0:r.find(s=>s.state.status==="pending");return!i||i===t}else return!0}runNext(t){var r;const n=xm(t);if(typeof n=="string"){const i=(r=se(this,ks).get(n))==null?void 0:r.find(s=>s!==t&&s.state.isPaused);return(i==null?void 0:i.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Rr.batch(()=>{se(this,Wo).forEach(t=>{this.notify({type:"removed",mutation:t})}),se(this,Wo).clear(),se(this,ks).clear()})}getAll(){return Array.from(se(this,Wo))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>lS(n,r))}findAll(t={}){return this.getAll().filter(n=>lS(t,n))}notify(t){Rr.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Rr.batch(()=>Promise.all(t.map(n=>n.continue().catch(hi))))}},Wo=new WeakMap,ks=new WeakMap,Wp=new WeakMap,ZR);function xm(e){var t;return(t=e.options.scope)==null?void 0:t.id}var to,WR,eZ=(WR=class extends Gp{constructor(t={}){super();_t(this,to);this.config=t,tt(this,to,new Map)}build(t,n,r){const i=n.queryKey,s=n.queryHash??O8(i,n);let o=this.get(s);return o||(o=new GU({client:t,queryKey:i,queryHash:s,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(i)}),this.add(o)),o}add(t){se(this,to).has(t.queryHash)||(se(this,to).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=se(this,to).get(t.queryHash);n&&(t.destroy(),n===t&&se(this,to).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Rr.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return se(this,to).get(t)}getAll(){return[...se(this,to).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>aS(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>aS(t,r)):n}notify(t){Rr.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Rr.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Rr.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},to=new WeakMap,WR),Zn,tl,nl,Td,Pd,rl,Id,Rd,GR,tZ=(GR=class{constructor(e={}){_t(this,Zn);_t(this,tl);_t(this,nl);_t(this,Td);_t(this,Pd);_t(this,rl);_t(this,Id);_t(this,Rd);tt(this,Zn,e.queryCache||new eZ),tt(this,tl,e.mutationCache||new JU),tt(this,nl,e.defaultOptions||{}),tt(this,Td,new Map),tt(this,Pd,new Map),tt(this,rl,0)}mount(){ym(this,rl)._++,se(this,rl)===1&&(tt(this,Id,F8.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Zn).onFocus())})),tt(this,Rd,qg.subscribe(async e=>{e&&(await this.resumePausedMutations(),se(this,Zn).onOnline())})))}unmount(){var e,t;ym(this,rl)._--,se(this,rl)===0&&((e=se(this,Id))==null||e.call(this),tt(this,Id,void 0),(t=se(this,Rd))==null||t.call(this),tt(this,Rd,void 0))}isFetching(e){return se(this,Zn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return se(this,tl).findAll({...e,status:"pending"}).length}getQueryData(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=se(this,Zn).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(e){const t=this.defaultQueryOptions(e),n=se(this,Zn).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(al(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return se(this,Zn).findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=this.defaultQueryOptions({queryKey:e}),i=se(this,Zn).get(r.queryHash),s=i==null?void 0:i.state.data,o=NU(t,s);if(o!==void 0)return se(this,Zn).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return Rr.batch(()=>se(this,Zn).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var n;const t=this.defaultQueryOptions({queryKey:e});return(n=se(this,Zn).get(t.queryHash))==null?void 0:n.state}removeQueries(e){const t=se(this,Zn);Rr.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=se(this,Zn);return Rr.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){const n={revert:!0,...t},r=Rr.batch(()=>se(this,Zn).findAll(e).map(i=>i.cancel(n)));return Promise.all(r).then(hi).catch(hi)}invalidateQueries(e,t={}){return Rr.batch(()=>(se(this,Zn).findAll(e).forEach(n=>{n.invalidate()}),(e==null?void 0:e.refetchType)==="none"?Promise.resolve():this.refetchQueries({...e,type:(e==null?void 0:e.refetchType)??(e==null?void 0:e.type)??"active"},t)))}refetchQueries(e,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Rr.batch(()=>se(this,Zn).findAll(e).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let s=i.fetch(void 0,n);return n.throwOnError||(s=s.catch(hi)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(r).then(hi)}fetchQuery(e){const t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);const n=se(this,Zn).build(this,t);return n.isStaleByTime(al(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(hi).catch(hi)}fetchInfiniteQuery(e){return e._type="infinite",this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(hi).catch(hi)}ensureInfiniteQueryData(e){return e._type="infinite",this.ensureQueryData(e)}resumePausedMutations(){return qg.isOnline()?se(this,tl).resumePausedMutations():Promise.resolve()}getQueryCache(){return se(this,Zn)}getMutationCache(){return se(this,tl)}getDefaultOptions(){return se(this,nl)}setDefaultOptions(e){tt(this,nl,e)}setQueryDefaults(e,t){se(this,Td).set(sp(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...se(this,Td).values()],n={};return t.forEach(r=>{op(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){se(this,Pd).set(sp(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...se(this,Pd).values()],n={};return t.forEach(r=>{op(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;const t={...se(this,nl).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=O8(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===V8&&(t.enabled=!1),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...se(this,nl).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){se(this,Zn).clear(),se(this,tl).clear()}},Zn=new WeakMap,tl=new WeakMap,nl=new WeakMap,Td=new WeakMap,Pd=new WeakMap,rl=new WeakMap,Id=new WeakMap,Rd=new WeakMap,GR),cM=h.createContext(void 0),nZ=e=>{const t=h.useContext(cM);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},rZ=({client:e,children:t})=>(h.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),y.jsx(cM.Provider,{value:e,children:t})),uM=h.createContext(!1),iZ=()=>h.useContext(uM);uM.Provider;function sZ(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var oZ=h.createContext(sZ()),aZ=()=>h.useContext(oZ),lZ=(e,t,n)=>{const r=n!=null&&n.state.error&&typeof e.throwOnError=="function"?nM(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},cZ=e=>{h.useEffect(()=>{e.clearReset()},[e])},uZ=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||nM(n,[e.error,r])),dZ=e=>{if(e.suspense){const n=i=>i==="static"?i:Math.max(i??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...i)=>n(r(...i)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},fZ=(e,t)=>e.isLoading&&e.isFetching&&!t,hZ=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,gS=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function pZ(e,t,n){var g,b,x,k;const r=iZ(),i=aZ(),s=nZ(),o=s.defaultQueryOptions(e);(b=(g=s.getDefaultOptions().queries)==null?void 0:g._experimental_beforeQuery)==null||b.call(g,o);const a=s.getQueryCache().get(o.queryHash),l=e.subscribed!==!1;o._optimisticResults=r?"isRestoring":l?"optimistic":void 0,dZ(o),lZ(o,i,a),cZ(i);const u=!s.getQueryCache().get(o.queryHash),[f]=h.useState(()=>new t(s,o)),p=f.getOptimisticResult(o),m=!r&&l;if(h.useSyncExternalStore(h.useCallback(w=>{const C=m?f.subscribe(Rr.batchCalls(w)):hi;return f.updateResult(),C},[f,m]),()=>f.getCurrentResult(),()=>f.getCurrentResult()),h.useEffect(()=>{f.setOptions(o)},[o,f]),hZ(o,p))throw gS(o,f,i);if(uZ({result:p,errorResetBoundary:i,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw p.error;if((k=(x=s.getDefaultOptions().queries)==null?void 0:x._experimental_afterQuery)==null||k.call(x,o,p),o.experimental_prefetchInRender&&!ap.isServer()&&fZ(p,r)){const w=u?gS(o,f,i):a==null?void 0:a.promise;w==null||w.catch(hi).finally(()=>{f.updateResult()})}return o.notifyOnChangeProps?p:f.trackResult(p)}function mZ(e,t){return pZ(e,qU)}var me=typeof window<"u"?window:void 0,hr=typeof globalThis<"u"?globalThis:me;typeof self>"u"&&(hr.self=hr),typeof File>"u"&&(hr.File=function(){});var Ni=hr==null?void 0:hr.navigator,Ze=hr==null?void 0:hr.document,Pr=hr==null?void 0:hr.location,jw=hr==null?void 0:hr.fetch,Fw=hr!=null&&hr.XMLHttpRequest&&"withCredentials"in new hr.XMLHttpRequest?hr.XMLHttpRequest:void 0,vS=hr==null?void 0:hr.AbortController,gZ=hr==null?void 0:hr.CompressionStream,ui=Ni==null?void 0:Ni.userAgent,gt=me??{},yS="1.379.2",wr={DEBUG:!1,LIB_VERSION:yS,LIB_NAME:"web",JS_SDK_VERSION:yS};function bS(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(u){return void n(u)}a.done?t(l):Promise.resolve(l).then(r,i)}function $i(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var s=e.apply(t,n);function o(l){bS(s,r,i,o,a,"next",l)}function a(l){bS(s,r,i,o,a,"throw",l)}o(void 0)}))}}function Oe(){return Oe=Object.assign?Object.assign.bind():function(e){for(var t=1;arguments.length>t;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Oe.apply(null,arguments)}function dM(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var eh,xS=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),vZ=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],fM="NativeGzipValidationError",Ow=e=>e.length>=2&&e[0]===31&&e[1]===139,wS=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",wm=e=>{var t=new Error("Native gzip produced invalid output: "+e);throw t.name=fM,t},yZ=(function(){var e=$i((function*(t,n){18>t.size&&wm("too-short");var r=new Uint8Array(yield t.slice(0,10).arrayBuffer());Ow(r)&&r[2]===8||wm("invalid-header");var i=new DataView(yield t.slice(t.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(eh)return eh;eh=[];for(var f=0;256>f;f++){for(var p=f,m=0;8>m;m++)p=1&p?3988292384^p>>>1:p>>>1;eh[f]=p>>>0}return eh})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(n)&&wm("invalid-crc");var s=n.length>>>0;i.getUint32(4,!0)!==s&&wm("invalid-size")}));return function(t,n){return e.apply(this,arguments)}})();function Vw(){return Vw=$i((function*(e,t,n){t===void 0&&(t=!0);try{var r=new TextEncoder().encode(e),i=new CompressionStream("gzip"),s=i.writable.getWriter(),o=s.write(r).then((()=>s.close())).catch((function(){var u=$i((function*(f){try{yield s.abort(f)}catch{}throw f}));return function(f){return u.apply(this,arguments)}})()),a=new Response(i.readable).blob(),[l]=yield Promise.all([a,o]);return yield yZ(l,r),l}catch(u){if(n!=null&&n.rethrow)throw u;return t&&console.error("Failed to gzip compress data",u),null}})),Vw.apply(this,arguments)}var bZ=["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"],_S=function(e,t){if(t===void 0&&(t=[]),!e)return!1;var n=e.toLowerCase();return bZ.concat(t).some((r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1}))};function At(e,t){return e.indexOf(t)!==-1}var bv=function(e){return e.trim()},Hw=function(e){return e.replace(/^\$/,"")},hM=Object.prototype,pM=hM.hasOwnProperty,xv=hM.toString,sn=Array.isArray||function(e){return xv.call(e)==="[object Array]"},zo=e=>typeof e=="function",Yn=e=>e===Object(e)&&!sn(e),Ku=e=>{if(Yn(e)){for(var t in e)if(pM.call(e,t))return!1;return!0}return!1},We=e=>e===void 0,Nn=e=>xv.call(e)=="[object String]",Bw=e=>Nn(e)&&e.trim().length===0,es=e=>e===null,Kt=e=>We(e)||es(e),Hi=e=>xv.call(e)=="[object Number]"&&e==e,Fo=e=>Hi(e)&&e>0,oo=e=>xv.call(e)==="[object Boolean]",xZ=e=>e instanceof FormData,wZ=e=>At(vZ,e);function mM(e){return e===null||typeof e!="object"}function Kg(e,t){return{}.toString.call(e)==="[object "+t+"]"}function B8(e){return typeof Event<"u"&&(function(t,n){try{return t instanceof n}catch{return!1}})(e,Event)}var _Z=[!0,"true",1,"1","yes"],pb=e=>At(_Z,e),kZ=[!1,"false",0,"0","no"];function ao(e,t,n,r,i){return t>n&&(r.warn("min cannot be greater than max."),t=n),Hi(e)?e>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t>e?(r.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),ao(i||n,t,n,r))}class CZ{constructor(t){this.$t={},this.zt=t.zt,this.Zt=ao(t.bucketSize,0,100,t.Gt),this.Qt=ao(t.refillRate,0,this.Zt,t.Gt),this.Jt=ao(t.refillInterval,0,864e5,t.Gt)}Kt(t,n){var r=Math.floor((n-t.lastAccess)/this.Jt);r>0&&(t.tokens=Math.min(t.tokens+r*this.Qt,this.Zt),t.lastAccess=t.lastAccess+r*this.Jt)}consumeRateLimit(t){var n,r=Date.now(),i=String(t),s=this.$t[i];return s?this.Kt(s,r):this.$t[i]=s={tokens:this.Zt,lastAccess:r},s.tokens===0||(s.tokens--,s.tokens===0&&((n=this.zt)==null||n.call(this,t)),s.tokens===0)}stop(){this.$t={}}}var _m,kS,mb,Li="Mobile",Yg="iOS",Ko="Android",Md="Tablet",gM=Ko+" "+Md,vM="iPad",yM="Apple",bM=yM+" Watch",Bh="Safari",$d="BlackBerry",xM="Samsung",wM=xM+"Browser",_M=xM+" Internet",wc="Chrome",EZ=wc+" OS",kM=wc+" "+Yg,z8="Internet Explorer",CM=z8+" "+Li,U8="Opera",SZ=U8+" Mini",Z8="Edge",EM="Microsoft "+Z8,cd="Firefox",SM=cd+" "+Yg,lp="Nintendo",cp="PlayStation",ud="Xbox",AM=Ko+" "+Li,TM=Li+" "+Bh,Eh="Windows",zw=Eh+" Phone",CS="Nokia",Uw="Ouya",PM="Generic",AZ=PM+" "+Li.toLowerCase(),IM=PM+" "+Md.toLowerCase(),Zw="Konqueror",RM="Oculus Browser",Xg="Vivaldi",MM="Yandex",Qg="Whale",Ww="DuckDuckGo",$M="Pale Moon",Jg="Waterfox",zh="Brave",Hn="(\\d+(\\.\\d+)?)",gb=new RegExp("Version/"+Hn),TZ=new RegExp(ud,"i"),PZ=new RegExp(cp+" \\w+","i"),IZ=new RegExp(lp+" \\w+","i"),W8=new RegExp($d+"|PlayBook|BB10","i"),RZ={"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"},DM=function(e,t,n){t=t||"";var r=(function(i){return i!=null&&i.brave?zh:null})(n);return r||(At(e," OPR/")&&At(e,"Mini")?SZ:At(e," OPR/")?U8:W8.test(e)?$d:At(e,"IE"+Li)||At(e,"WPDesktop")?CM:At(e,"OculusBrowser")?RM:At(e,wM)?_M:At(e,Z8)||At(e,"Edg/")?EM:At(e,Xg+"/")?Xg:At(e,"YaBrowser/")?MM:At(e,Qg+"/")?Qg:At(e,Ww+"/")||At(e,"Ddg/")?Ww:At(e,"FBIOS")?"Facebook "+Li:At(e,"UCWEB")||At(e,"UCBrowser")?"UC Browser":At(e,"CriOS")?kM:At(e,"CrMo")||At(e,wc)?wc:At(e,Ko)&&At(e,Bh)?AM:At(e,"FxiOS")?SM:At(e.toLowerCase(),Zw.toLowerCase())?Zw:At(e,zh+"/")?zh:((i,s)=>s&&At(s,yM)||(function(o){return At(o,Bh)&&!At(o,wc)&&!At(o,Ko)})(i))(e,t)?At(e,Li)?TM:Bh:At(e,"PaleMoon/")?$M:At(e,Jg+"/")?Jg:At(e,cd)?cd:At(e,"MSIE")||At(e,"Trident/")?z8:At(e,"Gecko")?cd:"")},MZ={[CM]:[new RegExp("rv:"+Hn)],[EM]:[new RegExp(Z8+"?\\/"+Hn)],[wc]:[new RegExp("("+wc+"|CrMo)\\/"+Hn)],[kM]:[new RegExp("CriOS\\/"+Hn)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Hn)],[Bh]:[gb],[TM]:[gb],[U8]:[new RegExp("(Opera|OPR)\\/"+Hn)],[cd]:[new RegExp(cd+"\\/"+Hn)],[SM]:[new RegExp("FxiOS\\/"+Hn)],[Zw]:[new RegExp("Konqueror[:/]?"+Hn,"i")],[$d]:[new RegExp($d+" "+Hn),gb],[AM]:[new RegExp("android\\s"+Hn,"i")],[_M]:[new RegExp(wM+"\\/"+Hn)],[RM]:[new RegExp("OculusBrowser\\/"+Hn)],[Xg]:[new RegExp(Xg+"\\/"+Hn)],[MM]:[new RegExp("YaBrowser\\/"+Hn)],[Qg]:[new RegExp(Qg+"\\/"+Hn)],[zh]:[new RegExp(zh+"\\/"+Hn)],[Ww]:[new RegExp("(DuckDuckGo|Ddg)\\/"+Hn)],[$M]:[new RegExp("PaleMoon\\/"+Hn)],[Jg]:[new RegExp(Jg+"\\/"+Hn)],[z8]:[new RegExp("(rv:|MSIE )"+Hn)],Mozilla:[new RegExp("rv:"+Hn)]},$Z=function(e,t,n){var r=DM(e,t,n),i=MZ[r];if(We(i))return null;for(var s=0;i.length>s;s++){var o=e.match(i[s]);if(o)return parseFloat(o[o.length-2])}return null},ES=[[new RegExp(ud+"; "+ud+" (.*?)[);]","i"),e=>[ud,e&&e[1]||""]],[new RegExp(lp,"i"),[lp,""]],[new RegExp(cp,"i"),[cp,""]],[W8,[$d,""]],[new RegExp(Eh,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[zw,""];if(new RegExp(Li).test(t)&&!/IEMobile\b/.test(t))return[Eh+" "+Li,""];var n=/Windows NT ([0-9.]+)/i.exec(t);if(n&&n[1]){var r=RZ[n[1]]||"";return/arm/i.test(t)&&(r="RT"),[Eh,r]}return[Eh,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?[Yg,[e[3],e[4],e[5]||"0"].join(".")]:[Yg,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{var t="";return e&&e.length>=3&&(t=We(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("("+Ko+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ko+")","i"),e=>e&&e[2]?[Ko,[e[2],e[3],e[4]||"0"].join(".")]:[Ko,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{var t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[EZ,""]],[/Linux|debian/i,["Linux",""]]],SS=function(e){return IZ.test(e)?lp:PZ.test(e)?cp:TZ.test(e)?ud:new RegExp(Uw,"i").test(e)?Uw:new RegExp("("+zw+"|WPDesktop)","i").test(e)?zw:/iPad/.test(e)?vM:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?bM:W8.test(e)?$d:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(CS,"i").test(e)?CS:/(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(Li).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)?Ko:gM:new RegExp("(pda|"+Li+")","i").test(e)?AZ:new RegExp(Md,"i").test(e)&&!new RegExp(Md+" pc","i").test(e)?IM:""},DZ=e=>e instanceof Error,NM={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},NZ=NM.info;function LM(e){if(oo(e))return{boolValue:e};if(typeof e=="number")return Number.isFinite(e)?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:{stringValue:String(e)};if(typeof e=="string")return{stringValue:e};if(sn(e))return{arrayValue:{values:e.map((t=>LM(t)))}};try{return{stringValue:JSON.stringify(e)}}catch{return{stringValue:String(e)}}}function AS(e){var t=[];for(var n in e){var r=e[n];es(r)||We(r)||t.push({key:n,value:LM(r)})}return t}function LZ(e){var t=globalThis._posthogChunkIds;if(t){var n=Object.keys(t);return mb&&n.length===kS||(kS=n.length,mb=n.reduce(((r,i)=>{_m||(_m={});var s=_m[i];if(s)r[s[0]]=s[1];else for(var o=e(i),a=o.length-1;a>=0;a--){var l=o[a],u=l==null?void 0:l.filename,f=t[i];if(u&&f){r[u]=f,_m[i]=[u,f];break}}return r}),{})),mb}}class jZ{constructor(t,n,r){r===void 0&&(r=[]),this.coercers=t,this.stackParser=n,this.modifiers=r}buildFromUnknown(t,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(t),s=this.buildParsingContext(n),o=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(t){var n=this;return $i((function*(){for(var r of t)r.stacktrace&&r.stacktrace.frames&&sn(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,i;return t.cause!=null&&(r=this.parseStacktrace(t.cause,n)),t.stack!=""&&t.stack!=null&&(i=this.applyChunkIds(this.stackParser(t.stack,t.synthetic?n.skipFirstLines:0),n.chunkIdMap)),Oe({},t,{cause:r,stack:i})}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 $i((function*(){var r=t;for(var i of n.modifiers)r=yield i(r);return r}))()}convertToExceptionList(t,n){var r,i,s,o={type:t.type,value:t.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(s=t.synthetic)!==null&&s!==void 0&&s}};t.stack&&(o.stacktrace={type:"raw",frames:t.stack});var a=[o];return t.cause!=null&&a.push(...this.convertToExceptionList(t.cause,Oe({},n,{handled:!0}))),a}buildParsingContext(t){var n;return{chunkIdMap:LZ(this.stackParser),skipFirstLines:(n=t.skipFirstLines)!==null&&n!==void 0?n:1}}buildCoercingContext(t,n,r){r===void 0&&(r=0);var i=(s,o)=>{if(4>=o){var a=this.buildCoercingContext(t,n,o);return this.applyCoercers(s,a)}};return Oe({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:t,apply:s=>i(s,r),next:s=>i(s,r+1)})}}var Dd="?";function Gw(e,t,n,r,i){var s={platform:e,filename:t,function:n==="<anonymous>"?Dd:n,in_app:!0};return We(r)||(s.lineno=r),We(i)||(s.colno=i),s}var jM=(e,t)=>{var n=e.indexOf("safari-extension")!==-1,r=e.indexOf("safari-web-extension")!==-1;return n||r?[e.indexOf("@")!==-1?e.split("@")[0]:Dd,n?"safari-extension:"+t:"safari-web-extension:"+t]:[e,t]},FZ=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,OZ=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,VZ=/\((\S*)(?::(\d+))(?::(\d+))\)/,HZ=(e,t)=>{var n=FZ.exec(e);if(n){var[,r,i,s]=n;return Gw(t,r,Dd,+i,+s)}var o=OZ.exec(e);if(o){if(o[2]&&o[2].indexOf("eval")===0){var a=VZ.exec(o[2]);a&&(o[2]=a[1],o[3]=a[2],o[4]=a[3])}var[l,u]=jM(o[1]||Dd,o[2]);return Gw(t,u,l,o[3]?+o[3]:void 0,o[4]?+o[4]:void 0)}},BZ=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,zZ=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,UZ=(e,t)=>{var n=BZ.exec(e);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=zZ.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],s=n[1]||Dd;return[s,i]=jM(s,i),Gw(t,i,s,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},TS=/\(error: (.*)\)/;class ZZ{match(t){return this.isDOMException(t)||this.isDOMError(t)}coerce(t,n){var r=Nn(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 Kg(t,"DOMException")}isDOMError(t){return Kg(t,"DOMError")}}class WZ{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 String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(t){return t.stacktrace||t.stack||void 0}}class GZ{constructor(){}match(t){return Kg(t,"ErrorEvent")&&t.error!=null}coerce(t,n){var r;return n.apply(t.error)||{type:"ErrorEvent",value:t.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}var qZ=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class KZ{match(t){return typeof t=="string"}coerce(t,n){var r,[i,s]=this.getInfos(t);return{type:i??"Error",value:s??t,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(t){var n="Error",r=t,i=t.match(qZ);return i&&(n=i[1],r=i[2]),[n,r]}}var YZ=["fatal","error","warning","log","info","debug"];function FM(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 i=n.slice(0,r).join(", ");if(t>=i.length)return r===n.length?i:i.length>t?i.slice(0,t)+"...":i}return""}class XZ{match(t){return typeof t=="object"&&t!==null}coerce(t,n){var r,i=this.getErrorPropertyFromObject(t);return i?n.apply(i):{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 B8(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: "+FM(t)}isSeverityLevel(t){return Nn(t)&&!Bw(t)&&YZ.indexOf(t)>=0}getErrorPropertyFromObject(t){for(var n in t)if({}.hasOwnProperty.call(t,n)){var r=t[n];if(DZ(r))return r}}getObjectClassName(t){try{var n=Object.getPrototypeOf(t);return n?n.constructor.name:void 0}catch{return}}}class QZ{match(t){return B8(t)}coerce(t,n){var r,i=t.constructor.name;return{type:i,value:i+" captured as exception with keys: "+FM(t),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class JZ{match(t){return mM(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}}}class eW{match(t){return Kg(t,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(t)}isCustomEventWrappingRejection(t){if(!B8(t))return!1;try{var n=t.detail;return n!=null&&typeof n=="object"&&"reason"in n}catch{return!1}}coerce(t,n){var r,i=this.getUnhandledRejectionReason(t);return mM(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(t){try{if("reason"in t)return t.reason;if("detail"in t&&t.detail!=null&&typeof t.detail=="object"&&"reason"in t.detail)return t.detail.reason}catch{}return t}}var e1="$message",t1="$timestamp",tW=new Set([e1,t1]),vb={enabled:!0,max_bytes:32768};function n1(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:vb.enabled,max_bytes:rW(e.max_bytes,vb.max_bytes)}:Oe({},vb)}class nW{constructor(t){this.Yt=[],this.Xt=0,this.qt=n1(t)}setConfig(t){this.qt=n1(t),this.er()}add(t){var n=(function(i){var s=(function(f){var p=new WeakSet;try{return JSON.stringify(f,((m,g)=>{if(typeof g=="bigint")return g.toString();if(typeof g!="function"&&typeof g!="symbol"){if(g instanceof Date)return g.toISOString();if(g instanceof Error)return{name:g.name,message:g.message,stack:g.stack};if(g&&typeof g=="object"){if(p.has(g))return"[Circular]";p.add(g)}return g}}))}catch{return}})(i);if(s)try{var o=JSON.parse(s);if(!Yn(o))return;var a=o,l=a[e1],u=a[t1];return!Nn(l)||l.trim().length===0||!Nn(u)&&!Hi(u)?void 0:{step:a,json:s}}catch{return}})(t);if(n){var r=(function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var s=encodeURIComponent(i),o=0,a=0;s.length>a;a++)s[a]==="%"?(o+=1,a+=2):o+=1;return o})(n.json);r>this.qt.max_bytes||(this.Yt.push({step:n.step,bytes:r}),this.Xt+=r,this.er())}}getAttachable(){return this.Yt.map((t=>t.step))}clear(){this.Yt=[],this.Xt=0}size(){return this.Yt.length}er(){for(;this.Xt>this.qt.max_bytes&&this.Yt.length>0;){var t=this.Yt.shift();t&&(this.Xt-=t.bytes)}}}function rW(e,t){if(!Hi(e)||e===1/0||e===-1/0)return t;var n=Math.floor(e);return 0>n?t:n}var OM=function(e,t){var{debugEnabled:n}=t===void 0?{}:t,r={k(i){if(me&&(wr.DEBUG||gt.POSTHOG_DEBUG||n)&&!We(me.console)&&me.console){for(var s=("__rrweb_original__"in me.console[i])?me.console[i].__rrweb_original__:me.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];s(e,...a)}},debug(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("debug",...s)},info(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("log",...s)},warn(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("warn",...s)},error(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];r.k("error",...s)},critical(){for(var i=arguments.length,s=new Array(i),o=0;i>o;o++)s[o]=arguments[o];console.error(e,...s)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,s)=>OM(e+" "+i,s)};return r},Ue=OM("[PostHog.js]"),Ln=Ue.createLogger,iW=Ln("[ExternalScriptsLoader]"),yb=(e,t,n)=>{if(e.config.disable_external_dependency_loading)return iW.warn(t+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=Ze==null?void 0:Ze.querySelectorAll("script");if(r){for(var i,s=function(){if(r[o].src===t){var l=r[o];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(u=>{l.__posthog_loading_callback_fired=!0,n(void 0,u)})),l.onerror=u=>n(u),{v:void 0})}},o=0;r.length>o;o++)if(i=s())return i.v}var a=()=>{if(!Ze)return n("document not found");var l=Ze.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=t,l.onload=p=>{l.__posthog_loading_callback_fired=!0,n(void 0,p)},l.onerror=p=>n(p),e.config.prepare_external_dependency_script&&(l=e.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")Ze.head.appendChild(l);else{var u,f=Ze.querySelectorAll("body > script");f.length>0?(u=f[0].parentNode)==null||u.insertBefore(l,f[0]):Ze.body.appendChild(l)}};Ze!=null&&Ze.body?a():Ze==null||Ze.addEventListener("DOMContentLoaded",a)};gt.__PosthogExtensions__=gt.__PosthogExtensions__||{},gt.__PosthogExtensions__.loadExternalDependency=(e,t,n)=>{if(t!=="remote-config"){var r;if(e.config.__preview_external_dependency_versioned_paths)r=e.requestRouter.endpointFor("assets","/static/"+e.version+"/"+t+".js");else{var i="/static/"+t+".js?v="+e.version;if(t==="toolbar"){var s=3e5;i=i+"&t="+Math.floor(Date.now()/s)*s}r=e.requestRouter.endpointFor("assets",i)}yb(e,r,n)}else{var o=e.requestRouter.endpointFor("assets","/array/"+e.config.token+"/config.js");yb(e,o,n)}},gt.__PosthogExtensions__.loadSiteApp=(e,t,n)=>{var r=e.requestRouter.endpointFor("api",t);yb(e,r,n)};var VM="$people_distinct_id",r1="$device_id",Sh="__alias",Ah="__timers",qw="$autocapture_disabled_server_side",Kw="$heatmaps_enabled_server_side",Yw="$exception_capture_enabled_server_side",Xw="$error_tracking_suppression_rules",Qw="$error_tracking_capture_extension_exceptions",Jw="$web_vitals_enabled_server_side",G8="$dead_clicks_enabled_server_side",e4="$product_tours_enabled_server_side",t4="$web_vitals_allowed_metrics",lc="$session_recording_remote_config",HM="$replay_override_sampling",BM="$replay_override_linked_flag",zM="$replay_override_url_trigger",UM="$replay_override_event_trigger",Yu="$sesid",q8="$session_is_sampled",Xu="$enabled_feature_flags",bg="$active_feature_flags",Th="$early_access_features",n4="$feature_flag_details",r4="$feature_flag_payloads",i4="$feature_flag_request_id",Oo="$override_feature_flags",zu="$override_feature_flag_payloads",Ph="$stored_person_properties",nc="$stored_group_properties",s4="$surveys",o4="$surveys_activated",xg="ph_product_tours",Uh="$flag_call_reported",a4="$flag_call_reported_session_id",l4="$feature_flag_errors",i1="$feature_flag_evaluated_at",xs="$user_state",c4="$client_session_props",u4="$capture_rate_limit",d4="$initial_campaign_params",f4="$initial_referrer_info",s1="$initial_person_info",o1="$epp",ZM="__POSTHOG_TOOLBAR__",km="$posthog_cookieless",WM="$sdk_debug_extensions_init_method",GM="$sdk_debug_extensions_init_time_ms",qM="$sdk_debug_recording_script_not_loaded",K8="PostHog loadExternalDependency extension not found.",rc="on_reject",Go="always",_u="anonymous",ku="identified",h4="identified_only",a1="visibilitychange",l1="beforeunload",Uu="$pageview",bb="$pageleave",xb="$identify",PS="$groupidentify";function Cm(e,t){sn(e)&&e.forEach(t)}function Rn(e,t){if(!Kt(e))if(sn(e))e.forEach(t);else if(xZ(e))e.forEach(((r,i)=>t(r,i)));else for(var n in e)pM.call(e,n)&&t(e[n],n)}var qn=function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;t>r;r++)n[r-1]=arguments[r];for(var i of n)for(var s in i)i[s]!==void 0&&(e[s]=i[s]);return e};function wg(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 IS=function(e){try{return e()}catch{return}},sW=function(e){return function(){try{for(var t=arguments.length,n=new Array(t),r=0;t>r;r++)n[r]=arguments[r];return e.apply(this,n)}catch(i){Ue.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ue.critical(i)}}},Y8=function(e){var t={};return Rn(e,(function(n,r){(Nn(n)&&n.length>0||Hi(n))&&(t[r]=n)})),t},oW=["herokuapp.com","vercel.app","netlify.app"];function aW(e){var t=e==null?void 0:e.hostname;if(!Nn(t))return!1;var n=t.split(".").slice(-2).join(".");for(var r of oW)if(n===r)return!1;return!0}function Wn(e,t,n,r){var{capture:i=!1,passive:s=!0}=r??{};e==null||e.addEventListener(t,n,{capture:i,passive:s})}function KM(e){return e.name==="ph_toolbar_internal"}Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return Hi(e)&&isFinite(e)&&Math.floor(e)===e});class c1{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,n,r,i){if(!Number.isInteger(t)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||0>t||0>n||0>r||0>i||t>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/Math.pow(2,8),s[5]=t,s[6]=112|n>>>8,s[7]=n,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new c1(s)}toString(){for(var t="",n=0;this.bytes.length>n;n++)t=t+(this.bytes[n]>>>4).toString(16)+(15&this.bytes[n]).toString(16),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 c1(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(var n=0;16>n;n++){var r=this.bytes[n]-t.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class lW{constructor(){this.S=0,this.C=0,this.I=new cW}generate(){var t=this.generateOrAbort();if(We(t)){this.S=0;var n=this.generateOrAbort();if(We(n))throw new Error("Could not generate UUID after timestamp reset");return n}return t}generateOrAbort(){var t=Date.now();if(t>this.S)this.S=t,this.T();else{if(this.S>=t+1e4)return;this.C++,this.C>4398046511103&&(this.S++,this.T())}return c1.fromFieldsV7(this.S,Math.trunc(this.C/Math.pow(2,30)),this.C&Math.pow(2,30)-1,this.I.nextUint32())}T(){this.C=1024*this.I.nextUint32()+(1023&this.I.nextUint32())}}var RS,YM=e=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};me&&!We(me.crypto)&&crypto.getRandomValues&&(YM=e=>crypto.getRandomValues(e));class cW{constructor(){this.M=new Uint32Array(8),this.R=1/0}nextUint32(){return this.M.length>this.R||(YM(this.M),this.R=0),this.M[this.R++]}}var Ga=()=>uW().toString(),uW=()=>(RS||(RS=new lW)).generate(),th="",dW=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,io={O:()=>!!Ze,D(e){Ue.error("cookieStore error: "+e)},A(e){if(Ze){try{for(var t=e+"=",n=Ze.cookie.split(";").filter((s=>s.length)),r=0;n.length>r;r++){for(var i=n[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}},F(e){var t;try{t=JSON.parse(io.A(e))||{}}catch{}return t},N(e,t,n,r,i){if(Ze)try{var s="",o="",a=(function(f,p){if(p){var m=(function(b,x){if(x===void 0&&(x=Ze),th)return th;if(!x||["localhost","127.0.0.1"].includes(b))return"";for(var k=b.split("."),w=Math.min(k.length,8),C="dmn_chk_"+Ga();!th&&w--;){var E=k.slice(w).join("."),A=C+"=1;domain=."+E+";path=/";x.cookie=A+";max-age=3",x.cookie.includes(C)&&(x.cookie=A+";max-age=0",th=E)}return th})(f);if(!m){var g=(b=>{var x=b.match(dW);return x?x[0]:""})(f);g!==m&&Ue.info("Warning: cookie subdomain discovery mismatch",g,m),m=g}return m?"; domain=."+m:""}return""})(Ze.location.hostname,r);if(n){var l=new Date;l.setTime(l.getTime()+864e5*n),s="; expires="+l.toUTCString()}i&&(o="; secure");var u=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&Ue.warn("cookieStore warning: large cookie, len="+u.length),Ze.cookie=u,u}catch{return}},q(e,t){if(Ze!=null&&Ze.cookie)try{io.N(e,"",-1,t)}catch{return}}},wb=null,Bn={O(){if(!es(wb))return wb;var e=!0;if(We(me))e=!1;else try{var t="__mplssupport__";Bn.N(t,"xyz"),Bn.A(t)!=='"xyz"'&&(e=!1),Bn.q(t)}catch{e=!1}return e||Ue.error("localStorage unsupported; falling back to cookie store"),wb=e,e},D(e){Ue.error("localStorage error: "+e)},A(e){try{return me==null?void 0:me.localStorage.getItem(e)}catch(t){Bn.D(t)}return null},F(e){try{return JSON.parse(Bn.A(e))||{}}catch{}return null},N(e,t){try{me==null||me.localStorage.setItem(e,JSON.stringify(t))}catch(n){Bn.D(n)}},q(e){try{me==null||me.localStorage.removeItem(e)}catch(t){Bn.D(t)}}},fW=[r1,"distinct_id",Yu,q8,o1,s1,xs],Em={},hW={O:()=>!0,D(e){Ue.error("memoryStorage error: "+e)},A:e=>Em[e]||null,F:e=>Em[e]||null,N(e,t){Em[e]=t},q(e){delete Em[e]}},Wl=null,Ir={O(){if(!es(Wl))return Wl;if(Wl=!0,We(me))Wl=!1;else try{var e="__support__";Ir.N(e,"xyz"),Ir.A(e)!=='"xyz"'&&(Wl=!1),Ir.q(e)}catch{Wl=!1}return Wl},D(e){Ue.error("sessionStorage error: ",e)},A(e){try{return me==null?void 0:me.sessionStorage.getItem(e)}catch(t){Ir.D(t)}return null},F(e){try{return JSON.parse(Ir.A(e))||null}catch{}return null},N(e,t){try{me==null||me.sessionStorage.setItem(e,JSON.stringify(t))}catch(n){Ir.D(n)}},q(e){try{me==null||me.sessionStorage.removeItem(e)}catch(t){Ir.D(t)}}};class pW{constructor(t){this._instance=t}get qt(){return this._instance.config}get consent(){return this.rr()?0:this.ir}isOptedOut(){return this.qt.cookieless_mode===Go||this.isRejected()||this.consent===-1&&this.qt.cookieless_mode===rc}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.qt.opt_out_capturing_by_default}optInOut(t){this.nr.N(this.sr,t?1:0,this.qt.cookie_expiration,this.qt.cross_subdomain_cookie,this.qt.secure_cookie)}reset(){this.nr.q(this.sr,this.qt.cross_subdomain_cookie)}get sr(){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 ir(){var t=this.nr.A(this.sr);return pb(t)?1:At(kZ,t)?0:-1}get nr(){var t=this.qt.opt_out_capturing_persistence_type,n=t==="localStorage"?Bn:io;if(!this.ar||this.ar!==n){this.ar=n;var r=t==="localStorage"?io:Bn;r.A(this.sr)&&(this.ar.A(this.sr)||this.optInOut(pb(r.A(this.sr))),r.q(this.sr,this.qt.cross_subdomain_cookie))}return this.ar}rr(){return!!this.qt.respect_dnt&&[Ni==null?void 0:Ni.doNotTrack,Ni==null?void 0:Ni.msDoNotTrack,gt.doNotTrack].some((t=>pb(t)))}}var Sm=Ln("[Dead Clicks]"),mW=()=>!0,gW=e=>{var t,n=!((t=e.instance.persistence)==null||!t.get_property(G8)),r=e.instance.config.capture_dead_clicks;return oo(r)?r:!!Yn(r)||n};class MS{get lazyLoadedDeadClicksAutocapture(){return this.ur}constructor(t,n,r){this.instance=t,this.isEnabled=n,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(t){"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[G8]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.lr((()=>{this.hr()})):this.stop()}lr(t){var n,r;(n=gt.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&t(),(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(i=>{i?Sm.error("failed to load script",i):t()}))}hr(){var t;if(Ze){if(!this.ur&&(t=gt.__PosthogExtensions__)!=null&&t.initDeadClicksAutocapture){var n=Yn(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.ur=gt.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.ur.start(Ze),Sm.info("starting...")}}else Sm.error("`document` not found. Cannot start.")}stop(){this.ur&&(this.ur.stop(),this.ur=void 0,Sm.info("stopping..."))}}var _b=Ln("[SegmentIntegration]"),XM="posthog-js";function QM(e,t){var{organization:n,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:o=!0}=t===void 0?{}:t;return a=>{var l,u,f,p,m;if(s!=="*"&&!s.includes(a.level)||!e.__loaded)return a;a.tags||(a.tags={});var g=e.requestRouter.endpointFor("ui","/project/"+e.config.token+"/person/"+e.get_distinct_id());a.tags["PostHog Person URL"]=g,e.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var b,x=((l=a.exception)==null?void 0:l.values)||[],k=x.map((C=>Oe({},C,{stacktrace:C.stacktrace?Oe({},C.stacktrace,{type:"raw",frames:(C.stacktrace.frames||[]).map((E=>Oe({},E,{platform:"web:javascript"})))}):void 0}))),w={$exception_message:((u=x[0])==null?void 0:u.value)||a.message,$exception_type:(f=x[0])==null?void 0:f.type,$exception_level:a.level,$exception_list:k,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((p=x[0])==null?void 0:p.value)||a.message,$sentry_exception_type:(m=x[0])==null?void 0:m.type,$sentry_tags:a.tags};return n&&r&&(w.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+a.event_id),o&&((b=e.exceptions)==null||b.sendExceptionEvent(w)),a}}class vW{constructor(t,n,r,i,s,o){this.name=XM,this.setupOnce=function(a){a(QM(t,{organization:n,projectId:r,prefix:i,severityAllowList:s,sendExceptionsToPostHog:o==null||o}))}}}class $S{constructor(t){this.cr=(n,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength)&&(Ue.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:n,changeReason:i}),this.dr=void 0,this._instance.scrollManager.resetContext())},this._instance=t,this.vr()}vr(){var t;this.pr=(t=this._instance.sessionManager)==null?void 0:t.onSessionId(this.cr)}destroy(){var t;(t=this.pr)==null||t.call(this),this.pr=void 0}doPageView(t,n){var r,i=this.gr(t,n);return this.dr={pathname:(r=me==null?void 0:me.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:t},this._instance.scrollManager.resetContext(),i}doPageLeave(t){var n;return this.gr(t,(n=this.dr)==null?void 0:n.pageViewId)}doEvent(){var t;return{$pageview_id:(t=this.dr)==null?void 0:t.pageViewId}}gr(t,n){var r=this.dr;if(!r)return{$pageview_id:n};var i={$pageview_id:n,$prev_pageview_id:r.pageViewId},s=this._instance.scrollManager.getContext();if(s&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:o,lastScrollY:a,maxScrollY:l,maxContentHeight:u,lastContentY:f,maxContentY:p}=s;if(!(We(o)||We(a)||We(l)||We(u)||We(f)||We(p))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),f=Math.ceil(f),p=Math.ceil(p);var m=o>1?ao(a/o,0,1,Ue):1,g=o>1?ao(l/o,0,1,Ue):1,b=u>1?ao(f/u,0,1,Ue):1,x=u>1?ao(p/u,0,1,Ue):1;i=qn(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:m,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:g,$prev_pageview_last_content:f,$prev_pageview_last_content_percentage:b,$prev_pageview_max_content:p,$prev_pageview_max_content_percentage:x})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(t.getTime()-r.timestamp.getTime())/1e3),i}}var yW={[VM]:{exposure:"hidden"},[Sh]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ah]:{exposure:"hidden"},[qw]:{exposure:"event"},[Kw]:{exposure:"hidden"},[Yw]:{exposure:"event"},[Xw]:{exposure:"hidden"},[Qw]:{exposure:"event"},[Jw]:{exposure:"event"},[G8]:{exposure:"event"},[e4]:{exposure:"hidden"},[t4]:{exposure:"event"},[lc]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Yu]:{exposure:"hidden"},[q8]:{exposure:"event"},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},[Xu]:{exposure:"derived",shouldSkipFromEventProperties:(e,t)=>t(),transformToEventProperties(e){if(!Yn(e))return{};for(var t={},n=Object.keys(e),r=0;n.length>r;r++)t["$feature/"+n[r]]=e[n[r]];return t}},[bg]:{exposure:"event"},[Th]:{exposure:"hidden"},[n4]:{exposure:"hidden"},[r4]:{exposure:"event"},[i4]:{exposure:"event"},[Oo]:{exposure:"event"},[zu]:{exposure:"hidden"},[Ph]:{exposure:"hidden"},[nc]:{exposure:"hidden"},[s4]:{exposure:"hidden"},[o4]:{exposure:"event"},[xg]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Uh]:{exposure:"hidden"},[a4]:{exposure:"hidden"},[l4]:{exposure:"hidden"},[i1]:{exposure:"hidden"},[xs]:{exposure:"hidden"},[c4]:{exposure:"hidden"},[u4]:{exposure:"hidden"},[d4]:{exposure:"hidden"},[f4]:{exposure:"hidden"},[s1]:{exposure:"hidden"},[o1]:{exposure:"hidden"},[HM]:{exposure:"event"},[BM]:{exposure:"event"},[zM]:{exposure:"event"},[UM]:{exposure:"event"},[WM]:{exposure:"event"},[GM]:{exposure:"event"},[qM]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},bW=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],u1=e=>{var t=Ze==null?void 0:Ze.createElement("a");return We(t)?null:(t.href=e,t)},up=function(e,t){for(var n,r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var s=r[i].split("=");if(s[0]===t){n=s;break}}if(!sn(n)||2>n.length)return"";var o=n[1];try{o=decodeURIComponent(o)}catch{Ue.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},dp=function(e,t,n){if(!e||!t||!t.length)return e;for(var r=e.split("#"),i=r[1],s=(r[0]||"").split("?"),o=s[1],a=s[0],l=(o||"").split("&"),u=[],f=0;l.length>f;f++){var p=l[f].split("=");sn(p)&&(t.includes(p[0])?u.push(p[0]+"="+n):u.push(l[f]))}var m=a;return o!=null&&(m+="?"+u.join("&")),i!=null&&(m+="#"+i),m},d1=function(e,t){var n=e.match(new RegExp(t+"=([^&]*)"));return n?n[1]:null},Am="https?://(.*)",Nd=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],xW=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Nd],fp="<masked>",wW=["li_fat_id"];function JM(e,t,n){if(!Ze)return{};var r,i=t?[...Nd,...n||[]]:[],s=e9(dp(Ze.URL,i,fp),e),o=(r={},Rn(wW,(function(a){var l=io.A(a);r[a]=l||null})),r);return qn(o,s)}function e9(e,t){var n=xW.concat(t||[]),r={};return Rn(n,(function(i){var s=up(e,i);r[i]=s||null})),r}function t9(e){var t=(function(s){return s?s.search(Am+"google.([^/?]*)")===0?"google":s.search(Am+"bing.com")===0?"bing":s.search(Am+"yahoo.com")===0?"yahoo":s.search(Am+"duckduckgo.com")===0?"duckduckgo":null:null})(e),n=t!="yahoo"?"q":"p",r={};if(!es(t)){r.$search_engine=t;var i=Ze?up(Ze.referrer,n):"";i.length&&(r.ph_keyword=i)}return r}function DS(){return navigator.language||navigator.userLanguage}var f1="$direct";function n9(){return(Ze==null?void 0:Ze.referrer)||f1}function r9(e,t){var n=e?[...Nd,...t||[]]:[],r=Pr==null?void 0:Pr.href.substring(0,1e3);return{r:n9().substring(0,1e3),u:r?dp(r,n,fp):void 0}}function i9(e){var t,{r:n,u:r}=e,i={$referrer:n,$referring_domain:n==null?void 0:n==f1?f1:(t=u1(n))==null?void 0:t.host};if(r){i.$current_url=r;var s=u1(r);i.$host=s==null?void 0:s.host,i.$pathname=s==null?void 0:s.pathname;var o=e9(r);qn(i,o)}if(n){var a=t9(n);qn(i,a)}return i}function s9(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function _W(){try{return new Date().getTimezoneOffset()}catch{return}}var kW=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class kb{constructor(t,n){if(this.qt=t,this.props={},this.mr=!1,this.yr=(i=>{var s="";return i.token&&(s=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+s+"_posthog"})(t),this.nr=this.br(t),this.load(),t.debug&&Ue.info("Persistence loaded",t.persistence,Oe({},this.props)),this.update_config(t,t,n),this.save(),me){var r=()=>this.flush();Wn(me,"beforeunload",r,{capture:!1}),Wn(me,"pagehide",r,{capture:!1})}}_r(){var t,n=(t=this.qt)==null?void 0:t.persistence_save_debounce_ms;return Hi(n)&&n>0?n:0}isDisabled(){return!!this.wr}br(t){kW.indexOf(t.persistence.toLowerCase())===-1&&(Ue.critical("Unknown persistence type "+t.persistence+"; falling back to localStorage+cookie"),t.persistence="localStorage+cookie");var n=(function(i){i===void 0&&(i=[]);var s=[...fW,...i];return Oe({},Bn,{F(o){try{var a={};try{a=io.F(o)||{}}catch{}var l=qn(a,JSON.parse(Bn.A(o)||"{}"));return Bn.N(o,l),l}catch{}return null},N(o,a,l,u,f,p){try{Bn.N(o,a,void 0,void 0,p);var m={};s.forEach((g=>{a[g]&&(m[g]=a[g])})),Object.keys(m).length&&io.N(o,m,l,u,f,p)}catch(g){Bn.D(g)}},q(o,a){try{me==null||me.localStorage.removeItem(o),io.q(o,a)}catch(l){Bn.D(l)}}})})(t.cookie_persisted_properties||[]),r=t.persistence.toLowerCase();return r==="localstorage"&&Bn.O()?Bn:r==="localstorage+cookie"&&n.O()?n:r==="sessionstorage"&&Ir.O()?Ir:r==="memory"?hW:r==="cookie"?io:n.O()?n:io}Sr(t){var n=t??this.qt.feature_flag_cache_ttl_ms;if(!n||0>=n)return!1;var r=this.props[i1];return!r||typeof r!="number"||Date.now()-r>n}properties(){var t={};return Rn(this.props,((n,r)=>{var i=(s=>{var o=yW[s];if(o)return o;for(var[a,l]of bW)if(s.indexOf(a)===0)return l})(r);if((i==null?void 0:i.exposure)==="derived"){if(i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(n,r===Xu?()=>this.Sr():()=>!1))return;i.transformToEventProperties&&qn(t,i.transformToEventProperties(n))}else i&&i.exposure!=="event"||(t[r]=n)})),t}load(){if(!this.wr){var t=this.nr.F(this.yr);t&&(this.props=qn({},t))}}refreshKey(t){if(!this.wr){var n=this.nr.F(this.yr);n&&t in n?this.kr(t,n[t]):this.Cr(t)}}save(){if(!this.wr){var t=this._r();t>0?We(this.Ir)&&(this.Ir=setTimeout((()=>{this.Ir=void 0,this.Tr()}),t)):this.Tr()}}flush(){We(this.Ir)||(clearTimeout(this.Ir),this.Ir=void 0,this.Tr())}Tr(){if(!this.wr){try{var t=JSON.stringify(this.props)+"|"+this.Er+"|"+this.Mr+"|"+this.Rr;if(t===this.Pr)return;this.Pr=t}catch{}this.nr.N(this.yr,this.props,this.Er,this.Mr,this.Rr,this.qt.debug)}}remove(){We(this.Ir)||(clearTimeout(this.Ir),this.Ir=void 0),this.nr.q(this.yr,!1),this.nr.q(this.yr,!0),this.Pr=void 0}clear(){this.remove(),this.props={}}register_once(t,n,r){if(Yn(t)){We(n)&&(n="None"),this.Er=We(r)?this.Or:r;var i=!1;if(Rn(t,((s,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.kr(o,s),i=!0)})),i)return this.save(),!0}return!1}register(t,n){if(Yn(t)){this.Er=We(n)?this.Or:n;var r=!1;if(Rn(t,((i,s)=>{t.hasOwnProperty(s)&&this.props[s]!==i&&(this.kr(s,i),r=!0)})),r)return this.save(),!0}return!1}unregister(t){t in this.props&&(this.Cr(t),this.save())}update_campaign_params(){if(!this.mr){var t=JM(this.qt.custom_campaign_params,this.qt.mask_personal_data_properties,this.qt.custom_personal_data_properties);Ku(Y8(t))||this.register(t),this.mr=!0}}update_search_keyword(){var t;this.register((t=Ze==null?void 0:Ze.referrer)?t9(t):{})}update_referrer_info(){var t;this.register_once({$referrer:n9(),$referring_domain:Ze!=null&&Ze.referrer&&((t=u1(Ze.referrer))==null?void 0:t.host)||f1},void 0)}set_initial_person_info(){this.props[d4]||this.props[f4]||this.register_once({[s1]:r9(this.qt.mask_personal_data_properties,this.qt.custom_personal_data_properties)},void 0)}get_initial_props(){var t={};Rn([f4,d4],(o=>{var a=this.props[o];a&&Rn(a,(function(l,u){t["$initial_"+Hw(u)]=l}))}));var n,r,i=this.props[s1];if(i){var s=(n=i9(i),r={},Rn(n,(function(o,a){r["$initial_"+Hw(a)]=o})),r);qn(t,s)}return t}safe_merge(t){return Rn(this.props,(function(n,r){r in t||(t[r]=n)})),t}update_config(t,n,r){if(this.Or=this.Er=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||!((o,a)=>{if(o.length!==a.length)return!1;var l=[...o].sort(),u=[...a].sort();return l.every(((f,p)=>f===u[p]))})(t.cookie_persisted_properties||[],n.cookie_persisted_properties||[])){var i=this.br(t),s=this.props;this.clear(),this.nr=i,this.props=s,this.save()}}set_disabled(t){this.wr=t,this.wr?this.remove():this.save()}set_cross_subdomain(t){t!==this.Mr&&(this.Mr=t,this.remove(),this.save())}set_secure(t){t!==this.Rr&&(this.Rr=t,this.remove(),this.save())}set_event_timer(t,n){var r=this.props[Ah]||{};r[t]=n,this.kr(Ah,r),this.save()}remove_event_timer(t){var n=this.props[Ah]||{},r=n[t];return We(r)||(delete n[t],this.kr(Ah,n),this.save()),r}get_property(t){return this.props[t]}set_property(t,n){this.kr(t,n),this.save()}kr(t,n){this.props[t]=n}Cr(t){delete this.props[t]}}var nh={Activation:"events",Cancellation:"cancelEvents"},Cb={Popover:"popover",API:"api",Widget:"widget"},Ih={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},Eb={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},p4={Popover:"popover",Inline:"inline"},CW={SHOWN:"product tour shown"},NS={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},LS=Ln("[RateLimiter]");class EW{constructor(t){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=n=>{var r=n.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach((i=>{LS.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4}))}catch(i){return void LS.warn('could not rate limit - continuing. Error: "'+(i==null?void 0:i.message)+'"',{text:r})}},this.instance=t,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var t;return((t=this.instance.config.rate_limiting)==null?void 0:t.events_per_second)||10}get captureEventsBurstLimit(){var t;return Math.max(((t=this.instance.config.rate_limiting)==null?void 0:t.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(t){var n,r,i;t===void 0&&(t=!1);var{captureEventsBurstLimit:s,captureEventsPerSecond:o}=this,a=new Date().getTime(),l=(n=(r=this.instance.persistence)==null?void 0:r.get_property(u4))!==null&&n!==void 0?n:{tokens:s,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>s&&(l.tokens=s);var u=1>l.tokens;return u||t||(l.tokens=Math.max(0,l.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 "+o+" events per second and "+s+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(u4,l),{isRateLimited:u,remainingTokens:l.tokens}}isServerRateLimited(t){var n=this.serverLimits[t||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var rh=Ln("[RemoteConfig]");class o9{constructor(t){this._instance=t}get remoteConfig(){var t;return(t=gt._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.config}Lr(t){var n,r;(n=gt.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>t(this.remoteConfig))):t()}Fr(t){this._instance._send_request({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 rh.info("Using preloaded remote config",this.remoteConfig),this.Ar(this.remoteConfig),void this.Nr();if(this._instance.Dr())return void rh.warn("Remote config is disabled. Falling back to local config.");this.Lr((t=>{if(!t)return rh.info("No config found after loading remote JS config. Falling back to JSON."),void this.Fr((n=>{this.Ar(n),this.Nr()}));this.Ar(t),this.Nr()}))}catch(t){rh.error("Error loading remote config",t)}}stop(){this.$r&&(clearInterval(this.$r),this.$r=void 0)}refresh(){!this._instance.Dr()&&Ze&&Ze.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Nr(){var t;if(!this.$r){var n=(t=this._instance.config.remote_config_refresh_interval_ms)!==null&&t!==void 0?t:3e5;n!==0&&(this.$r=setInterval((()=>{this.refresh()}),n))}}Ar(t){var n;t||rh.error("Failed to fetch remote config from PostHog."),this._instance.Ar(t??{}),(t==null?void 0:t.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||(n=this._instance.featureFlags)==null||n.ensureFlagsLoaded())}}var no={GZipJS:"gzip-js",Base64:"base64"},ts=Uint8Array,vi=Uint16Array,Ld=Uint32Array,X8=new ts([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]),Q8=new ts([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]),jS=new ts([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a9=function(e,t){for(var n=new vi(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var i=new Ld(n[30]);for(r=1;30>r;++r)for(var s=n[r];n[r+1]>s;++s)i[s]=s-n[r]<<5|r;return[n,i]},l9=a9(X8,2),m4=l9[1];l9[0][28]=258,m4[258]=28;for(var FS=a9(Q8,0)[1],c9=new vi(32768),Mn=0;32768>Mn;++Mn){var Cu=(43690&Mn)>>>1|(21845&Mn)<<1;c9[Mn]=((65280&(Cu=(61680&(Cu=(52428&Cu)>>>2|(13107&Cu)<<2))>>>4|(3855&Cu)<<4))>>>8|(255&Cu)<<8)>>>1}var Zh=function(e,t,n){for(var r=e.length,i=0,s=new vi(t);r>i;++i)++s[e[i]-1];var o,a=new vi(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;for(o=new vi(r),i=0;r>i;++i)o[i]=c9[a[e[i]-1]++]>>>15-e[i];return o},Ic=new ts(288);for(Mn=0;144>Mn;++Mn)Ic[Mn]=8;for(Mn=144;256>Mn;++Mn)Ic[Mn]=9;for(Mn=256;280>Mn;++Mn)Ic[Mn]=7;for(Mn=280;288>Mn;++Mn)Ic[Mn]=8;var h1=new ts(32);for(Mn=0;32>Mn;++Mn)h1[Mn]=5;var SW=Zh(Ic,9),AW=Zh(h1,5),u9=function(e){return(e/8>>0)+(7&e&&1)},d9=function(e,t,n){(n==null||n>e.length)&&(n=e.length);var r=new(e instanceof vi?vi:e instanceof Ld?Ld:ts)(n-t);return r.set(e.subarray(t,n)),r},Mo=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8},ih=function(e,t,n){var r=t/8>>0;e[r]|=n<<=7&t,e[r+1]|=n>>>8,e[r+2]|=n>>>16},Sb=function(e,t){for(var n=[],r=0;e.length>r;++r)e[r]&&n.push({s:r,f:e[r]});var i=n.length,s=n.slice();if(!i)return[new ts(0),0];if(i==1){var o=new ts(n[0].s+1);return o[n[0].s]=1,[o,1]}n.sort((function(R,P){return R.f-P.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,f=1,p=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};f!=i-1;)a=n[n[p].f>n[u].f?u++:p++],l=n[u!=f&&n[p].f>n[u].f?u++:p++],n[f++]={s:-1,f:a.f+l.f,l:a,r:l};var m=s[0].s;for(r=1;i>r;++r)s[r].s>m&&(m=s[r].s);var g=new vi(m+1),b=g4(n[f-1],g,0);if(b>t){r=0;var x=0,k=b-t,w=1<<k;for(s.sort((function(R,P){return g[P.s]-g[R.s]||R.f-P.f}));i>r;++r){var C=s[r].s;if(t>=g[C])break;x+=w-(1<<b-g[C]),g[C]=t}for(x>>>=k;x>0;){var E=s[r].s;t>g[E]?x-=1<<t-g[E]++-1:++r}for(;r>=0&&x;--r){var A=s[r].s;g[A]==t&&(--g[A],++x)}b=t}return[new ts(g),b]},g4=function(e,t,n){return e.s==-1?Math.max(g4(e.l,t,n+1),g4(e.r,t,n+1)):t[e.s]=n},OS=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new vi(++t),r=0,i=e[0],s=1,o=function(l){n[r++]=l},a=1;t>=a;++a)if(e[a]==i&&a!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=e[a]}return[n.subarray(0,r),t]},sh=function(e,t){for(var n=0,r=0;t.length>r;++r)n+=e[r]*t[r];return n},v4=function(e,t,n){var r=n.length,i=u9(t+2);e[i]=255&r,e[i+1]=r>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;r>s;++s)e[i+s+4]=n[s];return 8*(i+4+r)},VS=function(e,t,n,r,i,s,o,a,l,u,f){Mo(t,f++,n),++i[256];for(var p=Sb(i,15),m=p[0],g=p[1],b=Sb(s,15),x=b[0],k=b[1],w=OS(m),C=w[0],E=w[1],A=OS(x),R=A[0],P=A[1],I=new vi(19),T=0;C.length>T;++T)I[31&C[T]]++;for(T=0;R.length>T;++T)I[31&R[T]]++;for(var L=Sb(I,7),M=L[0],D=L[1],O=19;O>4&&!M[jS[O-1]];--O);var F,Z,V,U,K=u+5<<3,W=sh(i,Ic)+sh(s,h1)+o,G=sh(i,m)+sh(s,x)+o+14+3*O+sh(I,M)+(2*I[16]+3*I[17]+7*I[18]);if(W>=K&&G>=K)return v4(t,f,e.subarray(l,l+u));if(Mo(t,f,1+(W>G)),f+=2,W>G){F=Zh(m,g),Z=m,V=Zh(x,k),U=x;var j=Zh(M,D);for(Mo(t,f,E-257),Mo(t,f+5,P-1),Mo(t,f+10,O-4),f+=14,T=0;O>T;++T)Mo(t,f+3*T,M[jS[T]]);f+=3*O;for(var H=[C,R],B=0;2>B;++B){var N=H[B];for(T=0;N.length>T;++T)Mo(t,f,j[q=31&N[T]]),f+=M[q],q>15&&(Mo(t,f,N[T]>>>5&127),f+=N[T]>>>12)}}else F=SW,Z=Ic,V=AW,U=h1;for(T=0;a>T;++T)if(r[T]>255){var q;ih(t,f,F[257+(q=r[T]>>>18&31)]),f+=Z[q+257],q>7&&(Mo(t,f,r[T]>>>23&31),f+=X8[q]);var X=31&r[T];ih(t,f,V[X]),f+=U[X],X>3&&(ih(t,f,r[T]>>>5&8191),f+=Q8[X])}else ih(t,f,F[r[T]]),f+=Z[r[T]];return ih(t,f,F[256]),f+Z[256]},TW=new Ld([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),PW=(function(){for(var e=new Ld(256),t=0;256>t;++t){for(var n=t,r=9;--r;)n=(1&n&&3988292384)^n>>>1;e[t]=n}return e})(),Ab=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function IW(e,t){t===void 0&&(t={});var n=(function(){var p=4294967295;return{p(m){for(var g=p,b=0;m.length>b;++b)g=PW[255&g^m[b]]^g>>>8;p=g},d(){return 4294967295^p}}})(),r=e.length;n.p(e);var i,s,o,a,l,u=(a=10+((i=t).filename&&i.filename.length+1||0),l=8,(function(p,m,g,b,x,k){var w=p.length,C=new ts(b+w+5*(1+Math.floor(w/7e3))+x),E=C.subarray(b,C.length-x),A=0;if(!m||8>w)for(var R=0;w>=R;R+=65535){var P=R+65535;w>P?A=v4(E,A,p.subarray(R,P)):(E[R]=!0,A=v4(E,A,p.subarray(R,w)))}else{for(var I=TW[m-1],T=I>>>13,L=8191&I,M=(1<<g)-1,D=new vi(32768),O=new vi(M+1),F=Math.ceil(g/3),Z=2*F,V=function(Ae){return(p[Ae]^p[Ae+1]<<F^p[Ae+2]<<Z)&M},U=new Ld(25e3),K=new vi(288),W=new vi(32),G=0,j=0,H=(R=0,0),B=0,N=0;w>R;++R){var q=V(R),X=32767&R,te=O[q];if(D[X]=te,O[q]=X,R>=B){var ie=w-R;if((G>7e3||H>24576)&&ie>423){A=VS(p,E,0,U,K,W,j,H,N,R-N,A),H=G=j=0,N=R;for(var Y=0;286>Y;++Y)K[Y]=0;for(Y=0;30>Y;++Y)W[Y]=0}var J=2,ue=0,be=L,Me=X-te&32767;if(ie>2&&q==V(R-Me))for(var _e=Math.min(T,ie)-1,ke=Math.min(32767,R),$e=Math.min(258,ie);ke>=Me&&--be&&X!=te;){if(p[R+J]==p[R+J-Me]){for(var Qe=0;$e>Qe&&p[R+Qe]==p[R+Qe-Me];++Qe);if(Qe>J){if(J=Qe,ue=Me,Qe>_e)break;var He=Math.min(Me,Qe-2),ze=0;for(Y=0;He>Y;++Y){var ye=R-Me+Y+32768&32767,nt=ye-D[ye]+32768&32767;nt>ze&&(ze=nt,te=ye)}}}Me+=(X=te)-(te=D[X])+32768&32767}if(ue){U[H++]=268435456|m4[J]<<18|FS[ue];var $t=31&m4[J],ve=31&FS[ue];j+=X8[$t]+Q8[ve],++K[257+$t],++W[ve],B=R+J,++G}else U[H++]=p[R],++K[p[R]]}}A=VS(p,E,!0,U,K,W,j,H,N,R-N,A)}return d9(C,0,b+u9(A)+x)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,l)),f=u.length;return(function(p,m){var g=m.filename;if(p[0]=31,p[1]=139,p[2]=8,p[8]=2>m.level?4:m.level==9?2:0,p[9]=3,m.mtime!=0&&Ab(p,4,Math.floor(new Date(m.mtime||Date.now())/1e3)),g){p[3]=8;for(var b=0;g.length>=b;++b)p[b+10]=g.charCodeAt(b)}})(u,t),Ab(u,f-8,n.d()),Ab(u,f-4,r),u}var RW=!!Fw||!!jw,f9="text/plain",_g=!1,MW=(e,t)=>{var[n,r]=e.split("#"),[i,s]=n.split("?");if(!s)return e;var o=s.split("&").filter((a=>a.split("=")[0]!==t)).join("&");return i+(o?"?"+o:"")+(r?"#"+r:"")},wv=function(e,t,n){var r;n===void 0&&(n=!0);var[i,s]=e.split("?"),o=Oe({},t),a=(r=s==null?void 0:s.split("&").map((u=>{var f,[p,m]=u.split("="),g=n&&(f=o[p])!==null&&f!==void 0?f:m;return delete o[p],p+"="+g})))!==null&&r!==void 0?r:[],l=(function(u,f){var p,m;f===void 0&&(f="&");var g=[];return Rn(u,(function(b,x){We(b)||We(x)||x==="undefined"||(p=encodeURIComponent((k=>k instanceof File)(b)?b.name:b.toString()),m=encodeURIComponent(x),g[g.length]=m+"="+p)})),g.join(f)})(o);return l&&a.push(l),i+"?"+a.join("&")},Qu=(e,t)=>JSON.stringify(e,((n,r)=>typeof r=="bigint"?r.toString():r),t),HS=e=>{if(e.tr)return e.tr;var{data:t,compression:n}=e;if(t){if(n===no.GZipJS){var r=IW((function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var f=new ts(a.length+(a.length>>>1)),p=0,m=function(k){f[p++]=k},g=0;u>g;++g){if(p+5>f.length){var b=new ts(p+8+(u-g<<1));b.set(f),f=b}var x=a.charCodeAt(g);128>x?m(x):2048>x?(m(192|x>>>6),m(128|63&x)):x>55295&&57344>x?(m(240|(x=65536+(1047552&x)|1023&a.charCodeAt(++g))>>>18),m(128|x>>>12&63),m(128|x>>>6&63),m(128|63&x)):(m(224|x>>>12),m(128|x>>>6&63),m(128|63&x))}return d9(f,0,p)})(Qu(t)),{mtime:0});return{contentType:f9,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(n===no.Base64){var i=(function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,((l,u)=>String.fromCharCode(parseInt(u,16)))))})(Qu(t)),s=(a=>"data="+encodeURIComponent(typeof a=="string"?a:Qu(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var o=Qu(t);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Tb=e=>{var t,n,r,i=HS(e);return!i||(n=e.compression,r=up(e.url,"compression"),n!==xS.GZipJS&&r!==xS.GZipJS&&r!=="gzip")||((t=i.body)instanceof ArrayBuffer?Ow(new Uint8Array(t)):ArrayBuffer.isView(t)&&Ow(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)))?{url:e.url,encodedBody:i}:(_g=!0,{url:MW(e.url,"compression"),encodedBody:HS(Oe({},e,{compression:void 0,tr:void 0}))})},$W=(function(){var e=$i((function*(t){var n=Qu(t.data),r=yield(function(s,o,a){return Vw.apply(this,arguments)})(n,wr.DEBUG,{rethrow:!0});if(!r)return t;var i=yield r.arrayBuffer();return Oe({},t,{tr:{contentType:f9,body:i,estimatedSize:i.byteLength}})}));return function(t){return e.apply(this,arguments)}})(),BS=(e,t)=>wv(e,{_:new Date().getTime().toString(),ver:wr.JS_SDK_VERSION,compression:t}),kg=[];jw&&kg.push({transport:"fetch",method(e){var t,{url:n,encodedBody:r}=Tb(e),{contentType:i,body:s,estimatedSize:o}=r??{},a=new Headers;Rn(e.headers,(function(f,p){a.append(p,f)})),i&&a.append("Content-Type",i);var l=null;if(vS){var u=new vS;l={signal:u.signal,timeout:setTimeout((()=>u.abort()),e.timeout)}}jw(n,Oe({method:(e==null?void 0:e.method)||"GET",headers:a,keepalive:e.method==="POST"&&52428.8>(o||0),body:s,signal:(t=l)==null?void 0:t.signal},e.fetchOptions)).then((f=>f.text().then((p=>{var m={statusCode:f.status,text:p};if(f.status===200)try{m.json=JSON.parse(p)}catch(g){Ue.error(g)}e.callback==null||e.callback(m)})))).catch((f=>{Ue.error(f),e.callback==null||e.callback({statusCode:0,error:f})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Fw&&kg.push({transport:"XHR",method(e){var t=new Fw,{url:n,encodedBody:r}=Tb(e);t.open(e.method||"GET",n,!0);var{contentType:i,body:s}=r??{};Rn(e.headers,(function(o,a){t.setRequestHeader(a,o)})),i&&t.setRequestHeader("Content-Type",i),e.timeout&&(t.timeout=e.timeout),e.disableXHRCredentials||(t.withCredentials=!0),t.onreadystatechange=()=>{if(t.readyState===4){var o={statusCode:t.status,text:t.responseText};if(t.status===200)try{o.json=JSON.parse(t.responseText)}catch{}e.callback==null||e.callback(o)}},t.send(s)}}),Ni!=null&&Ni.sendBeacon&&kg.push({transport:"sendBeacon",method(e){try{var{url:t,encodedBody:n}=Tb(e),r=wv(t,{beacon:"1"}),{contentType:i,body:s}=n??{};if(!s)return;var o=s instanceof Blob?s:new Blob([s],{type:i});Ni.sendBeacon(r,o)}catch{}}});var y4=3e3;class DW{constructor(t,n){this.qr=!0,this.jr=[],this.Hr=ao((n==null?void 0:n.flush_interval_ms)||y4,250,5e3,Ue.createLogger("flush interval"),y4),this.Ur=t}enqueue(t){this.jr.push(t),this.Br||this.zr()}unload(){this.Vr();var t=this.jr.length>0?this.Wr():{},n=Object.values(t);[...n.filter((r=>r.url.indexOf("/e")===0)),...n.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Ur(Oe({},r,{transport:"sendBeacon"}))}))}enable(){this.qr=!1,this.zr()}zr(){var t=this;this.qr||(this.Br=setTimeout((()=>{if(this.Vr(),this.jr.length>0){var n=this.Wr(),r=function(){var s=n[i],o=new Date().getTime();s.data&&sn(s.data)&&Rn(s.data,(a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp})),t.Ur(s)};for(var i in n)r()}}),this.Hr))}Vr(){clearTimeout(this.Br),this.Br=void 0}Wr(){var t={};return Rn(this.jr,(n=>{var r,i=n,s=(i?i.batchKey:null)||i.url;We(t[s])&&(t[s]=Oe({},i,{data:[]})),(r=t[s].data)==null||r.push(i.data)})),this.jr=[],t}}var NW=["retriesPerformedSoFar"];class LW{constructor(t){this.Zr=!1,this.Gr=3e3,this.jr=[],this._instance=t,this.jr=[],this.Qr=!0,!We(me)&&"onLine"in me.navigator&&(this.Qr=me.navigator.onLine,this.Jr=()=>{this.Qr=!0,this.Kr()},this.Yr=()=>{this.Qr=!1},Wn(me,"online",this.Jr),Wn(me,"offline",this.Yr))}get length(){return this.jr.length}retriableRequest(t){var{retriesPerformedSoFar:n}=t,r=dM(t,NW);Fo(n)&&(r.url=wv(r.url,{retry_count:n})),this._instance._send_request(Oe({},r,{callback:i=>{i.statusCode===200||i.statusCode>=400&&500>i.statusCode||(n??0)>=10?r.callback==null||r.callback(i):this.Xr(Oe({retriesPerformedSoFar:n},r))}}))}Xr(t){var n=t.retriesPerformedSoFar||0;t.retriesPerformedSoFar=n+1;var r=(function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),f=Math.random()-.5;return Math.ceil(u+f*(u-l))})(n),i=Date.now()+r;this.jr.push({retryAt:i,requestOptions:t});var s="Enqueued failed request for retry in "+r;navigator.onLine||(s+=" (Browser is offline)"),Ue.warn(s),this.Zr||(this.Zr=!0,this.ei())}ei(){if(this.ti&&clearTimeout(this.ti),this.jr.length===0)return this.Zr=!1,void(this.ti=void 0);this.ti=setTimeout((()=>{this.Qr&&this.jr.length>0&&this.Kr(),this.ei()}),this.Gr)}Kr(){var t=Date.now(),n=[],r=this.jr.filter((s=>t>s.retryAt||(n.push(s),!1)));if(this.jr=n,r.length>0)for(var{requestOptions:i}of r)this.retriableRequest(i)}unload(){for(var{requestOptions:t}of(this.ti&&(clearTimeout(this.ti),this.ti=void 0),this.Zr=!1,We(me)||(this.Jr&&(me.removeEventListener("online",this.Jr),this.Jr=void 0),this.Yr&&(me.removeEventListener("offline",this.Yr),this.Yr=void 0)),this.jr))try{this._instance._send_request(Oe({},t,{transport:"sendBeacon"}))}catch(n){Ue.error(n)}this.jr=[]}}class jW{constructor(t){this.ri=()=>{var n,r,i,s;this.ii||(this.ii={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+((o==null?void 0:o.clientHeight)||0),f=(o==null?void 0:o.scrollHeight)||0;this.ii.lastScrollY=Math.ceil(a),this.ii.maxScrollY=Math.max(a,(n=this.ii.maxScrollY)!==null&&n!==void 0?n:0),this.ii.maxScrollHeight=Math.max(l,(r=this.ii.maxScrollHeight)!==null&&r!==void 0?r:0),this.ii.lastContentY=u,this.ii.maxContentY=Math.max(u,(i=this.ii.maxContentY)!==null&&i!==void 0?i:0),this.ii.maxContentHeight=Math.max(f,(s=this.ii.maxContentHeight)!==null&&s!==void 0?s:0)},this._instance=t}get ni(){return this._instance.config.scroll_root_selector}getContext(){return this.ii}resetContext(){var t=this.ii;return setTimeout(this.ri,0),t}startMeasuringScrollPosition(){Wn(me,"scroll",this.ri,{capture:!0}),Wn(me,"scrollend",this.ri,{capture:!0}),Wn(me,"resize",this.ri)}scrollElement(){if(!this.ni)return me==null?void 0:me.document.documentElement;var t=sn(this.ni)?this.ni:[this.ni];for(var n of t){var r=me==null?void 0:me.document.querySelector(n);if(r)return r}}scrollY(){if(this.ni){var t=this.scrollElement();return t&&t.scrollTop||0}return me&&(me.scrollY||me.pageYOffset||me.document.documentElement.scrollTop)||0}scrollX(){if(this.ni){var t=this.scrollElement();return t&&t.scrollLeft||0}return me&&(me.scrollX||me.pageXOffset||me.document.documentElement.scrollLeft)||0}}var FW=e=>r9(e==null?void 0:e.config.mask_personal_data_properties,e==null?void 0:e.config.custom_personal_data_properties);class zS{constructor(t,n,r,i){this.si=s=>{var o=this.oi();if(!o||o.sessionId!==s){var a={sessionId:s,props:this.ai(this._instance)};this.ui.register({[c4]:a})}},this._instance=t,this.li=n,this.ui=r,this.ai=i||FW,this.li.onSessionId(this.si)}oi(){return this.ui.props[c4]}getSetOnceProps(){var t,n=(t=this.oi())==null?void 0:t.props;return n?"r"in n?i9(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 Rn(Y8(this.getSetOnceProps()),((n,r)=>{r==="$current_url"&&(r="url"),t["$session_entry_"+Hw(r)]=n})),t}}class J8{constructor(){this.hi={}}on(t,n){return this.hi[t]||(this.hi[t]=[]),this.hi[t].push(n),()=>{this.hi[t]=this.hi[t].filter((r=>r!==n))}}emit(t,n){for(var r of this.hi[t]||[])r(n);for(var i of this.hi["*"]||[])i(t,n)}}var Pb=Ln("[SessionId]");class US{on(t,n){return this.ci.on(t,n)}constructor(t,n,r){var i;if(this.di=null,this.vi=[],this.fi=void 0,this.ci=new J8,this.pi=(u,f)=>!(!Fo(u)||!Fo(f))&&Math.abs(u-f)>this.sessionTimeoutMs,!t.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(t.config.cookieless_mode===Go)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.qt=t.config,this.ui=t.persistence,this.gi=void 0,this.mi=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.yi=n||Ga,this.bi=r||Ga;var s=this.qt.persistence_name||this.qt.token;if(this._sessionTimeoutMs=1e3*ao(this.qt.session_idle_timeout_seconds||1800,60,36e3,Pb.createLogger("session_idle_timeout_seconds"),1800),t.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.wi(),this.xi="ph_"+s+"_window_id",this.Si="ph_"+s+"_primary_window_exists",this.ki()){var o=Ir.F(this.xi),a=Ir.F(this.Si);o&&!a?this.gi=o:Ir.q(this.xi),Ir.N(this.Si,!0)}if((i=this.qt.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var f=this.qt.bootstrap.sessionID.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})();this.Ci(this.qt.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Pb.error("Invalid sessionID in bootstrap",u)}this.Ii()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(t){return We(this.vi)&&(this.vi=[]),this.vi.push(t),this.mi&&t(this.mi,this.gi),()=>{this.vi=this.vi.filter((n=>n!==t))}}ki(){return this.qt.persistence!=="memory"&&!this.ui.wr&&Ir.O()}Ti(t){t!==this.gi&&(this.gi=t,this.ki()&&Ir.N(this.xi,t))}Ei(){return this.gi?this.gi:this.ki()?Ir.F(this.xi):null}Mi(t){var n=this.di;return!es(n)&&!es(t)&&5e3>Math.abs(t-n)}Ci(t,n,r){var i=n!==this._sessionActivityTimestamp,s=!(t!==this.mi||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.mi=t,s&&!i||s&&this.Mi(n)||(this.di=n,this.ui.register({[Yu]:[n,t,r]}))}Ri(){var t,n=(t=this.qt)==null?void 0:t.persistence_save_debounce_ms;return Fo(n)&&n>0}Pi(){var t;if(!es(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.di){this.Ri()?this.ui.refreshKey(Yu):(this.ui.flush(),this.ui.load());var[,n,r]=this.Oi();n===this.mi&&r===this._sessionStartTimestamp&&(this.di=this._sessionActivityTimestamp,this.ui.register({[Yu]:[this._sessionActivityTimestamp,(t=this.mi)!==null&&t!==void 0?t:null,this._sessionStartTimestamp]}),this.ui.flush())}}Li(){var[t]=this.Oi(),n=Fo(t)?t:0,r=Fo(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(n,r)}Oi(){var t=this.ui.props[Yu];return sn(t)&&t.length===2&&t.push(t[0]),t||[0,null,0]}resetSessionId(){this.di=null,clearTimeout(this.Fi),this.Fi=void 0,this.Ci(null,null,null)}destroy(){this.Pi(),clearTimeout(this.Fi),this.Fi=void 0,this.fi&&me&&(me.removeEventListener(l1,this.fi,{capture:!1}),this.fi=void 0),this.vi=[]}Ii(){this.fi=()=>{this.Pi(),this.ki()&&Ir.q(this.Si)},Wn(me,l1,this.fi,{capture:!1})}checkAndGetSessionAndWindowId(t,n){if(t===void 0&&(t=!1),n===void 0&&(n=null),this.qt.cookieless_mode===Go)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[,i,s]=this.Oi(),o=this.Li(),a=this.Ei(),l=Fo(s)&&Math.abs(r-s)>864e5,u=!1,f=!i,p=!f&&!t&&this.pi(r,o);f||p||l?(i=this.yi(),a=this.bi(),Pb.info("new session ID generated",{sessionId:i,windowId:a,changeReason:{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}}),s=r,u=!0):a||(a=this.bi(),u=!0);var m=Fo(o)&&t&&!l?o:r,g=Fo(s)?s:new Date().getTime();return this.Ti(a),this.Ci(i,m,g),t||this.wi(),u&&this.vi.forEach((b=>b(i,a,u?{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}:void 0))),{sessionId:i,windowId:a,sessionStartTimestamp:g,changeReason:u?{noSessionId:f,activityTimeout:p,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:o}}wi(){clearTimeout(this.Fi),this.Fi=setTimeout((()=>{var t=this.Li();if(this.pi(new Date().getTime(),t)){var n=this.mi;this.resetSessionId(),this.ci.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}}var h9=function(e,t){if(!e)return!1;var n=e.userAgent;if(n&&_S(n,t))return!0;try{var r=e==null?void 0:e.userAgentData;if(r!=null&&r.brands&&r.brands.some((i=>_S(i==null?void 0:i.brand,t))))return!0}catch{}return!!e.webdriver},p1=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 ZS(e,t,n){return Qu({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:n})}var p9={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=>p1(n,r))))),not_regex:(e,t)=>t.every((n=>e.every((r=>!p1(n,r))))),icontains:(e,t)=>t.map(Tm).some((n=>e.map(Tm).some((r=>n.includes(r))))),not_icontains:(e,t)=>t.map(Tm).every((n=>e.map(Tm).every((r=>!n.includes(r))))),gt:(e,t)=>t.some((n=>{var r=parseFloat(n);return!isNaN(r)&&e.some((i=>r>parseFloat(i)))})),lt:(e,t)=>t.some((n=>{var r=parseFloat(n);return!isNaN(r)&&e.some((i=>r<parseFloat(i)))}))},Tm=e=>e.toLowerCase();function m9(e,t){return!e||Object.entries(e).every((n=>{var[r,i]=n,s=t==null?void 0:t[r];if(We(s)||es(s))return!1;var o=[String(s)],a=p9[i.operator];return!!a&&a(i.values,o)}))}var b4="custom",WS="i.posthog.com",OW=/^\/static\//;class VW{constructor(t){this.Ai={},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 flagsApiHost(){var t=this.instance.config.flags_api_host;return t?t.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var t,n=(t=this.instance.config.ui_host)==null?void 0:t.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+WS,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.Ai[this.apiHost]||(this.Ai[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":b4),this.Ai[this.apiHost]}Ni(t){var n=this.instance.config.__preview_external_dependency_versioned_paths;if(typeof n=="string"&&OW.test(t))return n.trim().replace(/\/$/,"")||void 0}endpointFor(t,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),t==="ui")return this.uiHost+n;if(t==="flags")return this.flagsApiHost+n;if(t==="assets"){var r=this.Ni(n);if(r)return""+r+n}if(this.region===b4)return this.apiHost+n;var i=WS+n;switch(t){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}var bn=Ln("[Surveys]"),x4="seenSurvey_",HW=[Cb.Popover,Cb.Widget,Cb.API],BW={ignoreConditions:!1,ignoreDelay:!1,displayType:p4.Popover},zW=Ln("[PostHog ExternalIntegrations]"),UW={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class ZW{constructor(t){this._instance=t}lr(t,n){var r;(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,t,(i=>{if(i)return zW.error("failed to load script",i);n()}))}startIfEnabledOrStop(){var t=this,n=function(o){var a,l,u;!i||(a=gt.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[o]||t.lr(UW[o],(()=>{var f;(f=gt.__PosthogExtensions__)==null||(f=f.integrations)==null||(f=f[o])==null||f.start(t._instance)})),!i&&(l=gt.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((u=gt.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.stop())};for(var[r,i]of Object.entries((s=this._instance.config.integrations)!==null&&s!==void 0?s:{})){var s;n(r)}}}var Eu,Wh={},Ib=0,w4=()=>{},GS='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',oh="Surveys module not available",qS="sanitize_properties is deprecated. Use before_send instead",g9="Invalid value for property_denylist config: ",Zu="posthog",v9=!RW&&(ui==null?void 0:ui.indexOf("MSIE"))===-1&&(ui==null?void 0:ui.indexOf("Mozilla"))===-1,KS=e=>{var t;return Oe({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:aW(Ze==null?void 0:Ze.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:w4,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,debug:Pr&&Nn(Pr==null?void 0:Pr.search)&&Pr.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_conversations:!1,disable_product_tours:!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,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(n){Ue.error("Bad HTTP status: "+n.statusCode+" "+n.text)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:h4,before_send:void 0,request_queue_config:{flush_interval_ms:y4},error_tracking:{},_onCapture:w4,__preview_eager_load_replay:!1},(n=>({rageclick:!n||"2025-11-30">n||{content_ignorelist:!0},capture_pageview:!n||"2025-05-24">n||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:n&&n>="2026-01-30"?"head":"body",internal_or_test_user_hostname:n&&n>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:n&&n>="2026-05-30"?250:0}))(e))},WW=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["store_google","save_campaign_params"],["verbose","debug"]],YS=e=>{var t={};for(var[n,r]of WW)We(e[n])||(t[r]=e[n]);var i=qn({},t,e);return sn(e.property_blacklist)&&(We(e.property_denylist)?i.property_denylist=e.property_blacklist:sn(e.property_denylist)?i.property_denylist=[...e.property_blacklist,...e.property_denylist]:Ue.error(g9+e.property_denylist)),i};class GW{constructor(){this.__forceAllowLocalhost=!1}get Di(){return this.__forceAllowLocalhost}set Di(t){Ue.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=t}}class Xi{$i(t,n){if(t){var r=this.qi.indexOf(t);r!==-1&&this.qi.splice(r,1)}return this.qi.push(n),n.initialize==null||n.initialize(),n}ji(){return this.config.cookieless_mode===Go||this.config.cookieless_mode===rc&&this.consent.isRejected()}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(){var t;this.webPerformance=new GW,this.Hi=!1,this.version=wr.LIB_VERSION,this.Ui=new J8,this.qi=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=KS(),this.SentryIntegration=vW,this.sentryIntegration=r=>(function(i,s){var o=QM(i,s);return{name:XM,processEvent:a=>o(a)}})(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Bi=!1,this.zi=null,this.Vi=null,this.Wi=null,this.scrollManager=new jW(this),this.pageViewManager=new $S(this),this.rateLimiter=new EW(this),this.requestRouter=new VW(this),this.consent=new pW(this),this.externalIntegrations=new ZW(this);var n=(t=Xi.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=n.featureFlags&&new n.featureFlags(this),this.toolbar=n.toolbar&&new n.toolbar(this),this.surveys=n.surveys&&new n.surveys(this),this.conversations=n.conversations&&new n.conversations(this),this.logs=n.logs&&new n.logs(this),this.experiments=n.experiments&&new n.experiments(this),this.exceptions=n.exceptions&&new n.exceptions(this),this.people={set:(r,i,s)=>{var o=Nn(r)?{[r]:i}:r;this.setPersonProperties(o),s==null||s({})},set_once:(r,i,s)=>{var o=Nn(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),s==null||s({})}},this.on("eventCaptured",(r=>Ue.info('send "'+(r==null?void 0:r.event)+'"',r)))}init(t,n,r){if(r&&r!==Zu){var i,s=(i=Wh[r])!==null&&i!==void 0?i:new Xi;return s._init(t,n,r),Wh[r]=s,Wh[Zu][r]=s,s}return this._init(t,n,r)}_init(t,n,r){var i,s;n===void 0&&(n={});var o=Nn(t)?t.trim():"";if(!o)return Ue.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.Zi(n.debug),this.Gi=n,this.Qi=[],n.person_profiles?this.Vi=n.person_profiles:n.process_person&&(this.Vi=n.process_person),this.set_config(qn({},KS(n.defaults),YS(n),{name:r,token:o})),this.config.on_xhr_error&&Ue.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:no.GZipJS;var a=this.Ji();this.persistence=new kb(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new kb(Oe({},this.config,{persistence:"sessionStorage"}),a);var l=Oe({},this.persistence.props),u=Oe({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Ki=new DW((w=>this.Yi(w)),this.config.request_queue_config),this.Xi=new LW(this),this.__request_queue=[];var f=this.ji();if(f||(this.sessionManager=new US(this),this.sessionPropsManager=new zS(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Ue.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.en(f)}),0)):(Ue.info("Initializing extensions synchronously"),this.en(f)),wr.DEBUG=wr.DEBUG||this.config.debug,wr.DEBUG&&Ue.info("Starting in debug mode",{this:this,config:n,thisC:Oe({},this.config),p:l,s:u}),!this.config.identity_distinct_id||(i=n.bootstrap)!=null&&i.distinctID||(n.bootstrap=Oe({},n.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((s=n.bootstrap)==null?void 0:s.distinctID)!==void 0){var p=n.bootstrap.distinctID,m=this.get_distinct_id(),g=this.persistence.get_property(xs);if(n.bootstrap.isIdentifiedID&&m!=null&&m!==p&&g===_u)this.identify(p);else if(n.bootstrap.isIdentifiedID&&m!=null&&m!==p&&g===ku)Ue.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var b=this.config.get_device_id(Ga()),x=n.bootstrap.isIdentifiedID?b:p;this.persistence.set_property(xs,n.bootstrap.isIdentifiedID?ku:_u),this.register({distinct_id:p,$device_id:x})}}if(f)this.register_once({distinct_id:km,$device_id:null},"");else if(!this.get_distinct_id()){var k=this.config.get_device_id(Ga());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(xs,_u)}return Wn(me,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),n.segment?(function(w,C){var E=w.config.segment;if(!E)return C();(function(A,R){var P=A.config.segment;if(!P)return R();var I=L=>{var M=()=>L.anonymousId()||Ga();A.config.get_device_id=M,L.id()&&(A.register({distinct_id:L.id(),$device_id:M()}),A.persistence.set_property(xs,ku)),R()},T=P.user();"then"in T&&zo(T.then)?T.then(I):I(T)})(w,(()=>{E.register((A=>{Promise&&Promise.resolve||_b.warn("This browser does not have Promise support, and can not use the segment integration");var R=(P,I)=>{if(!I)return P;P.event.userId||P.event.anonymousId===A.get_distinct_id()||(_b.info("No userId set, resetting PostHog"),A.reset()),P.event.userId&&P.event.userId!==A.get_distinct_id()&&(_b.info("UserId set, identifying with PostHog"),A.identify(P.event.userId));var T=A.calculateEventProperties(I,P.event.properties);return P.event.properties=Object.assign({},T,P.event.properties),P};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:P=>R(P,P.event.event),page:P=>R(P,Uu),identify:P=>R(P,xb),screen:P=>R(P,"$screen")}})(w)).then((()=>{C()}))}))})(this,(()=>this.tn())):this.tn(),zo(this.config._onCapture)&&this.config._onCapture!==w4&&(Ue.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(w=>this.config._onCapture(w.event,w)))),this.config.ip&&Ue.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}en(t){var n,r,i,s,o,a,l,u=performance.now(),f=Oe({},Xi.__defaultExtensionClasses,this.config.__extensionClasses),p=[];f.featureFlags&&this.qi.push(this.featureFlags=(n=this.featureFlags)!==null&&n!==void 0?n:new f.featureFlags(this)),f.exceptions&&this.qi.push(this.exceptions=(r=this.exceptions)!==null&&r!==void 0?r:new f.exceptions(this)),f.historyAutocapture&&this.qi.push(this.historyAutocapture=new f.historyAutocapture(this)),f.tracingHeaders&&this.qi.push(new f.tracingHeaders(this)),f.siteApps&&this.qi.push(this.siteApps=new f.siteApps(this)),f.sessionRecording&&!t&&this.qi.push(this.sessionRecording=new f.sessionRecording(this)),this.config.disable_scroll_properties||p.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),f.autocapture&&this.qi.push(this.autocapture=new f.autocapture(this)),f.surveys&&this.qi.push(this.surveys=(i=this.surveys)!==null&&i!==void 0?i:new f.surveys(this)),f.logs&&this.qi.push(this.logs=(s=this.logs)!==null&&s!==void 0?s:new f.logs(this)),f.conversations&&this.qi.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new f.conversations(this)),f.productTours&&this.qi.push(this.productTours=new f.productTours(this)),f.heatmaps&&this.qi.push(this.heatmaps=new f.heatmaps(this)),f.webVitalsAutocapture&&this.qi.push(this.webVitalsAutocapture=new f.webVitalsAutocapture(this)),f.exceptionObserver&&this.qi.push(this.exceptionObserver=new f.exceptionObserver(this)),f.deadClicksAutocapture&&this.qi.push(this.deadClicksAutocapture=new f.deadClicksAutocapture(this,gW)),f.toolbar&&this.qi.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new f.toolbar(this)),f.experiments&&this.qi.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new f.experiments(this)),this.qi.forEach((m=>{m.initialize&&p.push((()=>{m.initialize==null||m.initialize()}))})),p.push((()=>{if(this.rn){var m=this.rn;this.rn=void 0,this.Ar(m)}})),this.nn(p,u)}nn(t,n){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&t.length>0)return void setTimeout((()=>{this.nn(t,n)}),0);var r=t.shift();if(r)try{r()}catch(s){Ue.error("Error initializing extension:",s)}}var i=Math.round(performance.now()-n);this.register_for_session({[WM]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[GM]:i}),this.config.__preview_deferred_init_extensions&&Ue.info("PostHog extensions initialized ("+i+"ms)")}Ar(t){var n;if(!Ze||!Ze.body)return Ue.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Ar(t)}),500);this.config.__preview_deferred_init_extensions&&(this.rn=t),this.sn=t,this.compression=void 0,t.supportedCompression&&!this.config.disable_compression&&(this.compression=At(t.supportedCompression,no.GZipJS)?no.GZipJS:At(t.supportedCompression,no.Base64)?no.Base64:void 0),(n=t.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=t.analytics.endpoint),this.set_config({person_profiles:this.Vi?this.Vi:h4}),this.qi.forEach((r=>r.onRemoteConfig==null?void 0:r.onRemoteConfig(t)))}tn(){try{this.config.loaded(this)}catch(r){Ue.critical("`loaded` function failed",r)}if(this.an(),this.config.internal_or_test_user_hostname&&Pr!=null&&Pr.hostname){var t=Pr.hostname,n=this.config.internal_or_test_user_hostname;(typeof n=="string"?t===n:n.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.ji())&&this.un()}),1),this.ln=new o9(this),this.ln.load()}an(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.Ki)==null||t.enable())}_dom_loaded(){this.is_capturing()&&Cm(this.__request_queue,(t=>this.Yi(t))),this.__request_queue=[],this.an()}_handle_unload(){var t,n,r,i;(t=this.surveys)==null||t.handlePageUnload(),this.config.request_batching?(this.hn()&&this.capture(bb),(n=this.logs)==null||n.flushLogs("sendBeacon"),(r=this.Ki)==null||r.unload(),(i=this.Xi)==null||i.unload()):this.hn()&&this.capture(bb,null,{transport:"sendBeacon"})}_send_request(t){this.__loaded&&(v9?this.__request_queue.push(t):this.rateLimiter.isServerRateLimited(t.batchKey)||(t.transport=t.transport||this.config.api_transport,t.url=wv(t.url,{ip:this.config.ip?1:0}),t.headers=Oe({},this.config.request_headers,t.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,i,s,o=Oe({},n);o.timeout=o.timeout||6e4,o.url=BS(o.url,o.compression);var a=(r=o.transport)!==null&&r!==void 0?r:"fetch",l=kg.filter((f=>!o.disableTransport||!f.transport||!o.disableTransport.includes(f.transport))),u=(i=(s=(function(f,p){for(var m=0;f.length>m;m++)if(f[m].transport===a)return f[m]})(l))==null?void 0:s.method)!==null&&i!==void 0?i:l[0].method;if(!u)throw new Error("No available transport method");a!=="sendBeacon"&&o.data&&o.compression===no.GZipJS&&gZ&&!_g?$W(o).then((f=>{u(f)})).catch((f=>{if(wS(f))return _g=!0,void u(Oe({},o,{compression:void 0,url:BS(n.url,void 0)}));(p=>{if(!p||typeof p!="object")return!1;var m="name"in p?String(p.name):"";return wS(p)||m===fM})(f)&&(_g=!0),u(o)})):u(o)})(Oe({},t,{callback:n=>{var r,i;this.rateLimiter.checkForLimiting(n),400>n.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,n),t.callback==null||t.callback(n)}}))))}Yi(t){this.Xi?this.Xi.retriableRequest(t):this._send_request(t)}_execute_array(t){Ib++;try{var n,r=[],i=[],s=[];Cm(t,(a=>{if(a)if(sn(n=a[0]))s.push(a);else if(zo(a))try{a.call(this)}catch(l){Ue.error("Error executing queued PostHog call",a,l)}else sn(a)&&n==="alias"?r.push(a):sn(a)&&n.indexOf("capture")!==-1&&zo(this[n])?s.push(a):i.push(a)}));var o=function(a,l){Cm(a,(function(u){try{if(sn(u[0])){var f=l;Rn(u,(function(p){f=f[p[0]].apply(f,p.slice(1))}))}else l[u[0]].apply(l,u.slice(1))}catch(p){Ue.error("Error executing queued PostHog call",u,p)}}))};o(r,this),o(i,this),o(s,this)}finally{Ib--}}push(t){if(Ib>0&&sn(t)&&Nn(t[0])){var n=Xi.prototype[t[0]];zo(n)&&n.apply(this,t.slice(1))}else this._execute_array([t])}capture(t,n,r){var i,s,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Ki){if(this.is_capturing())if(!We(t)&&Nn(t)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var f=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(f==null||!f.isRateLimited){n!=null&&n.$current_url&&!Nn(n==null?void 0:n.$current_url)&&(Ue.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),t!=="$exception"||r!=null&&r.cn||Ue.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&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 p=new Date,m=(r==null?void 0:r.timestamp)||p,g=(r==null?void 0:r.uuid)||Ga(),b={uuid:g,event:t,properties:this.calculateEventProperties(t,n||{},m,g)};t===Uu&&this.config.__preview_capture_bot_pageviews&&u&&(b.event="$bot_pageview",b.properties.$browser_type="bot"),f&&(b.properties.$lib_rate_limit_remaining_tokens=f.remainingTokens),r!=null&&r.$set&&(b.$set=r==null?void 0:r.$set);var x,k,w,C=this.dn(r==null?void 0:r.$set_once,t!==PS,t===xb);if(C&&(b.$set_once=C),r!=null&&r._noTruncate||(s=this.config.properties_string_max_length,o=b,a=L=>Nn(L)?L.slice(0,s):L,l=new Set,b=(function L(M,D){return M!==Object(M)?a?a(M):M:l.has(M)?void 0:(l.add(M),sn(M)?(O=[],Cm(M,(F=>{O.push(L(F))}))):(O={},Rn(M,((F,Z)=>{l.has(F)||(O[Z]=L(F))}))),O);var O})(o)),b.timestamp=m,We(r==null?void 0:r.timestamp)||(b.properties.$event_time_override_provided=!0,b.properties.$event_time_override_system_time=p),t===Ih.DISMISSED||t===Ih.SENT){var E=n==null?void 0:n[Eb.SURVEY_ID],A=n==null?void 0:n[Eb.SURVEY_ITERATION];(L=>{try{var M=(D=>((O,F)=>{var Z=""+x4+F.id;return F.current_iteration&&F.current_iteration>0&&(Z=""+x4+F.id+"_"+F.current_iteration),Z})(0,D))(L);if(localStorage.getItem(M))return;localStorage.setItem(M,"true")}catch(D){bn.error("Failed to persist survey seen state",D)}})({id:E,current_iteration:A}),b.$set=Oe({},b.$set,{[(x={id:E,current_iteration:A},k=t===Ih.SENT?"responded":"dismissed",w="$survey_"+k+"/"+x.id,x.current_iteration&&x.current_iteration>0&&(w="$survey_"+k+"/"+x.id+"/"+x.current_iteration),w)]:!0})}else t===Ih.SHOWN&&(b.$set=Oe({},b.$set,{[Eb.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(t===CW.SHOWN){var R=n==null?void 0:n[NS.TOUR_TYPE];R&&(b.$set=Oe({},b.$set,{[NS.TOUR_LAST_SEEN_DATE+"/"+R]:new Date().toISOString()}))}var P=Oe({},b.properties.$set,b.$set);if(Ku(P)||this.setPersonPropertiesForFlags(P),!Kt(this.config.before_send)){var I=this.vn(b);if(!I)return;b=I}this.Ui.emit("eventCaptured",b);var T={method:"POST",url:(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:b,compression:"best-available",batchKey:r==null?void 0:r._batchKey,transport:r==null?void 0:r.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Yi(T):this.Ki.enqueue(T),b}Ue.critical("This capture call is ignored due to client rate limiting.")}}else Ue.error("No event name provided to posthog.capture")}else Ue.uninitializedWarning("posthog.capture")}_addCaptureHook(t){return this.on("eventCaptured",(n=>t(n.event,n)))}calculateEventProperties(t,n,r,i,s){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var o=s?void 0:this.persistence.remove_event_timer(t),a=Oe({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.ji()&&(a.$cookieless_mode=!0),t==="$snapshot"){var l=Oe({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!Nn(a.distinct_id)&&!Hi(a.distinct_id)||Bw(a.distinct_id))&&Ue.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,f=(function(w,C){var E,A,R,P;if(!ui)return{};var I,T,L,M,D,O,F,Z,V,U=w?[...Nd,...C||[]]:[],[K,W]=(function(H){for(var B=0;ES.length>B;B++){var[N,q]=ES[B],X=N.exec(H),te=X&&(zo(q)?q(X,H):q);if(te)return te}return["",""]})(ui),G=(I=typeof navigator<"u"?navigator:void 0)!=null&&I.brave?{brave:!0}:{},j=qn(Y8({$os:K,$os_version:W,$browser:DM(ui,navigator.vendor,G),$device:SS(ui),$device_type:(L=ui,M={userAgentDataPlatform:(E=navigator)==null||(E=E.userAgentData)==null?void 0:E.platform,maxTouchPoints:(A=navigator)==null?void 0:A.maxTouchPoints,screenWidth:me==null||(R=me.screen)==null?void 0:R.width,screenHeight:me==null||(P=me.screen)==null?void 0:P.height,devicePixelRatio:me==null?void 0:me.devicePixelRatio},V=SS(L),V===vM||V===gM||V==="Kobo"||V==="Kindle Fire"||V===IM?Md:V===lp||V===ud||V===cp||V===Uw?"Console":V===bM?"Wearable":V?Li:(M==null?void 0:M.userAgentDataPlatform)==="Android"&&((D=M==null?void 0:M.maxTouchPoints)!==null&&D!==void 0?D:0)>0?600>Math.min((O=M==null?void 0:M.screenWidth)!==null&&O!==void 0?O:0,(F=M==null?void 0:M.screenHeight)!==null&&F!==void 0?F:0)/((Z=M==null?void 0:M.devicePixelRatio)!==null&&Z!==void 0?Z:1)?Li:Md:"Desktop"),$timezone:s9(),$timezone_offset:_W()}),{$current_url:dp(Pr==null?void 0:Pr.href,U,fp),$host:Pr==null?void 0:Pr.host,$pathname:Pr==null?void 0:Pr.pathname,$raw_user_agent:ui.length>1e3?ui.substring(0,997)+"...":ui,$browser_version:$Z(ui,navigator.vendor,G),$browser_language:DS(),$browser_language_prefix:(T=DS(),typeof T=="string"?T.split("-")[0]:void 0),$screen_height:me==null?void 0:me.screen.height,$screen_width:me==null?void 0:me.screen.width,$viewport_height:me==null?void 0:me.innerHeight,$viewport_width:me==null?void 0:me.innerWidth,$lib:wr.LIB_NAME,$lib_version:wr.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return wr.SDK_DIST_CHANNEL&&(j.$sdk_dist_channel=wr.SDK_DIST_CHANNEL),j})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:p,windowId:m}=this.sessionManager.checkAndGetSessionAndWindowId(s,r.getTime());a.$session_id=p,a.$window_id=m}this.sessionPropsManager&&qn(a,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&qn(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(g=this.Xi)==null?void 0:g.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}if(this.requestRouter.region===b4&&(a.$lib_custom_api_host=this.config.api_host),u=t!==Uu||s?t!==bb||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=qn(a,u),t===Uu&&Ze&&(a.title=Ze.title),!We(o)){var b=r.getTime()-o;a.$duration=parseFloat((b/1e3).toFixed(3))}ui&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=qn({},f,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),sn(this.config.property_denylist)?Rn(this.config.property_denylist,(function(w){delete a[w]})):Ue.error(g9+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var x=this.config.sanitize_properties;x&&(Ue.error(qS),a=x(a,t));var k=this.fn();return a.$process_person_profile=k,k&&!s&&this.pn("_calculate_event_properties"),a}dn(t,n,r){var i;if(n===void 0&&(n=!0),r===void 0&&(r=!1),!this.persistence||!this.fn()||this.Hi&&!r)return t;var s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=qn({},s,o||{},t||{}),l=this.config.sanitize_properties;return l&&(Ue.error(qS),a=l(a,"$set_once")),n&&(this.Hi=!0),Ku(a)?void 0:a}register(t,n){var r;(r=this.persistence)==null||r.register(t,n)}register_once(t,n,r){var i;(i=this.persistence)==null||i.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)}gn(t,n){this.register({[t]:n})}getFeatureFlag(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(t,n)}getFeatureFlagPayload(t){var n;return(n=this.featureFlags)==null?void 0:n.getFeatureFlagPayload(t)}getFeatureFlagResult(t,n){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(t,n)}isFeatureEnabled(t,n){var r;return(r=this.featureFlags)==null?void 0:r.isFeatureEnabled(t,n)}reloadFeatureFlags(){var t;(t=this.featureFlags)==null||t.reloadFeatureFlags()}updateFlags(t,n,r){var i;(i=this.featureFlags)==null||i.updateFlags(t,n,r)}updateEarlyAccessFeatureEnrollment(t,n,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(t,n,r)}getEarlyAccessFeatures(t,n,r){var i;return n===void 0&&(n=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(t,n,r)}on(t,n){return this.Ui.on(t,n)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:oh}),()=>{})}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?this.surveys.getSurveys(t,n):t([],{isLoaded:!1,error:oh})}getActiveMatchingSurveys(t,n){n===void 0&&(n=!1),this.surveys?this.surveys.getActiveMatchingSurveys(t,n):t([],{isLoaded:!1,error:oh})}renderSurvey(t,n){var r;(r=this.surveys)==null||r.renderSurvey(t,n)}displaySurvey(t,n){var r;n===void 0&&(n=BW),(r=this.surveys)==null||r.displaySurvey(t,n)}cancelPendingSurvey(t){var n;(n=this.surveys)==null||n.cancelPendingSurvey(t)}canRenderSurvey(t){var n,r;return(n=(r=this.surveys)==null?void 0:r.canRenderSurvey(t))!==null&&n!==void 0?n:{visible:!1,disabledReason:oh}}canRenderSurveyAsync(t,n){var r,i;return n===void 0&&(n=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(t,n))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:oh})}mn(t){return!t||Bw(t)?(Ue.critical("Unique user id has not been set in posthog.identify"),!1):t===km?(Ue.critical('The string "'+t+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(Ue.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.'),!1)}identify(t,n,r){if(!this.__loaded||!this.persistence)return Ue.uninitializedWarning("posthog.identify");if(Hi(t)&&(t=t.toString(),Ue.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.mn(t)&&this.pn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:t}),this.get_property(r1)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),t!==i&&t!==this.get_property(Sh)&&(this.unregister(Sh),this.register({distinct_id:t}));var s,o=(this.persistence.get_property(xs)||_u)===_u;t!==i&&o?(this.persistence.set_property(xs,ku),this.setPersonPropertiesForFlags({$set:n||{},$set_once:r||{}},!1),this.capture(xb,{distinct_id:t,$anon_distinct_id:i},{$set:n||{},$set_once:r||{}}),this.Wi=ZS(t,n,r),(s=this.featureFlags)==null||s.setAnonymousDistinctId(i)):(n||r)&&this.setPersonProperties(n,r),t!==i&&(this.reloadFeatureFlags(),this.unregister(Uh))}}setPersonProperties(t,n){if((t||n)&&this.pn("posthog.setPersonProperties")){var r=ZS(this.get_distinct_id(),t,n);this.Wi!==r?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:n||{}},!0),this.capture("$set",{$set:t||{},$set_once:n||{}}),this.Wi=r):Ue.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(t,n,r){if(t&&n){var i=this.getGroups(),s=i[t]!==n;if(s&&this.resetGroupPropertiesForFlags(t),this.register({$groups:Oe({},i,{[t]:n})}),s||r){var o={$group_type:t,$group_key:n};r&&(o.$group_set=r),this.capture(PS,o)}r&&this.setGroupPropertiesForFlags({[t]:r}),s&&!r&&this.reloadFeatureFlags()}else Ue.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(t,n)}resetPersonPropertiesForFlags(){var t;(t=this.featureFlags)==null||t.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(t,n){var r;n===void 0&&(n=!0),this.pn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(t,n))}resetGroupPropertiesForFlags(t){var n;(n=this.featureFlags)==null||n.resetGroupPropertiesForFlags(t)}reset(t){var n,r,i,s,o,a,l,u;if(Ue.info("reset"),!this.__loaded)return Ue.uninitializedWarning("posthog.reset");var f,p=this.get_property(r1),m=this.get_property(lc);if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),We(m)||(f=this.persistence)==null||f.register({[lc]:m}),(i=this.surveys)==null||i.reset(),(s=this.ln)==null||s.stop(),(o=this.featureFlags)==null||o.reset(),(a=this.conversations)==null||a.reset(),(l=this.persistence)==null||l.set_property(xs,_u),(u=this.sessionManager)==null||u.resetSessionId(),this.Wi=null,this.config.cookieless_mode===Go)this.register_once({distinct_id:km,$device_id:null},"");else{var g=this.config.get_device_id(Ga());this.register_once({distinct_id:g,$device_id:t?g:p},"")}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}setIdentity(t,n){var r;this.config.identity_distinct_id=t,this.config.identity_hash=n,this.alias(t),(r=this.conversations)==null||r.yn()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,(t=this.conversations)==null||t.bn()}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),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(t!=null&&t.withTimestamp&&r){var s,o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(t,n){return t===this.get_property(VM)?(Ue.critical("Attempting to create alias for existing People user - aborting."),-2):this.pn("posthog.alias")?(We(n)&&(n=this.get_distinct_id()),t!==n?(this.gn(Sh,t),this.capture("$create_alias",{alias:t,distinct_id:n})):(Ue.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){var n=Oe({},this.config);if(Yn(t)){var r,i,s,o,a,l,u,f,p,m;qn(this.config,YS(t));var g=this.Ji();(r=this.persistence)==null||r.update_config(this.config,n,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new kb(Oe({},this.config,{persistence:"sessionStorage"}),g);var b=this.Zi(this.config.debug);oo(b)&&(this.config.debug=b),oo(this.config.debug)&&(this.config.debug?(wr.DEBUG=!0,Bn.O()&&Bn.N("ph_debug",!0),Ue.info("set_config",{config:t,oldConfig:n,newConfig:Oe({},this.config)})):(wr.DEBUG=!1,Bn.O()&&Bn.q("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(s=this.exceptions)==null||s.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(l=this.heatmaps)==null||l.startIfEnabled(),(u=this.exceptionObserver)==null||u.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)==null||f.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this._n(),(m=this.externalIntegrations)==null||m.startIfEnabledOrStop()}}_overrideSDKInfo(t,n){wr.LIB_NAME=t,wr.LIB_VERSION=n}startSessionRecording(t){var n,r,i,s,o,a=t===!0,l={sampling:a||!(t==null||!t.sampling),linked_flag:a||!(t==null||!t.linked_flag),url_trigger:a||!(t==null||!t.url_trigger),event_trigger:a||!(t==null||!t.event_trigger)};Object.values(l).some(Boolean)&&((n=this.sessionManager)==null||n.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.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){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(t,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(Oe({},i,n))}}addExceptionStep(t,n){var r;(r=this.exceptions)==null||r.addExceptionStep(t,n)}captureLog(t){var n;(n=this.logs)==null||n.captureLog(t)}get logger(){var t,n;return(t=(n=this.logs)==null?void 0:n.logger)!==null&&t!==void 0?t:Xi.wn}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var n,r;return(n=(r=this.toolbar)==null?void 0:r.loadToolbar(t))!==null&&n!==void 0&&n}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:Zu;return n!==Zu&&(n=Zu+"."+n),n}_isIdentified(){var t,n;return((t=this.persistence)==null?void 0:t.get_property(xs))===ku||((n=this.sessionPersistence)==null?void 0:n.get_property(xs))===ku}fn(){var t,n;return!(this.config.person_profiles==="never"||this.config.person_profiles===h4&&!this._isIdentified()&&Ku(this.getGroups())&&((t=this.persistence)==null||(t=t.props)==null||!t[Sh])&&((n=this.persistence)==null||(n=n.props)==null||!n[o1]))}hn(){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.fn()||this.pn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.pn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}pn(t){return this.config.person_profiles==="never"?(Ue.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.gn(o1,!0),!0)}Ji(){if(this.config.cookieless_mode==="always")return!0;var t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==rc)}_n(){var t,n,r,i,s=this.Ji();return((t=this.persistence)==null?void 0:t.wr)!==s&&((r=this.persistence)==null||r.set_disabled(s)),((n=this.sessionPersistence)==null?void 0:n.wr)!==s&&((i=this.sessionPersistence)==null||i.set_disabled(s)),s}opt_in_capturing(t){var n;if(this.config.cookieless_mode!==Go){if(this.ji()){var r,i,s,o,a;this.reset(!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new US(this),this.pageViewManager=new $S(this),this.persistence&&(this.sessionPropsManager=new zS(this,this.sessionManager,this.persistence));var l,u=(s=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&s!==void 0?s:(a=Xi.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.$i(this.sessionRecording,new u(this)),this.sn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.sn)))}var f,p;this.consent.optInOut(!0),this._n(),this.an(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode==rc&&((f=this.surveys)==null||f.loadIfEnabled()),(We(t==null?void 0:t.captureEventName)||t!=null&&t.captureEventName)&&this.capture((p=t==null?void 0:t.captureEventName)!==null&&p!==void 0?p:"$opt_in",t==null?void 0:t.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.un()}else Ue.warn(GS)}opt_out_capturing(){var t,n,r;this.config.cookieless_mode!==Go?(this.config.cookieless_mode===rc&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this._n(),this.config.cookieless_mode===rc&&(this.register({distinct_id:km,$device_id:null}),(t=this.sessionRecording)==null||t.stopRecording(),this.sessionRecording=void 0,(n=this.sessionManager)==null||n.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.un(),this.an())):Ue.warn(GS)}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===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Go||(this.config.cookieless_mode===rc?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this._n()}_is_bot(){return Ni?h9(Ni,this.config.custom_blocked_useragents):void 0}un(){Ze&&(Ze.visibilityState==="visible"?this.Bi||(this.Bi=!0,this.capture(Uu,{title:Ze.title},{send_instantly:!0}),this.zi&&(Ze.removeEventListener(a1,this.zi),this.zi=null)):this.zi||(this.zi=this.un.bind(this),Wn(Ze,a1,this.zi)))}debug(t){t===!1?(me==null||me.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(me==null||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}))}Dr(){var t,n,r,i,s,o,a=this.Gi||{};return"advanced_disable_flags"in a?!!a.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ue.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",i=Ue,s=(n="advanced_disable_flags")in(t=a)&&!Kt(t[n]),o=r in t&&!Kt(t[r]),s?t[n]:!!o&&(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]))}vn(t){if(Kt(this.config.before_send))return t;var n=sn(this.config.before_send)?this.config.before_send:[this.config.before_send],r=t;for(var i of n){if(r=i(r),Kt(r)){var s="Event '"+t.event+"' was rejected in beforeSend function";return wZ(t.event)?Ue.warn(s+". This can cause unexpected behavior."):Ue.info(s),null}r.properties&&!Ku(r.properties)||Ue.warn("Event '"+t.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var t;return(t=this.pageViewManager.dr)==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)})}Zi(t){var n=oo(t)&&!t,r=Bn.O()&&Bn.A("ph_debug")==="true";return!n&&(!!r||t)}}Xi.__defaultExtensionClasses={},Xi.wn={trace:Eu=()=>{},debug:Eu,info:Eu,warn:Eu,error:Eu,fatal:Eu},(function(e,t){for(var n=0;t.length>n;n++)e.prototype[t[n]]=sW(e.prototype[t[n]])})(Xi,["identify"]);var qW=1,KW=3,YW=11;function XS(e){return e instanceof Element&&(e.id===ZM||!(e.closest==null||!e.closest(".toolbar-global-fade-container")))}function Rc(e){return!!e&&e.nodeType===qW}function As(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function y9(e){return!!e&&e.nodeType===KW}function b9(e){return!!e&&e.nodeType===YW&&Rc(e.host)}function e3(e){return e?bv(e).split(/\s+/):[]}function QS(e){var t=me==null?void 0:me.location.href;return!!(t&&e&&e.some((n=>t.match(n))))}function m1(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 e3(t)}function x9(e){return Kt(e)?null:bv(e).split(/(\s+)/).filter((t=>Gh(t))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function hp(e){var t="";return k4(e)&&!_9(e)&&e.childNodes&&e.childNodes.length&&Rn(e.childNodes,(function(n){var r;y9(n)&&n.textContent&&(t+=(r=x9(n.textContent))!==null&&r!==void 0?r:"")})),bv(t)}function JS(e){return We(e.target)?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null;var t}var t3=["a","button","form","input","select","textarea","label"];function e5(e,t){if(We(t))return!0;var n,r=function(s){if(t.some((o=>s.matches(o))))return{v:!0}};for(var i of e)if(n=r(i))return n.v;return!1}function w9(e){var t=e.parentNode;return!(!t||!Rc(t))&&t}var XW=["next","previous","prev",">","<"],t5=[".ph-no-rageclick",".ph-no-capture"],_4=e=>!e||As(e,"html")||!Rc(e),n5=(e,t)=>{if(!me||_4(e))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[e],i=e;i.parentNode&&!As(i,"body");)if(b9(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var s=w9(i);if(!s)break;if(t||t3.indexOf(s.tagName.toLowerCase())>-1)n=!0;else{var o=me.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(s),i=s}return{parentIsUsefulElement:n,targetElementList:r}};function k4(e){for(var t=e;t.parentNode&&!As(t,"body");t=t.parentNode){var n=m1(t);if(At(n,"ph-sensitive")||At(n,"ph-no-capture"))return!1}if(At(m1(e),"ph-include"))return!0;var r=e.type||"";if(Nn(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=e.name||e.id||"";return!Nn(i)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,""))}function _9(e){return!!(As(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||As(e,"select")||As(e,"textarea")||e.getAttribute("contenteditable")==="true")}var k9="(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})",QW=new RegExp("^(?:"+k9+")$"),JW=new RegExp(k9),C9="\\d{3}-?\\d{2}-?\\d{4}",eG=new RegExp("^("+C9+")$"),tG=new RegExp("("+C9+")");function Gh(e,t){return t===void 0&&(t=!0),!(Kt(e)||Nn(e)&&(e=bv(e),(t?QW:JW).test((e||"").replace(/[- ]/g,""))||(t?eG:tG).test(e)))}function r5(e){var t=hp(e);return Gh(t=(t+" "+E9(e)).trim())?t:""}function E9(e){var t="";return e&&e.childNodes&&e.childNodes.length&&Rn(e.childNodes,(function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=hp(n);t=(t+" "+i).trim(),n.childNodes&&n.childNodes.length&&(t=(t+" "+E9(n)).trim())}catch(s){Ue.error("[AutoCapture]",s)}})),t}function i5(e){return e.replace(/"|\\"/g,'\\"')}function nG(e){var t=e.attr__class;return t?sn(t)?t:e3(t):void 0}class s5{constructor(t){this.disabled=t===!1;var n=Yn(t)?t:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(t,n,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(t-i.x)+Math.abs(n-i.y)<this.thresholdPx&&this.timeoutMs>r-i.timestamp){if(this.clicks.push({x:t,y:n,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:t,y:n,timestamp:r}];return!1}}var Rb="$copy_autocapture",Mb=Ln("[AutoCapture]");function $b(e,t){return t.length>e?t.slice(0,e)+"...":t}function rG(e){if(e.previousElementSibling)return e.previousElementSibling;var t=e;do t=t.previousSibling;while(t&&!Rc(t));return t}function iG(e,t){var n,r,{e:i,maskAllElementAttributes:s,maskAllText:o,elementAttributeIgnoreList:a,elementsChainAsString:l}=t;if(!Rc(e))return{props:{}};for(var u=[e],f=e;f.parentNode&&!As(f,"body");)if(b9(f.parentNode))u.push(f.parentNode.host),f=f.parentNode.host;else{if(!Rc(f.parentNode))break;u.push(f.parentNode),f=f.parentNode}var p,m,g=[],b={},x=!1,k=!1;if(Rn(u,(R=>{var P=k4(R);if(As(R,"a")){var I=R.getAttribute("href");x=P&&!!I&&Gh(I)&&I}At(m1(R),"ph-no-capture")&&(k=!0),g.push((function(L,M,D,O){var F=L.tagName.toLowerCase(),Z={tag_name:F};t3.indexOf(F)>-1&&!D&&(Z.$el_text=F.toLowerCase()==="a"||F.toLowerCase()==="button"?$b(1024,r5(L)):$b(1024,hp(L)));var V=m1(L);V.length>0&&(Z.classes=V.filter((function(G){return G!==""}))),Rn(L.attributes,(function(G){var j;if((!_9(L)||["name","id","class","aria-label"].indexOf(G.name)!==-1)&&(O==null||!O.includes(G.name))&&!M&&Gh(G.value)&&(!Nn(j=G.name)||j.substring(0,10)!=="_ngcontent"&&j.substring(0,7)!=="_nghost")){var H=G.value;G.name==="class"&&(H=e3(H).join(" ")),Z["attr__"+G.name]=$b(1024,H)}}));for(var U=1,K=1,W=L;W=rG(W);)U++,W.tagName===L.tagName&&K++;return Z.nth_child=U,Z.nth_of_type=K,Z})(R,s,o,a));var T=(function(L){if(!k4(L))return{};var M={};return Rn(L.attributes,(function(D){if(D.name&&D.name.indexOf("data-ph-capture-attribute")===0){var O=D.name.replace("data-ph-capture-attribute-",""),F=D.value;O&&F&&Gh(F)&&(M[O]=F)}})),M})(R);qn(b,T)})),k)return{props:{},explicitNoCapture:k};if(o||(g[0].$el_text=As(e,"a")||As(e,"button")?r5(e):hp(e)),x){var w,C;g[0].attr__href=x;var E=(w=u1(x))==null?void 0:w.host,A=me==null||(C=me.location)==null?void 0:C.host;E&&A&&E!==A&&(p=x)}return{props:qn({$event_type:i.type,$ce_version:1},l?{}:{$elements:g},{$elements_chain:(m=g,(function(R){return R.map((P=>{var I,T,L="";if(P.tag_name&&(L+=P.tag_name),P.attr_class)for(var M of(P.attr_class.sort(),P.attr_class))L+="."+M.replace(/"/g,"");var D=Oe({},P.text?{text:P.text}:{},{"nth-child":(I=P.nth_child)!==null&&I!==void 0?I:0,"nth-of-type":(T=P.nth_of_type)!==null&&T!==void 0?T:0},P.href?{href:P.href}:{},P.attr_id?{attr_id:P.attr_id}:{},P.attributes),O={};return wg(D).sort(((F,Z)=>{var[V]=F,[U]=Z;return V.localeCompare(U)})).forEach((F=>{var[Z,V]=F;return O[i5(Z.toString())]=i5(V.toString())})),(L+=":")+wg(O).map((F=>{var[Z,V]=F;return Z+'="'+V+'"'})).join("")})).join(";")})((function(R){return R.map((P=>{var I,T,L={text:(I=P.$el_text)==null?void 0:I.slice(0,400),tag_name:P.tag_name,href:(T=P.attr__href)==null?void 0:T.slice(0,2048),attr_class:nG(P),attr_id:P.attr__id,nth_child:P.nth_child,nth_of_type:P.nth_of_type,attributes:{}};return wg(P).filter((M=>{var[D]=M;return D.indexOf("attr__")===0})).forEach((M=>{var[D,O]=M;return L.attributes[D]=O})),L}))})(m)))},(n=g[0])!=null&&n.$el_text?{$el_text:(r=g[0])==null?void 0:r.$el_text}:{},p&&i.type==="click"?{$external_click_url:p}:{},b)}}var ah=Ln("[ExceptionAutocapture]");function o5(e,t,n){try{if(!(t in e))return()=>{};var r=e[t],i=n(r);return zo(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),e[t]=i,()=>{e[t]===i&&(e[t]=r)}}catch{return()=>{}}}var sG=Ln("[TracingHeaders]"),Gl=Ln("[Web Vitals]"),a5=9e5,l5="disabled",c5="lazy_loading",lh="awaiting_config",Pm="missing_config";Ln("[SessionRecording]"),Ln("[SessionRecording]");var C4="[SessionRecording]",$o=Ln(C4),oG=Ln("[Heatmaps]");function u5(e){return Yn(e)&&"clientX"in e&&"clientY"in e&&Hi(e.clientX)&&Hi(e.clientY)}var d5=Ln("[Product Tours]"),aG=["$set_once","$set"],Na=Ln("[SiteApps]"),f5="Error while initializing PostHog app with config id ";function Su(e,t,n){if(Kt(e))return!1;switch(n){case"exact":return e===t;case"contains":var r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(e);case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}class lG{constructor(t){this.xn=new J8,this.Sn=(n,r)=>this.kn(n,r)&&this.Cn(n,r)&&this.In(n,r)&&this.Tn(n,r),this.kn=(n,r)=>r==null||!r.event||(n==null?void 0:n.event)===(r==null?void 0:r.event),this._instance=t,this.En=new Set,this.Mn=new Set}init(){var t,n;We((t=this._instance)==null?void 0:t._addCaptureHook)||(n=this._instance)==null||n._addCaptureHook(((r,i)=>{this.on(r,i)}))}register(t){var n,r;if(!We((n=this._instance)==null?void 0:n._addCaptureHook)&&(t.forEach((o=>{var a,l;(a=this.Mn)==null||a.add(o),(l=o.steps)==null||l.forEach((u=>{var f;(f=this.En)==null||f.add((u==null?void 0:u.event)||"")}))})),(r=this._instance)!=null&&r.autocapture)){var i,s=new Set;t.forEach((o=>{var a;(a=o.steps)==null||a.forEach((l=>{l!=null&&l.selector&&s.add(l==null?void 0:l.selector)}))})),(i=this._instance)==null||i.autocapture.setElementSelectors(s)}}on(t,n){var r;n!=null&&t.length!=0&&(this.En.has(t)||this.En.has(n==null?void 0:n.event))&&this.Mn&&((r=this.Mn)==null?void 0:r.size)>0&&this.Mn.forEach((i=>{this.Rn(n,i)&&this.xn.emit("actionCaptured",i.name)}))}Pn(t){this.onAction("actionCaptured",(n=>t(n)))}Rn(t,n){if((n==null?void 0:n.steps)==null)return!1;for(var r of n.steps)if(this.Sn(t,r))return!0;return!1}onAction(t,n){return this.xn.on(t,n)}Cn(t,n){if(n!=null&&n.url){var r,i=t==null||(r=t.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!Su(i,n.url,n.url_matching||"contains"))return!1}return!0}In(t,n){return!!this.On(t,n)&&!!this.Ln(t,n)&&!!this.Fn(t,n)}On(t,n){var r;if(n==null||!n.href)return!0;var i=this.An(t);if(i.length>0)return i.some((a=>Su(a.href,n.href,n.href_matching||"exact")));var s,o=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!o&&Su((s=o.match(/(?::|")href="(.*?)"/))?s[1]:"",n.href,n.href_matching||"exact")}Ln(t,n){var r;if(n==null||!n.text)return!0;var i=this.An(t);if(i.length>0)return i.some((u=>Su(u.text,n.text,n.text_matching||"exact")||Su(u.$el_text,n.text,n.text_matching||"exact")));var s,o,a,l=(t==null||(r=t.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(s=(function(u){for(var f,p=[],m=/(?::|")text="(.*?)"/g;!Kt(f=m.exec(u));)p.includes(f[1])||p.push(f[1]);return p})(l),o=n.text,a=n.text_matching||"exact",s.some((u=>Su(u,o,a))))}Fn(t,n){var r,i;if(n==null||!n.selector)return!0;var s=t==null||(r=t.properties)==null?void 0:r.$element_selectors;if(s!=null&&s.includes(n.selector))return!0;var o=(t==null||(i=t.properties)==null?void 0:i.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}An(t){var n;return(t==null||(n=t.properties)==null?void 0:n.$elements)==null?[]:t==null?void 0:t.properties.$elements}Tn(t,n){return n==null||!n.properties||n.properties.length===0||m9(n.properties.reduce(((r,i)=>{var s=sn(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:s,operator:i.operator||"exact"},r}),{}),t==null?void 0:t.properties)}}class cG{constructor(t){this._instance=t,this.Nn=new Map,this.Dn=new Map,this.$n=new Map}qn(t,n){return!!t&&m9(t.propertyFilters,n==null?void 0:n.properties)}jn(t,n){var r=new Map;return t.forEach((i=>{var s;(s=i.conditions)==null||(s=s[n])==null||(s=s.values)==null||s.forEach((o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}}))})),r}Hn(t,n,r){var i=(r===nh.Activation?this.Nn:this.Dn).get(t),s=[];return this.Un((o=>{s=o.filter((a=>i==null?void 0:i.includes(a.id)))})),s.filter((o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((u=>u.name===t));return this.qn(l,n)}))}register(t){var n;We((n=this._instance)==null?void 0:n._addCaptureHook)||(this.Bn(t),this.zn(t))}zn(t){var n=t.filter((r=>{var i,s;return((i=r.conditions)==null?void 0:i.actions)&&((s=r.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0}));n.length!==0&&(this.Vn==null&&(this.Vn=new lG(this._instance),this.Vn.init(),this.Vn.Pn((r=>{this.onAction(r)}))),n.forEach((r=>{var i,s,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(s=r.conditions)!=null&&(s=s.actions)!=null&&s.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Vn)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((u=>{if(u&&u.name){var f=this.$n.get(u.name);f&&f.push(r.id),this.$n.set(u.name,f||[r.id])}})))})))}Bn(t){var n,r=t.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.events)&&((a=s.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),i=t.filter((s=>{var o,a;return((o=s.conditions)==null?void 0:o.cancelEvents)&&((a=s.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));r.length===0&&i.length===0||((n=this._instance)==null||n._addCaptureHook(((s,o)=>{this.onEvent(s,o)})),this.Nn=this.jn(t,nh.Activation),this.Dn=this.jn(t,nh.Cancellation))}onEvent(t,n){var r,i=this.le(),s=this.Wn(),o=this.Zn(),a=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[s])||[];if(o===t&&n&&a.length>0){var l,u;i.info("event matched, removing item from activated items",{event:t,eventPayload:n,existingActivatedItems:a});var f=(n==null||(l=n.properties)==null?void 0:l.$survey_id)||(n==null||(u=n.properties)==null?void 0:u.$product_tour_id);if(f){var p=a.indexOf(f);0>p||(a.splice(p,1),this.Gn(a))}}else{if(this.Dn.has(t)){var m=this.Hn(t,n,nh.Cancellation);m.length>0&&(i.info("cancel event matched, cancelling items",{event:t,itemsToCancel:m.map((b=>b.id))}),m.forEach((b=>{var x=a.indexOf(b.id);0>x||a.splice(x,1),this.Qn(b.id)})),this.Gn(a))}if(this.Nn.has(t)){i.info("event name matched",{event:t,eventPayload:n,items:this.Nn.get(t)});var g=this.Hn(t,n,nh.Activation);this.Gn(a.concat(g.map((b=>b.id))||[]))}}}onAction(t){var n,r=this.Wn(),i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[r])||[];this.$n.has(t)&&this.Gn(i.concat(this.$n.get(t)||[]))}Gn(t){var n=this.le(),r=[...new Set(t)].filter((i=>!this.Jn(i)));n.info("updating activated items",{activatedItems:r}),this.Kn(r)}getActivatedIds(){var t,n=this.Wn();return((t=this._instance)==null||(t=t.persistence)==null?void 0:t.props[n])||[]}getEventToItemsMap(){return this.Nn}Yn(){return this.Vn}}class uG extends cG{constructor(t){super(t)}Wn(){return o4}Zn(){return Ih.SHOWN}Un(t){var n;(n=this._instance)==null||n.getSurveys(t)}Qn(t){var n;(n=this._instance)==null||n.cancelPendingSurvey(t)}le(){return bn}Kn(t){var n;(n=this._instance)==null||(n=n.persistence)==null||n.register({[o4]:t})}Jn(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Db="SDK is not enabled or survey functionality is not yet loaded",h5="Disabled. Not loading surveys.",dG=me!=null&&me.location?d1(me.location.hash,"__posthog")||d1(location.hash,"state"):null,p5="_postHogToolbarParams",m5=Ln("[Toolbar]"),Sr=Ln("[FeatureFlags]"),ql=Ln("[FeatureFlags]",{debugEnabled:!0}),Nb=`" failed. Feature flags didn't load in time.`,g5=e=>{for(var t={},n=0;e.length>n;n++)t[e[n]]=!0;return t},v5=e=>{var t={};for(var[n,r]of wg(e||{}))r&&(t[n]=r);return t},Do=Ln("[Error tracking]"),y5="Refusing to render web experiment since the viewer is a likely bot",fG={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&&p1(t.href,e),not_regex:(e,t)=>!!me&&!p1(t.href,e),exact:(e,t)=>t.href===e,is_not:(e,t)=>t.href!==e};class Vr{get qt(){return this._instance.config}constructor(t){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments((i=>{Vr.Xn("retrieved web experiments from the server"),n.es=new Map,i.forEach((s=>{if(s.feature_flag_key){var o;n.es&&(Vr.Xn("setting flag key ",s.feature_flag_key," to web experiment ",s),(o=n.es)==null||o.set(s.feature_flag_key,s));var a=n._instance.getFeatureFlag(s.feature_flag_key);Nn(a)&&s.variants[a]&&n.ts(s.name,a,s.variants[a].transforms)}else if(s.variants)for(var l in s.variants){var u=s.variants[l];Vr.rs(u)&&n.ts(s.name,l,u.transforms)}}))}),r)},this._instance=t,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}initialize(){}onFeatureFlags(t){if(this._is_bot())Vr.Xn(y5);else if(!this.qt.disable_web_experiments){if(Kt(this.es))return this.es=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Vr.Xn("applying feature flags",t),t.forEach((n=>{var r;if(this.es&&(r=this.es)!=null&&r.has(n)){var i,s=this._instance.getFeatureFlag(n),o=(i=this.es)==null?void 0:i.get(n);s&&o!=null&&o.variants[s]&&this.ts(o.name,s,o.variants[s].transforms)}}))}}previewWebExperiment(){var t=Vr.getWindowLocation();if(t!=null&&t.search){var n=up(t==null?void 0:t.search,"__experiment_id"),r=up(t==null?void 0:t.search,"__experiment_variant");n&&r&&(Vr.Xn("previewing web experiments "+n+" && "+r),this.getWebExperiments((i=>{this.ns(parseInt(n),r,i)}),!1,!0))}}loadIfEnabled(){this.qt.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,n,r){if(this.qt.disable_web_experiments&&!r)return t([]);var i=this._instance.get_property("$web_experiments");if(i&&!n)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.qt.token),method:"GET",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}ns(t,n,r){var i=r.filter((s=>s.id===t));i&&i.length>0&&(Vr.Xn("Previewing web experiment ["+i[0].name+"] with variant ["+n+"]"),this.ts(i[0].name,n,i[0].variants[n].transforms))}static rs(t){return!Kt(t.conditions)&&Vr.ss(t)&&Vr.os(t)}static ss(t){var n;if(Kt(t.conditions)||Kt((n=t.conditions)==null?void 0:n.url))return!0;var r,i,s,o=Vr.getWindowLocation();return!!o&&((r=t.conditions)==null||!r.url||fG[(i=(s=t.conditions)==null?void 0:s.urlMatchType)!==null&&i!==void 0?i:"icontains"](t.conditions.url,o))}static getWindowLocation(){return me==null?void 0:me.location}static os(t){var n;if(Kt(t.conditions)||Kt((n=t.conditions)==null?void 0:n.utm))return!0;var r=JM();if(r.utm_source){var i,s,o,a,l,u,f,p,m=(i=t.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((s=t.conditions)==null||(s=s.utm)==null?void 0:s.utm_campaign)==r.utm_campaign,g=(o=t.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=t.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,b=(l=t.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=t.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,x=(f=t.conditions)==null||(f=f.utm)==null||!f.utm_term||((p=t.conditions)==null||(p=p.utm)==null?void 0:p.utm_term)==r.utm_term;return m&&b&&x&&g}return!1}static Xn(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;n>i;i++)r[i-1]=arguments[i];Ue.info("[WebExperiments] "+t,r)}ts(t,n,r){this._is_bot()?Vr.Xn(y5):n!=="control"?r.forEach((i=>{if(i.selector){var s;Vr.Xn("applying transform of variant "+n+" for experiment "+t+" ",i);var o=(s=document)==null?void 0:s.querySelectorAll(i.selector);o==null||o.forEach((a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)}))}})):Vr.Xn("Control variants leave the page unmodified.")}_is_bot(){return Ni&&this._instance?h9(Ni,this.qt.custom_blocked_useragents):void 0}}var Ki=Ln("[Conversations]"),Kl="Conversations not available yet.",_v={featureFlags:class{constructor(e){this.us=!1,this.ls=!1,this.hs=!1,this.cs=!1,this.ds=!1,this.vs=!1,this.fs=!1,this.ps=!1,this._instance=e,this.featureFlagEventHandlers=[]}get qt(){return this._instance.config}get ui(){return this._instance.persistence}gs(e){return this._instance.get_property(e)}ys(){var e,t;return(e=(t=this.ui)==null?void 0:t.Sr(this.qt.feature_flag_cache_ttl_ms))!==null&&e!==void 0&&e}bs(){return!!this.ys()&&(this.ps||this.hs||(this.ps=!0,Sr.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}_s(){var e,t=(e=this.qt.evaluation_contexts)!==null&&e!==void 0?e:this.qt.evaluation_environments;return!this.qt.evaluation_environments||this.qt.evaluation_contexts||this.fs||(Sr.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.fs=!0),t!=null&&t.length?t.filter((n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||Sr.error("Invalid evaluation context found:",n,"Expected non-empty string"),r})):[]}ws(){return this._s().length>0}xs(){var e=this.qt.flag_keys;if(!We(e)){if(sn(e))return e.filter((t=>{var n=t&&typeof t=="string"&&t.trim().length>0;return n||Sr.error("Invalid flag key found:",t,"Expected non-empty string"),n}));Sr.error("Invalid flag_keys found:",e,"Expected array of non-empty strings")}}initialize(){var e,t,{config:n}=this._instance,r=(e=(t=n.bootstrap)==null?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(r).length){var i,s,o=(i=(s=n.bootstrap)==null?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter((u=>!!r[u])).reduce(((u,f)=>(u[f]=r[f]||!1,u)),{}),l=Object.keys(o).filter((u=>a[u])).reduce(((u,f)=>(o[f]&&(u[f]=o[f]),u)),{});this.receivedFeatureFlags({featureFlags:a,featureFlagPayloads:l})}}updateFlags(e,t,n){var r=n!=null&&n.merge?this.getFlagVariants():{},i=n!=null&&n.merge?this.getFlagPayloads():{},s=Oe({},r,e),o=Oe({},i,t),a={};for(var[l,u]of Object.entries(s)){var f=typeof u=="string";a[l]={key:l,enabled:!!f||!!u,variant:f?u:void 0,reason:void 0,metadata:We(o==null?void 0:o[l])?void 0:{id:0,version:void 0,description:void 0,payload:o[l]}}}this.receivedFeatureFlags({flags:a})}get hasLoadedFlags(){return this.ls}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this.gs(n4),t=this.gs(Oo),n=this.gs(zu);if(!n&&!t)return e||{};var r=qn({},e||{}),i=[...new Set([...Object.keys(n||{}),...Object.keys(t||{})])];for(var s of i){var o,a,l=r[s],u=t==null?void 0:t[s],f=We(u)?(o=l==null?void 0:l.enabled)!==null&&o!==void 0&&o:!!u,p=We(u)?l.variant:typeof u=="string"?u:void 0,m=n==null?void 0:n[s],g=Oe({},l,{enabled:f,variant:f?p??(l==null?void 0:l.variant):void 0});f!==(l==null?void 0:l.enabled)&&(g.original_enabled=l==null?void 0:l.enabled),p!==(l==null?void 0:l.variant)&&(g.original_variant=l==null?void 0:l.variant),m&&(g.metadata=Oe({},l==null?void 0:l.metadata,{payload:m,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[s]=g}return this.us||(Sr.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:n,finalDetails:r}),this.us=!0),r}getFlagVariants(){var e=this.gs(Xu),t=this.gs(Oo);if(!t)return e||{};for(var n=qn({},e),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.us||(Sr.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:n}),this.us=!0),n}getFlagPayloads(){var e=this.gs(r4),t=this.gs(zu);if(!t)return e||{};for(var n=qn({},e||{}),r=Object.keys(t),i=0;r.length>i;i++)n[r[i]]=t[r[i]];return this.us||(Sr.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:n}),this.us=!0),n}reloadFeatureFlags(){this.cs||this.qt.advanced_disable_feature_flags||this.Ss||(this._instance.Ui.emit("featureFlagsReloading",!0),this.Ss=setTimeout((()=>{this.ks()}),5))}Cs(){clearTimeout(this.Ss),this.Ss=void 0}ensureFlagsLoaded(){this.ls||this.hs||this.Ss||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.cs=e}ks(e){var t;if(this.Cs(),!this._instance.Dr())if(this.hs)this.ds=!0;else{var n=this.qt.token,r=this.gs(r1),i={token:n,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:Oe({},((t=this.ui)==null?void 0:t.get_initial_props())||{},this.gs(Ph)||{}),group_properties:this.gs(nc),timezone:s9()};es(r)||We(r)||(i.$device_id=r),(e!=null&&e.disableFlags||this.qt.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.ws()&&(i.evaluation_contexts=this._s());var s=this.xs();We(s)||(i.flag_keys=s);var o=!!this.qt.advanced_only_evaluate_survey_feature_flags,a=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+(this.qt.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":""));this.hs=!0,this._instance._send_request({method:"POST",url:a,data:i,compression:this.qt.disable_compression?void 0:no.Base64,timeout:this.qt.feature_flag_request_timeout_ms,callback:l=>{var u,f,p,m=!0;if(l.statusCode===200&&(this.ds||(this.$anon_distinct_id=void 0),m=!1),this.hs=!1,!i.disable_flags||this.ds){this.vs=!m;var g=[];l.error?l.error instanceof Error?g.push(l.error.name==="AbortError"?"timeout":"connection_error"):g.push("unknown_error"):l.statusCode!==200&&g.push("api_error_"+l.statusCode),(u=l.json)!=null&&u.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var b,x=!((f=l.json)==null||(f=f.quotaLimited)==null||!f.includes("feature_flags"));x&&g.push("quota_limited"),(p=this.ui)==null||p.register({[l4]:g}),x?Sr.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."):(i.disable_flags||this.receivedFeatureFlags((b=l.json)!==null&&b!==void 0?b:{},m,{partialResponse:o}),this.ds&&(this.ds=!1,this.ks()))}}})}}getFeatureFlag(e,t){var n;if(t===void 0&&(t={}),!t.fresh||this.vs)if(this.ls||this.getFlags()&&this.getFlags().length>0){if(!this.bs()){var r=this.getFeatureFlagResult(e,t);return(n=r==null?void 0:r.variant)!==null&&n!==void 0?n:r==null?void 0:r.enabled}}else Sr.warn('getFeatureFlag for key "'+e+Nb)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){var t=this.getFeatureFlagResult(e,{send_event:!1});return t==null?void 0:t.payload}getFeatureFlagResult(e,t){if(t===void 0&&(t={}),!t.fresh||this.vs)if(this.ls||this.getFlags()&&this.getFlags().length>0){if(!this.bs()){var n=this.getFlagVariants(),r=e in n,i=n[e],s=this.getFlagPayloads()[e],o=String(i),a=this.gs(i4)||void 0,l=this.gs(i1)||void 0,u=this.gs(Uh)||{};if(this.qt.advanced_feature_flags_dedup_per_session){var f,p=this._instance.get_session_id(),m=this.gs(a4);p&&p!==m&&(u={},(f=this.ui)==null||f.register({[Uh]:u,[a4]:p}))}if((t.send_event||!("send_event"in t))&&(!(e in u)||!u[e].includes(o))){var g,b,x,k,w,C,E,A,R,P;sn(u[e])?u[e].push(o):u[e]=[o],(g=this.ui)==null||g.register({[Uh]:u});var I=this.getFeatureFlagDetails(e),T=[...(b=this.gs(l4))!==null&&b!==void 0?b:[]];We(i)&&T.push("flag_missing");var L={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:l,$feature_flag_bootstrapped_response:((x=this.qt.bootstrap)==null||(x=x.featureFlags)==null?void 0:x[e])||null,$feature_flag_bootstrapped_payload:((k=this.qt.bootstrap)==null||(k=k.featureFlagPayloads)==null?void 0:k[e])||null,$used_bootstrap_value:!this.vs};We(I==null||(w=I.metadata)==null?void 0:w.version)||(L.$feature_flag_version=I.metadata.version);var M,D=(C=I==null||(E=I.reason)==null?void 0:E.description)!==null&&C!==void 0?C:I==null||(A=I.reason)==null?void 0:A.code;D&&(L.$feature_flag_reason=D),I!=null&&(R=I.metadata)!=null&&R.id&&(L.$feature_flag_id=I.metadata.id),We(I==null?void 0:I.original_variant)&&We(I==null?void 0:I.original_enabled)||(L.$feature_flag_original_response=We(I.original_variant)?I.original_enabled:I.original_variant),I!=null&&(P=I.metadata)!=null&&P.original_payload&&(L.$feature_flag_original_payload=I==null||(M=I.metadata)==null?void 0:M.original_payload),T.length&&(L.$feature_flag_error=T.join(",")),this._instance.capture("$feature_flag_called",L)}if(r){var O=s;if(!We(s))try{O=JSON.parse(s)}catch{}return{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:O}}}}else Sr.warn('getFeatureFlagResult for key "'+e+Nb)}getRemoteConfigPayload(e,t){var n=this.qt.token,r={distinct_id:this._instance.get_distinct_id(),token:n};this.ws()&&(r.evaluation_contexts=this._s());var i=this.xs();We(i)||(r.flag_keys=i),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:r,compression:this.qt.disable_compression?void 0:no.Base64,timeout:this.qt.feature_flag_request_timeout_ms,callback(s){var o,a=(o=s.json)==null?void 0:o.featureFlagPayloads;t((a==null?void 0:a[e])||void 0)}})}isFeatureEnabled(e,t){if(t===void 0&&(t={}),!t.fresh||this.vs){if(this.ls||this.getFlags()&&this.getFlags().length>0){var n=this.getFeatureFlag(e,t);return We(n)?void 0:!!n}Sr.warn('isFeatureEnabled for key "'+e+Nb)}}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((t=>t!==e))}receivedFeatureFlags(e,t,n){if(this.ui){this.ls=!0;var r=this.getFlagVariants(),i=this.getFlagPayloads(),s=this.getFlagsWithDetails();(function(o,a,l,u,f,p){l===void 0&&(l={}),u===void 0&&(u={}),f===void 0&&(f={});var m=(T=>{var L=T.flags;return L?(T.featureFlags=Object.fromEntries(Object.keys(L).map((M=>{var D;return[M,(D=L[M].variant)!==null&&D!==void 0?D:L[M].enabled]}))),T.featureFlagPayloads=Object.fromEntries(Object.keys(L).filter((M=>L[M].enabled)).filter((M=>{var D;return(D=L[M].metadata)==null?void 0:D.payload})).map((M=>{var D;return[M,(D=L[M].metadata)==null?void 0:D.payload]})))):Sr.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),T})(o),g=m.flags,b=m.featureFlags,x=m.featureFlagPayloads;if(b){var k=o.requestId,w=o.evaluatedAt;if(sn(b)){Sr.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var C={};if(b)for(var E=0;b.length>E;E++)C[b[E]]=!0;a&&a.register({[bg]:b,[Xu]:C})}else{var A=b,R=x,P=g;if(p!=null&&p.partialResponse)A=Oe({},l,A),R=Oe({},u,R),P=Oe({},f,P);else if(o.errorsWhileComputingFlags)if(g){var I=new Set(Object.keys(g).filter((T=>{var L;return!((L=g[T])!=null&&L.failed)})));A=Oe({},l,Object.fromEntries(Object.entries(A).filter((T=>{var[L]=T;return I.has(L)})))),R=Oe({},u,Object.fromEntries(Object.entries(R||{}).filter((T=>{var[L]=T;return I.has(L)})))),P=Oe({},f,Object.fromEntries(Object.entries(P||{}).filter((T=>{var[L]=T;return I.has(L)}))))}else A=Oe({},l,A),R=Oe({},u,R),P=Oe({},f,P);a&&a.register(Oe({[bg]:Object.keys(v5(A)),[Xu]:A||{},[r4]:R||{},[n4]:P||{}},k?{[i4]:k}:{},w?{[i1]:w}:{}))}}})(e,this.ui,r,i,s,n),t||(this.ps=!1),this.Is(t)}}override(e,t){t===void 0&&(t=!1),Sr.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this.ui)return Sr.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this.ui.unregister(Oo),this.ui.unregister(zu),this.Is(),ql.info("All overrides cleared");if(sn(e)){var t=g5(e);return this.ui.register({[Oo]:t}),this.Is(),ql.info("Flag overrides set",{flags:e})}if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.us=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this.ui.unregister(Oo),ql.info("Flag overrides cleared");else if(r.flags){if(sn(r.flags)){var i=g5(r.flags);this.ui.register({[Oo]:i})}else this.ui.register({[Oo]:r.flags});ql.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this.ui.unregister(zu),ql.info("Payload overrides cleared")):r.payloads&&(this.ui.register({[zu]:r.payloads}),ql.info("Payload overrides set",{payloads:r.payloads}))),void this.Is()}if(e&&typeof e=="object")return this.ui.register({[Oo]:e}),this.Is(),ql.info("Flag overrides set",{flags:e});Sr.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ls){var{flags:t,flagVariants:n}=this.Ts();e(t,n)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,n){var r,i=(this.gs(Th)||[]).find((l=>l.flagKey===e)),s={["$feature_enrollment/"+e]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),n&&(o.$feature_enrollment_stage=n),this._instance.capture("$feature_enrollment_update",o),this.setPersonPropertiesForFlags(s,!1);var a=Oe({},this.getFlagVariants(),{[e]:t});(r=this.ui)==null||r.register({[bg]:Object.keys(v5(a)),[Xu]:a}),this.Is()}getEarlyAccessFeatures(e,t,n){t===void 0&&(t=!1);var r=this.gs(Th),i=n?"&"+n.map((s=>"stage="+s)).join("&"):"";if(r&&!t)return e(r);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this.qt.token+i),method:"GET",callback:s=>{var o,a;if(s.json){var l=s.json.earlyAccessFeatures;return(o=this.ui)==null||o.unregister(Th),(a=this.ui)==null||a.register({[Th]:l}),e(l)}}})}Ts(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter((n=>t[n])),flagVariants:Object.keys(t).filter((n=>t[n])).reduce(((n,r)=>(n[r]=t[r],n)),{})}}Is(e){var{flags:t,flagVariants:n}=this.Ts();this.featureFlagEventHandlers.forEach((r=>r(t,n,{errorsLoading:e})))}setPersonPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.gs(Ph)||{},r=(e==null?void 0:e.$set)||(e!=null&&e.$set_once?{}:e),i=e==null?void 0:e.$set_once,s={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in n||(s[o]=i[o]));this._instance.register({[Ph]:Oe({},n,s,r)}),t&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Ph)}setGroupPropertiesForFlags(e,t){t===void 0&&(t=!0);var n=this.gs(nc)||{};Object.keys(n).length!==0&&Object.keys(n).forEach((r=>{n[r]=Oe({},n[r],e[r]),delete e[r]})),this._instance.register({[nc]:Oe({},n,e)}),t&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var t=this.gs(nc)||{};this._instance.register({[nc]:Oe({},t,{[e]:{}})})}else this._instance.unregister(nc)}reset(){this.ls=!1,this.hs=!1,this.cs=!1,this.ds=!1,this.vs=!1,this.$anon_distinct_id=void 0,this.Cs(),this.us=!1}}},hG={sessionRecording:class{get qt(){return this._instance.config}get ui(){return this._instance.persistence}get started(){var e;return!((e=this.Es)==null||!e.isStarted)}get status(){var e,t;return this.Ms===lh||this.Ms===Pm?this.Ms:(e=(t=this.Es)==null?void 0:t.status)!==null&&e!==void 0?e:this.Ms}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ms=l5,this.Rs=void 0,this._instance=e,!this._instance.sessionManager)throw $o.error("started without valid sessionManager"),new Error(C4+" started without valid sessionManager. This is a bug.");if(this.qt.cookieless_mode===Go)throw new Error(C4+' cannot be used with cookieless_mode="always"')}initialize(){this.startIfEnabledOrStop()}get Ps(){var e,t=!((e=this._instance.get_property(lc))==null||!e.enabled),n=!this.qt.disable_session_recording,r=this.qt.disable_session_recording||this._instance.consent.isOptedOut();return me&&t&&n&&!r}startIfEnabledOrStop(e){var t;if(!this.Ps||(t=this.Es)==null||!t.isStarted){var n=!We(Object.assign)&&!We(Array.from);this.Ps&&n?(this.Os(e),$o.info("starting")):(this.Ms=l5,this.stopRecording())}}Os(e){var t,n,r;this.Ps&&(this.Ms!==lh&&this.Ms!==Pm&&(this.Ms=c5),gt!=null&&(t=gt.__PosthogExtensions__)!=null&&(t=t.rrweb)!=null&&t.record&&(n=gt.__PosthogExtensions__)!=null&&n.initSessionRecording?this.Ls(e):(r=gt.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.Fs,(i=>{if(i)return $o.error("could not load recorder",i);this.Ls(e)})))}stopRecording(){var e,t;(e=this.Rs)==null||e.call(this),this.Rs=void 0,(t=this.Es)==null||t.stop()}As(){var e,t;(e=this.Rs)==null||e.call(this),this.Rs=void 0,(t=this.Es)==null||t.discard()}Ns(){var e;(e=this.ui)==null||e.unregister(q8)}Ds(e,t){if(Kt(e))return null;var n,r=Hi(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?($o.warn(t+" must be between 0 and 1. Ignoring invalid value:",e),null):r}$s(e){if(this.ui){var t,n,r=this.ui,i=()=>{var s,o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.Ds((s=this.qt.session_recording)==null?void 0:s.sampleRate,"session_recording.sampleRate"),l=this.Ds(o==null?void 0:o.sampleRate,"remote config sampleRate"),u=a??l;Kt(u)&&this.Ns();var f=o==null?void 0:o.minimumDurationMilliseconds;r.register({[lc]:Oe({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:Oe({capturePerformance:e.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:u,minimumDurationMilliseconds:We(f)?null:f,endpoint:o==null?void 0:o.endpoint,triggerMatchType:o==null?void 0:o.triggerMatchType,masking:o==null?void 0:o.masking,urlTriggers:o==null?void 0:o.urlTriggers,version:o==null?void 0:o.version,triggerGroups:o==null?void 0:o.triggerGroups})})};i(),(t=this.Rs)==null||t.call(this),this.Rs=(n=this._instance.sessionManager)==null?void 0:n.onSessionId(i)}}onRemoteConfig(e){return"sessionRecording"in e?e.sessionRecording===!1?(this.$s(e),void this.As()):(this.$s(e),void this.startIfEnabledOrStop()):(this.Ms===lh&&(this.Ms=Pm,$o.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(e,t){var n;t===void 0&&(t="log"),(n=this.Es)!=null&&n.log?this.Es.log(e,t):$o.warn("log called before recorder was ready")}get Fs(){var e,t,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(lc);return(n==null||(t=n.scriptConfig)==null?void 0:t.script)||"lazy-recorder"}qs(){var e,t,n=this._instance.get_property(lc);if(!n)return!1;try{t=typeof n=="object"?n:JSON.parse(n)}catch(i){return $o.warn("persisted remote config for session recording is invalid and will be ignored",i),!1}var r=(e=t.cache_timestamp)!==null&&e!==void 0?e:Date.now();return 36e5>=Date.now()-r}Ls(e){var t,n;if((t=gt.__PosthogExtensions__)==null||!t.initSessionRecording)return $o.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[qM]:!0});if(this.Es||(this.Es=(n=gt.__PosthogExtensions__)==null?void 0:n.initSessionRecording(this._instance),this.Es._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.qs())return this.Ms===Pm||this.Ms===lh?void 0:(this.Ms=lh,$o.info("persisted remote config is stale, requesting fresh config before starting"),void new o9(this._instance).load());this.Ms=c5,this.Es.start(e)}onRRwebEmit(e){var t;(t=this.Es)==null||t.onRRwebEmit==null||t.onRRwebEmit(e)}overrideLinkedFlag(){var e,t;this.Es||(t=this.ui)==null||t.register({[BM]:!0}),(e=this.Es)==null||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.Es||(t=this.ui)==null||t.register({[HM]:!0}),(e=this.Es)==null||e.overrideSampling()}overrideTrigger(e){var t,n;this.Es||(n=this.ui)==null||n.register({[e==="url"?zM:UM]:!0}),(t=this.Es)==null||t.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Es)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,t){var n;return!((n=this.Es)==null||!n.tryAddCustomEvent(e,t))}}},pG={autocapture:class{constructor(e){this.js=!1,this.Hs=null,this.Us=!1,this.instance=e,this.rageclicks=new s5(e.config.rageclick),this.Bs=null}initialize(){this.startIfEnabled()}get qt(){var e,t,n=Yn(this.instance.config.autocapture)?this.instance.config.autocapture:{};return n.url_allowlist=(e=n.url_allowlist)==null?void 0:e.map((r=>new RegExp(r))),n.url_ignorelist=(t=n.url_ignorelist)==null?void 0:t.map((r=>new RegExp(r))),n}zs(){if(this.isBrowserSupported()){if(me&&Ze){var e=n=>{n=n||(me==null?void 0:me.event);try{this.Vs(n)}catch(r){Mb.error("Failed to capture event",r)}};if(Wn(Ze,"submit",e,{capture:!0}),Wn(Ze,"change",e,{capture:!0}),Wn(Ze,"click",e,{capture:!0}),this.qt.capture_copied_text){var t=n=>{n=n||(me==null?void 0:me.event);try{this.Vs(n,Rb)}catch(r){Mb.error("Failed to capture copy/cut event",r)}};Wn(Ze,"copy",t,{capture:!0}),Wn(Ze,"cut",t,{capture:!0})}}}else Mb.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.js&&(this.zs(),this.js=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.Us=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[qw]:!!e.autocapture_opt_out}),this.Hs=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.Bs=e}getElementSelectors(e){var t,n=[];return(t=this.Bs)==null||t.forEach((r=>{var i=Ze==null?void 0:Ze.querySelectorAll(r);i==null||i.forEach((s=>{e===s&&n.push(r)}))})),n}get isEnabled(){var e,t,n=(e=this.instance.persistence)==null?void 0:e.props[qw];if(es(this.Hs)&&!oo(n)&&!this.instance.Dr())return!1;var r=(t=this.Hs)!==null&&t!==void 0?t:!!n;return!!this.instance.config.autocapture&&!r}Vs(e,t){if(t===void 0&&(t="$autocapture"),this.isEnabled){var n,r=JS(e);y9(r)&&(r=r.parentNode||null),t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&(function(p,m){if(!me||_4(p))return!1;var g,b,x;if(oo(m)?(g=!!m&&t5,b=void 0):(g=(x=m==null?void 0:m.css_selector_ignorelist)!==null&&x!==void 0?x:t5,b=m==null?void 0:m.content_ignorelist),g===!1)return!1;var{targetElementList:k}=n5(p,!1);return!(function(w,C){if(w===!1||We(w))return!1;var E;if(w===!0)E=XW;else{if(!sn(w))return!1;if(w.length>10)return Ue.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;E=w.map((A=>A.toLowerCase()))}return C.some((A=>{var{safeText:R,ariaLabel:P}=A;return E.some((I=>R.includes(I)||P.includes(I)))}))})(b,k.map((w=>{var C;return{safeText:hp(w).toLowerCase(),ariaLabel:((C=w.getAttribute("aria-label"))==null?void 0:C.toLowerCase().trim())||""}})))&&!e5(k,g)})(r,this.instance.config.rageclick)&&this.Vs(e,"$rageclick");var i=t===Rb;if(r&&(function(p,m,g,b,x){var k,w,C,E;if(g===void 0&&(g=void 0),!me||_4(p)||(k=g)!=null&&k.url_allowlist&&!QS(g.url_allowlist)||(w=g)!=null&&w.url_ignorelist&&QS(g.url_ignorelist))return!1;if((C=g)!=null&&C.dom_event_allowlist){var A=g.dom_event_allowlist;if(A&&!A.some((L=>m.type===L)))return!1}var{parentIsUsefulElement:R,targetElementList:P}=n5(p,b);if(!(function(L,M){var D=M==null?void 0:M.element_allowlist;if(We(D))return!0;var O,F=function(V){if(D.some((U=>V.tagName.toLowerCase()===U)))return{v:!0}};for(var Z of L)if(O=F(Z))return O.v;return!1})(P,g)||!e5(P,(E=g)==null?void 0:E.css_selector_allowlist))return!1;var I=me.getComputedStyle(p);if(I&&I.getPropertyValue("cursor")==="pointer"&&m.type==="click")return!0;var T=p.tagName.toLowerCase();switch(T){case"html":return!1;case"form":return(x||["submit"]).indexOf(m.type)>=0;case"input":case"select":case"textarea":return(x||["change","click"]).indexOf(m.type)>=0;default:return R?(x||["click"]).indexOf(m.type)>=0:(x||["click"]).indexOf(m.type)>=0&&(t3.indexOf(T)>-1||p.getAttribute("contenteditable")==="true")}})(r,e,this.qt,i,i?["copy","cut"]:void 0)){var{props:s,explicitNoCapture:o}=iG(r,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.qt.element_attribute_ignorelist,elementsChainAsString:this.Us});if(o)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(s.$element_selectors=a),t===Rb){var l,u=x9(me==null||(l=me.getSelection())==null?void 0:l.toString()),f=e.type||"clipboard";if(!u)return!1;s.$selected_content=u,s.$copy_type=f}return this.instance.capture(t,s),!0}}}isBrowserSupported(){return zo(Ze==null?void 0:Ze.querySelectorAll)}},historyAutocapture:class{constructor(e){var t;this._instance=e,this.Ws=(me==null||(t=me.location)==null?void 0:t.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ue.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.Zs&&this.Zs(),this.Zs=void 0,Ue.info("History API monitoring stopped")}monitorHistoryChanges(){var e,t;if(me&&me.history){var n=this;(e=me.history.pushState)!=null&&e.__posthog_wrapped__||o5(me.history,"pushState",(r=>function(i,s,o){r.call(this,i,s,o),n.Gs("pushState")})),(t=me.history.replaceState)!=null&&t.__posthog_wrapped__||o5(me.history,"replaceState",(r=>function(i,s,o){r.call(this,i,s,o),n.Gs("replaceState")})),this.Qs()}}Gs(e){try{var t,n=me==null||(t=me.location)==null?void 0:t.pathname;if(!n)return;n!==this.Ws&&this.isEnabled&&this._instance.capture(Uu,{navigation_type:e}),this.Ws=n}catch(r){Ue.error("Error capturing "+e+" pageview",r)}}Qs(){if(!this.Zs){var e=()=>{this.Gs("popstate")};Wn(me,"popstate",e),this.Zs=()=>{me&&me.removeEventListener("popstate",e)}}}},heatmaps:class{get qt(){return this.instance.config}constructor(e){var t;this.Js=!1,this.js=!1,this.Ks=null,this.instance=e,this.Js=!((t=this.instance.persistence)==null||!t.props[Kw]),this.rageclicks=new s5(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var e=5e3;return Yn(this.qt.capture_heatmaps)&&this.qt.capture_heatmaps.flush_interval_milliseconds&&(e=this.qt.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return Kt(this.qt.capture_heatmaps)?Kt(this.qt.enable_heatmaps)?this.Js:this.qt.enable_heatmaps:this.qt.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.js)return;oG.info("starting..."),this.Ys(),this.At()}else{var e;clearInterval((e=this.Ks)!==null&&e!==void 0?e:void 0),this.Xs(),this.getAndClearBuffer()}}onRemoteConfig(e){if("heatmaps"in e){var t=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Kw]:t}),this.Js=t,this.startIfEnabled()}}getAndClearBuffer(){var e=this.M;return this.M=void 0,e}eo(e){this.Mt(e.originalEvent,"deadclick")}At(){this.Ks&&clearInterval(this.Ks),this.Ks=(Ze==null?void 0:Ze.visibilityState)==="visible"?setInterval(this.Kr.bind(this),this.flushIntervalMilliseconds):null}Ys(){me&&Ze&&(this.ro=this.Kr.bind(this),Wn(me,l1,this.ro),this.io=e=>this.Mt(e||(me==null?void 0:me.event)),Wn(Ze,"click",this.io,{capture:!0}),this.no=e=>this.so(e||(me==null?void 0:me.event)),Wn(Ze,"mousemove",this.no,{capture:!0}),this.oo=new MS(this.instance,mW,this.eo.bind(this)),this.oo.startIfEnabledOrStop(),this.ao=this.At.bind(this),Wn(Ze,a1,this.ao),this.js=!0)}Xs(){var e;me&&Ze&&(this.ro&&me.removeEventListener(l1,this.ro),this.io&&Ze.removeEventListener("click",this.io,{capture:!0}),this.no&&Ze.removeEventListener("mousemove",this.no,{capture:!0}),this.ao&&Ze.removeEventListener(a1,this.ao),clearTimeout(this.uo),(e=this.oo)==null||e.stop(),this.js=!1)}lo(e,t){var n=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,l){for(var u=o;u&&Rc(u)&&!As(u,"body");){if(u===l)return!1;if(At(a,me==null?void 0:me.getComputedStyle(u).position))return!0;u=w9(u)}return!1})(JS(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:r),y:e.clientY+(s?0:n),target_fixed:s,type:t}}Mt(e,t){var n;if(t===void 0&&(t="click"),!XS(e.target)&&u5(e)){var r=this.lo(e,t);(n=this.rageclicks)!=null&&n.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.ho(Oe({},r,{type:"rageclick"})),this.ho(r)}}so(e){!XS(e.target)&&u5(e)&&(clearTimeout(this.uo),this.uo=setTimeout((()=>{this.ho(this.lo(e,"mousemove"))}),500))}ho(e){if(me){var t=me.location.href,n=this.qt.custom_personal_data_properties,r=this.qt.mask_personal_data_properties?[...Nd,...n||[]]:[],i=dp(t,r,fp);this.M=this.M||{},this.M[i]||(this.M[i]=[]),this.M[i].push(e)}}Kr(){this.M&&!Ku(this.M)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:MS,webVitalsAutocapture:class{constructor(e){var t;this.Js=!1,this.js=!1,this.M={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.co=()=>{clearTimeout(this.do),this.M.metrics.length!==0&&(this._instance.capture("$web_vitals",this.M.metrics.reduce(((n,r)=>Oe({},n,{["$web_vitals_"+r.name+"_event"]:Oe({},r),["$web_vitals_"+r.name+"_value"]:r.value})),{})),this.M={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.ht=n=>{var r;this.M=this.M||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var i=this.vo();if(!We(i))if(Kt(n==null?void 0:n.name)||Kt(n==null?void 0:n.value))Gl.error("Invalid metric received",n);else if(!this.fo||this.fo>n.value){this.M.url!==i&&(this.co(),this.do=setTimeout(this.co,this.flushToCaptureTimeoutMs)),We(this.M.url)&&(this.M.url=i),this.M.firstMetricTimestamp=We(this.M.firstMetricTimestamp)?Date.now():this.M.firstMetricTimestamp,n.attribution&&n.attribution.interactionTargetElement&&(n.attribution.interactionTargetElement=void 0);var s=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),o=Oe({},n,{$current_url:i,timestamp:Date.now()});We(s)||(o.$session_id=s.sessionId,o.$window_id=s.windowId),this.M.metrics.push(o),this.M.metrics.length===this.allowedMetrics.length&&this.co()}else Gl.error("Ignoring metric with value >= "+this.fo,n)},this.po=()=>{if(!this.js){var n,r,i,s,o=gt.__PosthogExtensions__;We(o)||We(o.postHogWebVitalsCallbacks)||({onLCP:n,onCLS:r,onFCP:i,onINP:s}=o.postHogWebVitalsCallbacks),n&&r&&i&&s?(this.allowedMetrics.indexOf("LCP")>-1&&n(this.ht.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&r(this.ht.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.ht.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&s(this.ht.bind(this)),this.js=!0):Gl.error("web vitals callbacks not loaded - not starting")}},this._instance=e,this.Js=!((t=this._instance.persistence)==null||!t.props[Jw]),this.startIfEnabled()}get mo(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t,n=Yn(this.mo)?(e=this.mo)==null?void 0:e.web_vitals_allowed_metrics:void 0;return Kt(n)?((t=this._instance.persistence)==null?void 0:t.props[t4])||["CLS","FCP","INP","LCP"]:n}get flushToCaptureTimeoutMs(){return(Yn(this.mo)?this.mo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var e=Yn(this.mo)?this.mo.web_vitals_attribution:void 0;return e!=null&&e}get fo(){var e=Yn(this.mo)&&Hi(this.mo.__web_vitals_max_value)?this.mo.__web_vitals_max_value:a5;return e>0&&6e4>=e?a5:e}get isEnabled(){var e=Pr==null?void 0:Pr.protocol;if(e!=="http:"&&e!=="https:")return Gl.info("Web Vitals are disabled on non-http/https protocols"),!1;var t=Yn(this.mo)?this.mo.web_vitals:oo(this.mo)?this.mo:void 0;return oo(t)?t:this.Js}startIfEnabled(){this.isEnabled&&!this.js&&(Gl.info("enabled, starting..."),this.lr(this.po))}onRemoteConfig(e){if("capturePerformance"in e){var t=Yn(e.capturePerformance)&&!!e.capturePerformance.web_vitals,n=Yn(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Jw]:t}),this._instance.persistence.register({[t4]:n})),this.Js=t,this.startIfEnabled()}}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.postHogWebVitalsCallbacks?e():(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,this.useAttribution?"web-vitals-with-attribution":"web-vitals",(r=>{r?Gl.error("failed to load script",r):e()}))}vo(){var e=me?me.location.href:void 0;if(e){var t=this._instance.config.custom_personal_data_properties,n=this._instance.config.mask_personal_data_properties?[...Nd,...t||[]]:[];return dp(e,n,fp)}Gl.error("Could not determine current URL")}}},mG={exceptionObserver:class{constructor(e){var t,n,r;this.po=()=>{var i;if(me&&this.isEnabled&&(i=gt.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var s=gt.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,o=gt.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,a=gt.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.yo&&this.qt.capture_unhandled_errors&&(this.yo=s(this.captureException.bind(this))),!this.bo&&this.qt.capture_unhandled_rejections&&(this.bo=o(this.captureException.bind(this))),!this._o&&this.qt.capture_console_errors&&(this._o=a(this.captureException.bind(this)))}catch(l){ah.error("failed to start",l),this.wo()}}},this._instance=e,this.xo=!((t=this._instance.persistence)==null||!t.props[Yw]),this.So=new CZ({refillRate:(n=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(r=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&r!==void 0?r:10,refillInterval:1e4,Gt:ah}),this.qt=this.ko(),this.startIfEnabledOrStop()}ko(){var e=this._instance.config.capture_exceptions,t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return Yn(e)?t=Oe({},t,e):(We(e)?this.xo:e)&&(t=Oe({},t,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.qt.capture_console_errors||this.qt.capture_unhandled_errors||this.qt.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(ah.info("enabled"),this.wo(),this.lr(this.po)):this.wo()}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.errorWrappingFunctions&&e(),(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"exception-autocapture",(r=>{if(r)return ah.error("failed to load script",r);e()}))}wo(){var e,t,n;(e=this.yo)==null||e.call(this),this.yo=void 0,(t=this.bo)==null||t.call(this),this.bo=void 0,(n=this._o)==null||n.call(this),this._o=void 0}onRemoteConfig(e){"autocaptureExceptions"in e&&(this.xo=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Yw]:this.xo}),this.qt=this.ko(),this.startIfEnabledOrStop())}onConfigChange(){this.qt=this.ko()}captureException(e){var t,n,r,i=(t=e==null||(n=e.$exception_list)==null||(n=n[0])==null?void 0:n.type)!==null&&t!==void 0?t:"Exception";this.So.consumeRateLimit(i)?ah.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(e)}},exceptions:class{constructor(e){var t,n;this.Co=[],this.Io=new jZ([new ZZ,new eW,new GZ,new WZ,new QZ,new XZ,new KZ,new JZ],(function(r){for(var i=arguments.length,s=new Array(i>1?i-1:0),o=1;i>o;o++)s[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],f=a.split(`
|
|
18
18
|
`),p=l;f.length>p;p++){var m=f[p];if(1024>=m.length){var g=TS.test(m)?m.replace(TS,"$1"):m;if(!g.match(/\S*Error: /)){for(var b of s){var x=b(g,r);if(x){u.push(x);break}}if(u.length>=50)break}}}return(function(k){if(!k.length)return[];var w=Array.from(k);return w.reverse(),w.slice(0,50).map((C=>{return Oe({},C,{filename:C.filename||(E=w,E[E.length-1]||{}).filename,function:C.function||Dd});var E}))})(u)}})("web:javascript",HZ,UZ)),this._instance=e,this.Co=(t=(n=this._instance.persistence)==null?void 0:n.get_property(Xw))!==null&&t!==void 0?t:[],this.To=n1(this.Eo()),this.Mo=new nW(this.To)}onConfigChange(){this.To=n1(this.Eo()),this.Mo.setConfig(this.To)}onRemoteConfig(e){var t,n,r;if("errorTracking"in e){var i=(t=(n=e.errorTracking)==null?void 0:n.suppressionRules)!==null&&t!==void 0?t:[],s=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Co=i,this._instance.persistence&&this._instance.persistence.register({[Xw]:this.Co,[Qw]:s})}}get Ro(){var e,t=!!this._instance.get_property(Qw),n=this._instance.config.error_tracking.captureExtensionExceptions;return(e=n??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.Io.buildFromUnknown(e,{syntheticException:t==null?void 0:t.syntheticException,mechanism:{handled:t==null?void 0:t.handled}})}addExceptionStep(e,t){if(this.To.enabled)try{if(!Nn(e)||e.trim().length===0)return void Do.warn("Ignoring exception step because message must be a non-empty string");var n=this.Po(t),{sanitizedProperties:r,droppedKeys:i}=(function(s){if(!s)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(s).reduce(((a,l)=>tW.has(l)?(o.push(l),a):(a[l]=s[l],a)),{}),droppedKeys:o}})(n);i.length>0&&Do.warn("Ignoring reserved exception step fields",{droppedKeys:i}),this.Mo.add(Oe({[e1]:e,[t1]:new Date().toISOString()},r))}catch(s){Do.error("Failed to add exception step. Ignoring breadcrumb.",s)}}sendExceptionEvent(e){try{var t=e.$exception_list;if(this.Oo(t)){if(this.Lo(t))return this.Fo("Exception dropped: matched a suppression rule"),void Do.info("Skipping exception capture because a suppression rule matched");if(!this.Ro&&this.Ao(t))return this.Fo("Exception dropped: thrown by a browser extension"),void Do.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.No(t))return this.Fo("Exception dropped: thrown by the PostHog SDK"),void Do.info("Skipping exception capture because it was thrown by the PostHog SDK")}var n=this.To.enabled&&Kt(e.$exception_steps)?this.Do(e):e;try{var r=this._instance.capture("$exception",n,{_noTruncate:!0,_batchKey:"exceptionEvent",cn:!0});return r&&this.Mo.clear(),r}catch(i){return Do.error("Failed to capture exception event. Dropping this exception.",i),void this.Mo.clear()}}catch(i){return void Do.error("Failed to process exception event. Ignoring this exception.",i)}}Do(e){try{var t=this.Mo.getAttachable();return t.length===0?e:Oe({},e,{$exception_steps:t})}catch(n){return Do.error("Failed to read buffered exception steps. Capturing exception without steps.",n),e}}Fo(e){this.To.enabled&&this.Mo.add({[e1]:e,[t1]:new Date().toISOString()})}Po(e){return Yn(e)?Oe({},e):{}}Eo(){var e,t;return(e=(t=this._instance.config.error_tracking)==null?void 0:t.exception_steps)!==null&&e!==void 0?e:{}}Lo(e){if(e.length===0)return!1;var t=e.reduce(((n,r)=>{var{type:i,value:s}=r;return Nn(i)&&i.length>0&&n.$exception_types.push(i),Nn(s)&&s.length>0&&n.$exception_values.push(s),n}),{$exception_types:[],$exception_values:[]});return this.Co.some((n=>{var r=n.values.map((i=>{var s,o=p9[i.operator],a=sn(i.value)?i.value:[i.value],l=(s=t[i.key])!==null&&s!==void 0?s:[];return a.length>0&&o(a,l)}));return n.type==="OR"?r.some(Boolean):r.every(Boolean)}))}Ao(e){return e.flatMap((t=>{var n,r;return(n=(r=t.stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[]})).some((t=>t.filename&&t.filename.startsWith("chrome-extension://")))}No(e){if(e.length>0){var t,n,r,i,s=(t=(n=e[0].stacktrace)==null?void 0:n.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}Oo(e){return!Kt(e)&&sn(e)}}},gG=Oe({productTours:class{get ui(){return this._instance.persistence}constructor(e){this.$o=null,this.qo=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){"productTours"in e&&(this.ui&&this.ui.register({[e4]:!!e.productTours}),this.loadIfEnabled())}loadIfEnabled(){var e,t;this.$o||(e=this._instance).config.disable_product_tours||(t=e.persistence)==null||!t.get_property(e4)||this.lr((()=>this.jo()))}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.generateProductTours?e():(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"product-tours",(r=>{r?d5.error("Could not load product tours script",r):e()}))}jo(){var e;!this.$o&&(e=gt.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.$o=gt.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t){if(t===void 0&&(t=!1),!sn(this.qo)||t){var n=this.ui;if(n){var r=n.props[xg];if(sn(r)&&!t)return this.qo=r,void e(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:i=>{var s=i.statusCode;if(s!==200||!i.json){var o="Product Tours API could not be loaded, status: "+s;return d5.error(o),void e([],{isLoaded:!1,error:o})}var a=sn(i.json.product_tours)?i.json.product_tours:[];this.qo=a,n&&n.register({[xg]:a}),e(a,{isLoaded:!0})}})}else e(this.qo,{isLoaded:!0})}getActiveProductTours(e){Kt(this.$o)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.$o.getActiveProductTours(e)}showProductTour(e){var t;(t=this.$o)==null||t.showTourById(e)}previewTour(e){this.$o?this.$o.previewTour(e):this.lr((()=>{var t;this.jo(),(t=this.$o)==null||t.previewTour(e)}))}dismissProductTour(){var e;(e=this.$o)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.$o)==null||e.nextStep()}previousStep(){var e;(e=this.$o)==null||e.previousStep()}clearCache(){var e;this.qo=null,(e=this.ui)==null||e.unregister(xg)}resetTour(e){var t;(t=this.$o)==null||t.resetTour(e)}resetAllTours(){var e;(e=this.$o)==null||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.$o)==null||t.cancelPendingTour(e)}}},_v),vG={siteApps:class{constructor(e){this._instance=e,this.Ho=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Uo(e,t){if(t){var n=this.globalsForEvent(t);this.Ho.push(n),this.Ho.length>1e3&&(this.Ho=this.Ho.slice(10))}}get siteAppLoaders(){var e;return(e=gt._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}initialize(){if(this.isEnabled){var e=this._instance._addCaptureHook(this.Uo.bind(this));this.Bo=()=>{e(),this.Ho=[],this.Bo=void 0}}}globalsForEvent(e){var t,n,r,i,s,o,a;if(!e)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(var[p,m]of Object.entries(f))l[p]={id:u[p],type:p,properties:m};var{$set_once:g,$set:b}=e;return{event:Oe({},dM(e,aG),{properties:Oe({},e.properties,b?{$set:Oe({},(t=(n=e.properties)==null?void 0:n.$set)!==null&&t!==void 0?t:{},b)}:{},g?{$set_once:Oe({},(r=(i=e.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},g)}:{}),elements_chain:(s=(o=e.properties)==null?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}setupSiteApp(e){var t=this.apps[e.id],n=()=>{var o;!t.errored&&this.Ho.length&&(Na.info("Processing "+this.Ho.length+" events for site app with id "+e.id),this.Ho.forEach((a=>t.processEvent==null?void 0:t.processEvent(a))),t.processedBuffer=!0),Object.values(this.apps).every((a=>a.processedBuffer||a.errored))&&((o=this.Bo)==null||o.call(this))},r=!1,i=o=>{t.errored=!o,t.loaded=!0,Na.info("Site app with id "+e.id+" "+(o?"loaded":"errored")),r&&n()};try{var{processEvent:s}=e.init({posthog:this._instance,callback(o){i(o)}});s&&(t.processEvent=s),r=!0}catch(o){Na.error(f5+e.id,o),i(!1)}if(r&&t.loaded)try{n()}catch(o){Na.error("Error while processing buffered events PostHog app with config id "+e.id,o),t.errored=!0}}zo(){var e=this.siteAppLoaders||[];for(var t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(var n of e)this.setupSiteApp(n)}Vo(e){if(Object.keys(this.apps).length!==0){var t=this.globalsForEvent(e);for(var n of Object.values(this.apps))try{n.processEvent==null||n.processEvent(t)}catch(r){Na.error("Error while processing event "+e.event+" for site app "+n.id,r)}}}onRemoteConfig(e){var t,n,r,i=this;if((t=this.siteAppLoaders)!=null&&t.length)return this.isEnabled?(this.zo(),void this._instance.on("eventCaptured",(l=>this.Vo(l)))):void Na.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((n=this.Bo)==null||n.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var s=function(l){var u;gt["__$$ph_site_app_"+l]=i._instance,(u=gt.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(i._instance,a,(f=>{if(f)return Na.error(f5+l,f)}))};for(var{id:o,url:a}of e.siteApps)s(o)}else Na.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},yG={tracingHeaders:class{constructor(e){this.Wo=void 0,this.Zo=void 0,this.po=()=>{var t,n,r=this.Go()||[];We(this.Wo)&&(this.Wo=(t=gt.__PosthogExtensions__)==null||(t=t.tracingHeadersPatchFns)==null?void 0:t._patchXHR(r,this._instance.get_distinct_id(),this._instance.sessionManager)),We(this.Zo)&&(this.Zo=(n=gt.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null?void 0:n._patchFetch(r,this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}initialize(){this.startIfEnabledOrStop()}lr(e){var t,n;(t=gt.__PosthogExtensions__)!=null&&t.tracingHeadersPatchFns?e():(n=gt.__PosthogExtensions__)==null||n.loadExternalDependency==null||n.loadExternalDependency(this._instance,"tracing-headers",(r=>{if(r)return sG.error("failed to load script",r);e()}))}Go(){var e;return(e=this._instance.config.addTracingHeaders)!==null&&e!==void 0?e:this._instance.config.__add_tracing_headers}startIfEnabledOrStop(){var e,t;this.Go()?this.lr(this.po):((e=this.Wo)==null||e.call(this),(t=this.Zo)==null||t.call(this),this.Wo=void 0,this.Zo=void 0)}}},bG=Oe({surveys:class{get qt(){return this._instance.config}constructor(e){this.Qo=void 0,this._surveyManager=null,this.Jo=!1,this.Ko=[],this.Yo=null,this._instance=e,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this.qt.disable_surveys){var t=e.surveys;if(Kt(t))return bn.warn("Flags not loaded yet. Not loading surveys.");var n=sn(t);this.Qo=n?t.length>0:t,bn.info("flags response received, isSurveysEnabled: "+this.Qo),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],t=0;t<localStorage.length;t++){var n=localStorage.key(t);(n!=null&&n.startsWith(x4)||n!=null&&n.startsWith("inProgressSurvey_"))&&e.push(n)}e.forEach((r=>localStorage.removeItem(r)))}loadIfEnabled(){if(!this._surveyManager)if(this.Jo)bn.info("Already initializing surveys, skipping...");else if(this.qt.disable_surveys)bn.info(h5);else if(this.qt.cookieless_mode&&this._instance.consent.isOptedOut())bn.info("Not loading surveys in cookieless mode without consent.");else{var e=gt==null?void 0:gt.__PosthogExtensions__;if(e){if(!We(this.Qo)||this.qt.advanced_enable_surveys){var t=this.Qo||this.qt.advanced_enable_surveys;this.Jo=!0;try{var n=e.generateSurveys;if(n)return void this.Xo(n,t);var r=e.loadExternalDependency;if(!r)return void this.ea(K8);r(this._instance,"surveys",(i=>{i||!e.generateSurveys?this.ea("Could not load surveys script",i):this.Xo(e.generateSurveys,t)}))}catch(i){throw this.ea("Error initializing surveys",i),i}finally{this.Jo=!1}}}else bn.error("PostHog Extensions not found.")}}Xo(e,t){this._surveyManager=e(this._instance,t),this._surveyEventReceiver=new uG(this._instance),bn.info("Surveys loaded successfully"),this.ta({isLoaded:!0})}ea(e,t){bn.error(e,t),this.ta({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.Ko.push(e),this._surveyManager&&this.ta({isLoaded:!0}),()=>{this.Ko=this.Ko.filter((t=>t!==e))}}getSurveys(e,t){if(t===void 0&&(t=!1),this.qt.disable_surveys)return bn.info(h5),e([]);var n,r=this._instance.get_property(s4);if(r&&!t)return e(r,{isLoaded:!0});typeof Promise<"u"&&this.Yo?this.Yo.then((i=>{var{surveys:s,context:o}=i;return e(s,o)})):(typeof Promise<"u"&&(this.Yo=new Promise((i=>{n=i}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.qt.token),method:"GET",timeout:this.qt.surveys_request_timeout_ms,callback:i=>{var s;this.Yo=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;bn.error(a);var l={isLoaded:!1,error:a};return e([],l),void(n==null||n({surveys:[],context:l}))}var u,f=i.json.surveys||[],p=f.filter((g=>(function(b){return!(!b.start_date||b.end_date)})(g)&&((function(b){var x;return!((x=b.conditions)==null||(x=x.events)==null||(x=x.values)==null||!x.length)})(g)||(function(b){var x;return!((x=b.conditions)==null||(x=x.actions)==null||(x=x.values)==null||!x.length)})(g))));p.length>0&&((u=this._surveyEventReceiver)==null||u.register(p)),(s=this._instance.persistence)==null||s.register({[s4]:f});var m={isLoaded:!0};e(f,m),n==null||n({surveys:f,context:m})}}))}ta(e){for(var t of this.Ko)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(n){bn.error("Error in survey callback",n)}}getActiveMatchingSurveys(e,t){if(t===void 0&&(t=!1),!Kt(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);bn.warn("init was not called")}ra(e){var t=null;return this.getSurveys((n=>{var r;t=(r=n.find((i=>i.id===e)))!==null&&r!==void 0?r:null})),t}ia(e){if(Kt(this._surveyManager))return{eligible:!1,reason:Db};var t=typeof e=="string"?this.ra(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Kt(this._surveyManager))return bn.warn("init was not called"),{visible:!1,disabledReason:Db};var t=this.ia(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return Kt(this._surveyManager)?(bn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Db})):new Promise((n=>{this.getSurveys((r=>{var i,s=(i=r.find((a=>a.id===e)))!==null&&i!==void 0?i:null;if(s){var o=this.ia(s);n({visible:o.eligible,disabledReason:o.reason})}else n({visible:!1,disabledReason:"Survey not found"})}),t)}))}renderSurvey(e,t,n){var r;if(Kt(this._surveyManager))bn.warn("init was not called");else{var i=typeof e=="string"?this.ra(e):e;if(i!=null&&i.id)if(HW.includes(i.type)){var s=Ze==null?void 0:Ze.querySelector(t);if(s)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(bn.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,a;bn.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,s,n),bn.info("Survey "+i.id+" rendered")}),1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,s,n);bn.warn("Survey element not found")}else bn.warn("Surveys of type "+i.type+" cannot be rendered in the app");else bn.warn("Survey not found")}}displaySurvey(e,t){var n;if(Kt(this._surveyManager))bn.warn("init was not called");else{var r=this.ra(e);if(r){var i=r;if((n=r.appearance)!=null&&n.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=Oe({},r,{appearance:Oe({},r.appearance,{surveyPopupDelaySeconds:0})})),t.displayType!==p4.Popover&&t.initialResponses&&bn.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){var s=this.canRenderSurvey(r);if(!s.visible)return void bn.warn("Survey is not eligible to be displayed: ",s.disabledReason)}t.displayType!==p4.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}else bn.warn("Survey not found")}}cancelPendingSurvey(e){Kt(this._surveyManager)?bn.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}},_v),xG={toolbar:class{constructor(e){this.instance=e}na(e){gt.ph_toolbar_state=e}sa(){var e;return(e=gt.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e,t,n){if(e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),KM(this.instance.config)||!me||!Ze)return!1;e=e??me.location,n=n??me.history;try{if(!t){try{me.localStorage.setItem("test","test"),me.localStorage.removeItem("test")}catch{return!1}t=me==null?void 0:me.localStorage}var r,i=dG||d1(e.hash,"__posthog")||d1(e.hash,"state"),s=i?IS((()=>JSON.parse(atob(decodeURIComponent(i)))))||IS((()=>JSON.parse(decodeURIComponent(i)))):null;return s&&s.action==="ph_authorize"?((r=s).source="url",r&&Object.keys(r).length>0&&(s.desiredHash?e.hash=s.desiredHash:n?n.replaceState(n.state,"",e.pathname+e.search):e.hash="")):((r=JSON.parse(t.getItem(p5)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}oa(e){var t=gt.ph_load_toolbar||gt.ph_load_editor;!Kt(t)&&zo(t)?t(e,this.instance):m5.warn("No toolbar load function found")}loadToolbar(e){var t=!(Ze==null||!Ze.getElementById(ZM));if(!me||t)return!1;var n=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=Oe({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},n?{instrument:!1}:{});if(me.localStorage.setItem(p5,JSON.stringify(Oe({},r,{source:void 0}))),this.sa()===2)this.oa(r);else if(this.sa()===0){var i;this.na(1),(i=gt.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return m5.error("[Toolbar] Failed to load",s),void this.na(0);this.na(2),this.oa(r)})),Wn(me,"turbolinks:load",(()=>{this.na(0),this.loadToolbar(r)}))}return!0}aa(e){return this.loadToolbar(e)}maybeLoadEditor(e,t,n){return e===void 0&&(e=void 0),t===void 0&&(t=void 0),n===void 0&&(n=void 0),this.maybeLoadToolbar(e,t,n)}}},wG=Oe({experiments:Vr},_v),_G={conversations:class{constructor(e){this.ua=void 0,this._conversationsManager=null,this.la=!1,this.ha=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var t=e.conversations;Kt(t)||(oo(t)?this.ua=t:(this.ua=t.enabled,this.ha=t),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.ua=void 0,this.ha=null}loadIfEnabled(){if(!(this._conversationsManager||this.la||this._instance.config.disable_conversations||KM(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=gt==null?void 0:gt.__PosthogExtensions__;if(e&&!We(this.ua)&&this.ua)if(this.ha&&this.ha.token){this.la=!0;try{var t=e.initConversations;if(t)return this.ca(t),void(this.la=!1);var n=e.loadExternalDependency;if(!n)return void this.da(K8);n(this._instance,"conversations",(r=>{r||!e.initConversations?this.da("Could not load conversations script",r):this.ca(e.initConversations),this.la=!1}))}catch(r){this.da("Error initializing conversations",r),this.la=!1}}else Ki.error("Conversations enabled but missing token in remote config.")}}ca(e){if(this.ha)try{this._conversationsManager=e(this.ha,this._instance),Ki.info("Conversations loaded successfully")}catch(t){this.da("Error completing conversations initialization",t)}else Ki.error("Cannot complete initialization: remote config is null")}da(e,t){Ki.error(e,t),this._conversationsManager=null,this.la=!1}show(){this._conversationsManager?this._conversationsManager.show():Ki.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.ua===!0&&!es(this._conversationsManager)}isVisible(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,n){var r=this;return $i((function*(){return r._conversationsManager?r._conversationsManager.sendMessage(e,t,n):(Ki.warn(Kl),null)}))()}getMessages(e,t){var n=this;return $i((function*(){return n._conversationsManager?n._conversationsManager.getMessages(e,t):(Ki.warn(Kl),null)}))()}markAsRead(e){var t=this;return $i((function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Ki.warn(Kl),null)}))()}getTickets(e){var t=this;return $i((function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Ki.warn(Kl),null)}))()}requestRestoreLink(e){var t=this;return $i((function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(Ki.warn(Kl),null)}))()}restoreFromToken(e){var t=this;return $i((function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(Ki.warn(Kl),null)}))()}restoreFromUrlToken(){var e=this;return $i((function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(Ki.warn(Kl),null)}))()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)==null?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}yn(){var e;(e=this._conversationsManager)==null||e.setIdentity()}bn(){var e;(e=this._conversationsManager)==null||e.clearIdentity()}}},kG={logs:class{constructor(e){var t;this.va=!1,this.fa=!1,this.Gt=Ln("[logs]"),this.pa=[],this.ga=0,this.ma=0,this.ya=!1,this._instance=e,this._instance&&(t=this._instance.config.logs)!=null&&t.captureConsoleLogs&&(this.va=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(e){var t,n=(t=e.logs)==null?void 0:t.captureConsoleLogs;!Kt(n)&&n&&(this.va=!0,this.loadIfEnabled())}reset(){this.pa=[],this.Br&&(clearTimeout(this.Br),this.Br=void 0),this.ga=0,this.ma=0,this.ya=!1}loadIfEnabled(){if(this.va&&!this.fa){var e=gt==null?void 0:gt.__PosthogExtensions__;if(e){var t=e.loadExternalDependency;t?t(this._instance,"logs",(n=>{var r;n||(r=e.logs)==null||!r.initializeLogs?this.Gt.error("Could not load logs script",n):(e.logs.initializeLogs(this._instance),this.fa=!0)})):this.Gt.error(K8)}else this.Gt.error("PostHog Extensions not found.")}}captureLog(e){var t,n,r,i,s,o;if(this._instance.is_capturing())if(e&&e.body){var a=(t=(n=this._instance.config.logs)==null?void 0:n.flushIntervalMs)!==null&&t!==void 0?t:3e3,l=(r=(i=this._instance.config.logs)==null?void 0:i.maxLogsPerInterval)!==null&&r!==void 0?r:1e3,u=Date.now();if(a>u-this.ma||(this.ma=u,this.ga=0,this.ya=!1),l>this.ga){this.ga++;var f=(function(p,m){var g=p.level||"info",{text:b,number:x}=NM[g]||NZ,k=String(Date.now())+"000000",w={};m.distinctId&&(w.posthogDistinctId=m.distinctId),m.sessionId&&(w.sessionId=m.sessionId),m.currentUrl&&(w["url.full"]=m.currentUrl),m.screenName&&(w["screen.name"]=m.screenName),m.appState&&(w["app.state"]=m.appState),m.activeFeatureFlags&&m.activeFeatureFlags.length>0&&(w.feature_flags=m.activeFeatureFlags);var C=Oe({},w,p.attributes||{}),E={timeUnixNano:k,observedTimeUnixNano:k,severityNumber:x,severityText:b,body:{stringValue:p.body},attributes:AS(C)};return p.trace_id&&(E.traceId=p.trace_id),p.span_id&&(E.spanId=p.span_id),We(p.trace_flags)||(E.flags=p.trace_flags),E})(e,this.ba());this.pa.push({record:f}),((s=(o=this._instance.config.logs)==null?void 0:o.maxBufferSize)!==null&&s!==void 0?s:100)>this.pa.length?this._a():this.flushLogs()}else this.ya||(this.Gt.warn("captureLog dropping logs: exceeded "+l+" logs per "+a+"ms"),this.ya=!0)}else this.Gt.warn("captureLog requires a body")}get logger(){return this.wa||(this.wa={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.wa}flushLogs(e){if(this.Br&&(clearTimeout(this.Br),this.Br=void 0),this.pa.length!==0){var t=this.pa;this.pa=[];var n=this._instance.config.logs,r=Oe({"service.name":(n==null?void 0:n.serviceName)||"unknown_service"},(n==null?void 0:n.environment)&&{"deployment.environment":n.environment},(n==null?void 0:n.serviceVersion)&&{"service.version":n.serviceVersion},n==null?void 0:n.resourceAttributes),i=(function(o,a,l,u){return{resourceLogs:[{resource:{attributes:AS(a)},scopeLogs:[{scope:{name:l,version:u},logRecords:o}]}]}})(t.map((o=>o.record)),r,wr.LIB_NAME,wr.LIB_VERSION),s=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Yi({method:"POST",url:s,data:i,compression:"best-available",batchKey:"logs",transport:e})}}_a(){var e,t;this.Br||(this.Br=setTimeout((()=>{this.Br=void 0,this.flushLogs()}),(e=(t=this._instance.config.logs)==null?void 0:t.flushIntervalMs)!==null&&e!==void 0?e:3e3))}ba(){var e,t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:n}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=n}if(gt!=null&&(e=gt.location)!=null&&e.href&&(t.currentUrl=gt.location.href),this._instance.featureFlags){var r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},CG=Oe({},_v,hG,pG,mG,gG,vG,bG,yG,xG,wG,_G,kG);Xi.__defaultExtensionClasses=Oe({},CG);var St=(function(){wr.SDK_DIST_CHANNEL="npm";var e=Wh[Zu]=new Xi;return(function(){function t(){t.done||(t.done=!0,v9=!1,Rn(Wh,(function(n){n._dom_loaded()})))}Ze!=null&&Ze.addEventListener?Ze.readyState==="complete"?t():Wn(Ze,"DOMContentLoaded",t,{capture:!1}):me&&Ue.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),e})(),S9;function EG(e){S9=e}function E4(){return S9}var n3=h.createContext({get client(){return E4()},bootstrap:void 0});function A9(e,t,n){if(n===void 0&&(n=new WeakMap),e===t)return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(n.has(e)&&n.get(e)===t)return!0;n.set(e,t);var r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(var s=0,o=r;s<o.length;s++){var a=o[s];if(!i.includes(a)||!A9(e[a],t[a],n))return!1}return!0}function SG(e){var t,n,r=e.children,i=e.client,s=e.apiKey,o=e.options,a=h.useRef(null),l=h.useMemo(function(){if(i)return s&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),o&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),i;var u=E4();return s||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),u},[i,s,JSON.stringify(o)]);return h.useEffect(function(){if(!(i||!s)){var u=E4(),f=a.current;f?(s!==f.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),o&&!A9(o,f.options)&&u.set_config(o),a.current={apiKey:s,options:o??{}}):(u.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),u.init(s,o),a.current={apiKey:s,options:o??{}})}},[i,s,JSON.stringify(o)]),xe.createElement(n3.Provider,{value:{client:l,bootstrap:(t=o==null?void 0:o.bootstrap)!==null&&t!==void 0?t:(n=i==null?void 0:i.config)===null||n===void 0?void 0:n.bootstrap}},r)}var Lb=function(e){return typeof e=="function"},xi=function(){var e=h.useContext(n3).client;return e},S4=function(e,t){return S4=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},S4(e,t)};function AG(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");S4(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var TG={componentStack:null,exceptionEvent:null,error:null},PG={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."},IG=(function(e){AG(t,e);function t(n){var r=e.call(this,n)||this;return r.state=TG,r}return t.prototype.componentDidCatch=function(n,r){var i=this.props.additionalProperties,s;Lb(i)?s=i(n):typeof i=="object"&&(s=i);var o=this.context.client,a=o.captureException(n,s),l=r.componentStack;this.setState({error:n,componentStack:l??null,exceptionEvent:a})},t.prototype.render=function(){var n=this.props,r=n.children,i=n.fallback,s=this.state;if(s.componentStack==null)return Lb(r)?r():r;var o=Lb(i)?xe.createElement(i,{error:s.error,componentStack:s.componentStack,exceptionEvent:s.exceptionEvent}):i;return xe.isValidElement(o)?o:(console.warn(PG.INVALID_FALLBACK),xe.createElement(xe.Fragment,null))},t.contextType=n3,t})(xe.Component);EG(St);var Im={},jb={exports:{}},ai={},Fb={exports:{}},Ob={};/**
|
|
19
19
|
* @license React
|
|
20
20
|
* scheduler.production.min.js
|
|
@@ -608,7 +608,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
|
|
|
608
608
|
pointer-events: none;
|
|
609
609
|
display: none;
|
|
610
610
|
`,this.iframeRef.parentElement.appendChild(t)),t}removeMouseCaptureOverlay(){var n;if(!((n=this.iframeRef)!=null&&n.parentElement))return;const t=this.iframeRef.parentElement.querySelector("#rivet-mouse-capture");t&&t.remove()}isOverlayInSidebar(t,n,r,i){const s=document.querySelector('[data-cy="element-inspector"]');if(!s)return!1;const o=s.getBoundingClientRect(),a=t+r,l=n+i;return!(a<=o.left||t>=o.right||l<=o.top||n>=o.bottom)}getComputedStyles(){if(!this.currentElement||!this.iframeRef)return _h.warn("Attempt to get computed styles failed: currentElement ",this.currentElement,"iFrameRef:",this.iframeRef),{};const t=this.iframeRef.contentWindow;if(!t)return _h.warn("Attempt to get computed styles failed: iFrameWindow not defined"),{};const n=t.getComputedStyle(this.currentElement),r={};for(let i=0;i<n.length;i++){const s=n[i];r[s]=n.getPropertyValue(s)}return r.background=wT(r),r}onStylesChanged(t){return this.onStylesChangedCallback=t,()=>{this.onStylesChangedCallback=null}}refreshStyles(){const t=this.getComputedStyles();this.notifyStylesChanged(t)}setCurrentElement(t){this.currentElement=t,t&&this.refreshStyles()}notifyStylesChanged(t){this.onStylesChangedCallback&&this.onStylesChangedCallback(t)}async applyStyle(t,n,r){const i=await this.findElement(t);if(!i.ok)return fi(i.error);const s=i.value;t.rivetId&&this.injectRivetId(s,t.rivetId);try{return s.style[n]=r,Cs(void 0)}catch(o){return fi(new zee(n,r,o instanceof Error?o.message:String(o)))}}async getComputedStylesForElement(t){const n=await this.findElement(t);if(!n.ok)return fi(n.error);const r=n.value;if(!this.iframeRef)return fi(new Au(t,"Iframe ref is null"));const i=this.iframeRef.contentWindow;if(!i)return fi(new Au(t,"Iframe window is null"));try{const s=i.getComputedStyle(r),o={};for(let a=0;a<s.length;a++){const l=s[a];o[l]=s.getPropertyValue(l)}return o.background=wT(o),Cs(o)}catch(s){return fi(new Au(t,s instanceof Error?s.message:String(s)))}}async findElement(t){if(!this.iframeRef)return fi(new Au(t,"Iframe ref is null"));const n=_r(this.iframeRef);if(!n)return fi(new Au(t,"Cannot access iframe document"));if(t.rivetId){const r=n.querySelector(`[data-rivet-id="${t.rivetId}"]`);if(r)return Cs(r)}if(t.xpath){const r=dd(n,t.xpath);if(r)return Cs(r)}if(t.cssSelector)try{const r=n.querySelector(t.cssSelector);if(r)return Cs(r)}catch(r){_h.warn("Invalid CSS selector:",t.cssSelector,r)}return fi(new Au(t,"Element not found using any identifier strategy"))}injectRivetId(t,n){t.setAttribute("data-rivet-id",n)}createElementIdentifier(t){const n=t.getAttribute("data-rivet-id"),r=Dv(t);let i;if(t.id)i=`#${t.id}`;else if(t.className&&typeof t.className=="string"){const s=t.className.trim().split(/\s+/).join(".");s&&(i=`${t.tagName.toLowerCase()}.${s}`)}return{rivetId:n||"",xpath:r,cssSelector:i}}onHMR(t){var o;this.hmrCallbacks.push(t);let n=null,r=null;const i=()=>{r&&clearTimeout(r),r=setTimeout(()=>{this.handleIframeLoad()},1e3)};this.iframeRef&&this.hmrCallbacks.length===1&&this.iframeRef.addEventListener("load",this.handleIframeLoad);const s=this.iframeRef?_r(this.iframeRef):null;if(s){n=new MutationObserver(u=>{u.some(p=>{var g;const m=p.target;return!((g=m.closest)!=null&&g.call(m,'[id^="rivet-"]'))})&&i()});const a=s.body??s.documentElement??s,l=((o=s.defaultView)==null?void 0:o.Node)??Node;if(a instanceof l)try{n.observe(a,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","src","href"],characterData:!0})}catch{}}return()=>{const a=this.hmrCallbacks.indexOf(t);a!==-1&&this.hmrCallbacks.splice(a,1),n==null||n.disconnect(),r&&clearTimeout(r),this.hmrCallbacks.length===0&&this.iframeRef&&this.iframeRef.removeEventListener("load",this.handleIframeLoad)}}forceReload(){return new Promise((t,n)=>{var a;if(!((a=this.iframeRef)!=null&&a.contentWindow)){t();return}let r,i=!1;const s=()=>{var l;i||(i=!0,clearTimeout(r),(l=this.iframeRef)==null||l.removeEventListener("load",o))},o=()=>{s(),t()};r=setTimeout(()=>{s(),n(new Error("Iframe reload timeout after 10s"))},1e4),this.iframeRef.addEventListener("load",o);try{this.iframeRef.contentWindow.location.reload()}catch(l){s(),n(l)}})}}class u4e extends tB{}const d4e={pending:"bg-primary",complete:"bg-accent-success",error:"bg-accent-error"},k8=36,C8=28,Wg=10,E8=Wg/2,sR=k8/2,oR=C8+E8,aR=8,f4e=.65,lR=200,cR=8,h4e=(e,t)=>{const n=e-t/2,r=window.innerWidth-t-cR;return Math.max(cR,Math.min(n,r))},nB=({comment:e,index:t,position:n,stale:r=!1,onEdit:i,onHover:s,onHoverEnd:o})=>{var b;const[a,l]=h.useState(!1),u=h.useCallback(x=>{x.stopPropagation(),i(e.id)},[e.id,i]),f=n.y/window.innerHeight>f4e,p=e.instruction,g=h4e(n.x,lR)-(n.x-sR);return y.jsxs("div",{className:"fixed",style:{top:f?n.y:n.y-oR,left:n.x-sR,zIndex:a?55:36,opacity:r?.5:1},onMouseEnter:()=>{l(!0),s==null||s()},onMouseLeave:()=>{l(!1),o==null||o()},children:[y.jsxs("div",{className:"relative cursor-pointer",style:{filter:"drop-shadow(0 1px 3px rgba(0,0,0,0.2))"},onClick:u,children:[y.jsx("div",{className:"absolute bg-main",style:{width:Wg,height:Wg,left:(k8-Wg)/2,top:f?-E8:C8-E8,transform:"rotate(45deg)",borderRadius:3}}),y.jsxs("div",{className:"relative flex items-center justify-center rounded-lg bg-main",style:{width:k8,height:C8},children:[y.jsx("div",{className:`flex h-5 w-5 items-center justify-center rounded-full ${d4e[e.status]}`,children:y.jsx("span",{className:"text-[10px] font-bold leading-none text-white",children:t+1})}),e.variantRequest?y.jsx("div",{"aria-label":"Direction request","data-testid":"comment-marker-variant-glyph",className:"absolute -right-1 -top-1 flex h-3.5 w-3.5 items-center justify-center rounded-full bg-primary text-white",children:y.jsx(g1,{className:"h-2.5 w-2.5",weight:"bold"})}):null]})]}),y.jsx(Fi,{children:a&&(p||((b=e.images)==null?void 0:b.length))&&y.jsxs(mn.div,{className:"absolute rounded-lg bg-main px-3 py-2 shadow-lg",style:{left:g,top:f?-aR:oR+aR,transformOrigin:f?"bottom center":"top center",width:lR},initial:{scale:.96,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.96,opacity:0,transition:{duration:.06,ease:[.55,0,1,.45]}},transition:{duration:.08,ease:[.165,.84,.44,1]},children:[p?y.jsx("p",{className:"line-clamp-2 text-left text-xs leading-snug text-content",children:p}):null,e.images&&e.images.length>0?y.jsx("div",{className:`flex flex-wrap justify-center gap-1 ${p?"mt-1.5":""}`,children:e.images.map((x,k)=>y.jsx("img",{src:x,alt:`Reference ${k+1}`,className:"max-h-10 rounded border border-divider"},k))}):null]})})]})},p4e=({onEditComment:e,target:t,iframeRef:n})=>{const[r,i]=zn($r),[s,o]=h.useState(null),[,a]=h.useState(0),l=h.useRef(null),u=h.useRef(new Map),f=h.useRef(new Set),p=h.useCallback(()=>a(I=>I+1),[]);h.useEffect(()=>{const I=n==null?void 0:n.current;if(!I)return;let T=null;const L=()=>{const O=_r(I);!O||O===T||(T&&T.removeEventListener("scroll",p,!0),T=O,O.addEventListener("scroll",p,!0))},M=()=>{L(),p()};L(),I.addEventListener("load",M),window.addEventListener("resize",p);const D=new ResizeObserver(p);return D.observe(I),l.current=()=>{I.removeEventListener("load",M),window.removeEventListener("resize",p),D.disconnect(),T&&T.removeEventListener("scroll",p,!0)},()=>{var O;return(O=l.current)==null?void 0:O.call(l)}},[n,p]);const m=h.useCallback(I=>{const T=n==null?void 0:n.current;T&&hd(T,r.values()),i(L=>{const M=new Map(L);return M.delete(I),M})},[i,n,r]),g=Array.from(r.values()).filter(I=>xp(I.target??uo,t));if(g.length===0)return null;const b=(n==null?void 0:n.current)??null,x=b?_r(b):null,k=(b==null?void 0:b.getBoundingClientRect())??null,w=(I,T,L,M)=>{const D=u.current.get(I);if(!k)return D?{position:D,stale:!0}:null;if(!x){const V=T.boundingRect,U={x:k.left+V.left+L*V.width,y:k.top+V.top+M*V.height};return u.current.set(I,U),{position:U,stale:!0}}const O=fd(x,T);if(!O){if(!f.current.has(I)){const V=q3(x,T);console.warn("[CommentMarkerLayer] anchor unresolved",{commentId:I,xpath:T.xpath,rivetId:T.rivetId,byRivetHit:!!V.byRivet,byXPathHit:!!V.byXPath,fallback:D?"cached-position":"none"}),f.current.add(I)}return D?{position:D,stale:!0}:null}f.current.delete(I);const F=O.getBoundingClientRect();if(F.bottom<0||F.top>k.height)return null;const Z={x:k.left+F.left+L*F.width,y:k.top+F.top+M*F.height};return u.current.set(I,Z),{position:Z,stale:!1}},C=I=>{if(!I.dragBox||!k)return null;const T=x?fd(x,I.elementContext):null,L=(T==null?void 0:T.getBoundingClientRect())??I.elementContext.boundingRect,{leftPct:M,topPct:D,widthPct:O,heightPct:F}=I.dragBox;return{left:k.left+L.left+M*L.width,top:k.top+L.top+D*L.height,width:O*L.width,height:F*L.height}},E=I=>{if(!k)return null;const T=!I.finalizedVariant&&(I.selectedVariantIndex??0)===0;if(I.dragBox&&T)return C(I);const L=x?fd(x,I.elementContext):null,M=(L==null?void 0:L.getBoundingClientRect())??I.elementContext.boundingRect;return{left:k.left+M.left,top:k.top+M.top,width:M.width,height:M.height}},A=s!=null?r.get(s):void 0,R=A?E(A):null,P=!!(A!=null&&A.dragBox&&!A.finalizedVariant&&(A.selectedVariantIndex??0)===0);for(const I of u.current.keys())r.has(I)||u.current.delete(I);return y.jsxs(y.Fragment,{children:[g.map((I,T)=>{const L=w(I.id,I.elementContext,I.pin.elementXPct,I.pin.elementYPct);return L?y.jsx(nB,{comment:I,index:T,position:L.position,stale:L.stale,onDismiss:m,onEdit:e,onHover:()=>o(I.id),onHoverEnd:()=>o(null)},I.id):null}),R&&y.jsx("div",{"data-comment-hover-overlay":"true",style:{position:"fixed",pointerEvents:"none",zIndex:30,border:P?"1px dashed var(--color-primary, #FF3300)":"1px solid var(--color-primary-border, #ff6b35)",background:P?"rgba(255, 51, 0, 0.08)":"transparent",borderRadius:2,boxSizing:"border-box",left:R.left,top:R.top,width:R.width,height:R.height}})]})},rB=Vt("commentPersistence"),iB=e=>`rivet:pending-comments:${e}`,sB=e=>`rivet:applied-variant-diff:${e}`,m4e=(e,t)=>{const n=sB(t);try{e?localStorage.setItem(n,JSON.stringify(e)):localStorage.removeItem(n)}catch{}},g4e=e=>{try{const t=localStorage.getItem(sB(e));return t?JSON.parse(t):null}catch{return null}},Pk=()=>{const e=Ge(ei),t=Ee(Mv);return h.useCallback(n=>{e(n),t&&m4e(n,t)},[e,t])},v4e=(e,t)=>{const n=Array.from(e.values()).filter(r=>{var i;return r.status==="pending"&&((i=r.target)==null?void 0:i.kind)!=="variant"}).map(r=>r.styleVariants?{...r,styleVariants:r.styleVariants.map(i=>i.codeStatus==="pending"||i.codeStatus==="error"?{...i,codeStatus:void 0,codeError:void 0}:{...i,codeError:void 0}),variantSessionId:void 0}:r);try{localStorage.setItem(iB(t),JSON.stringify(n))}catch(r){rB.warn("Failed to persist comments to localStorage:",r)}},y4e=e=>{const t=iB(e);try{const n=localStorage.getItem(t);if(!n)return new Map;const i=JSON.parse(n).filter(s=>s.status==="pending").map(s=>{var u;const o=s.pin,a=(o==null?void 0:o.elementXPct)??(o==null?void 0:o.xPct)??.5,l=(o==null?void 0:o.elementYPct)??(o==null?void 0:o.yPct)??.5;return{...s,pin:{elementXPct:Number.isFinite(a)?a:.5,elementYPct:Number.isFinite(l)?l:.5},variantGenerationStatus:s.variantGenerationStatus==="generating"?void 0:s.variantGenerationStatus,variantGenerationError:s.variantGenerationStatus==="generating"?void 0:s.variantGenerationError,styleVariants:(u=s.styleVariants)!=null&&u.every(f=>!f.changeSpec)?void 0:s.styleVariants,previewBaselineStyle:void 0}});return new Map(i.map(s=>[s.id,s]))}catch(n){rB.warn("Failed to restore comments from localStorage, clearing bad key:",n);try{localStorage.removeItem(t)}catch{}return new Map}},b4e=(e,t,n)=>{const r=Math.max(0,e.left),i=Math.max(0,e.top),s=Math.min(t,e.right),o=Math.min(n,e.bottom),a=s-r,l=o-i;return a<=0||l<=0?null:{left:r,top:i,right:s,bottom:o,width:a,height:l}},ov=36,av=8,x4e=e=>e.top-8<ov+av,fw=ov,hw=av,uR=220,kh=8,w4e="Original",_4e=["⡡⠊⢔⠡","⠊⡰⡡⡘","⢔⢅⠈⢢","⡁⢂⠆⡍","⢔⠨⢑⢐","⠨⡑⡠⠊"],dR=(e,t,n)=>t>n?t:Math.min(Math.max(e,t),n),k4e=(e,t,n)=>{const r=t.top+e.top,i=r+e.height,s=t.left+e.left+e.width/2,o=window.innerWidth-n-kh,a=dR(s-n/2,kh,o),f=!(r-kh>=fw+hw),p=f?i+hw:r-fw-hw;return{top:dR(p,kh,window.innerHeight-fw-kh),left:a,below:f}},C4e=({onCommentClose:e})=>{const t=xi(),[n,r]=zn($r),i=Ee(Iv),s=Ee(nf),o=Ee(Mc),a=Ge(Mc),l=Pk(),u=da(),[f,p]=h.useState(0),[m,g]=h.useState(null),b=h.useRef(null),x=h.useRef(!1),[k,w]=h.useState(0),C=h.useRef(null),E=h.useRef(!1),A=h.useRef(n);A.current=n;const R=h.useRef(new Map),P=h.useRef(new Set),I=h.useCallback(()=>{x.current||(x.current=!0,requestAnimationFrame(()=>{x.current=!1,p(ae=>ae+1)}))},[]),T=h.useCallback(ae=>{g(ae),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(()=>{g(null)},160)},[]),L=h.useCallback(async(ae,we)=>{try{return(await fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:ae,reverse:we})})).ok}catch{return!1}},[]),M=h.useCallback(async(ae,we)=>{var Re;if(!E.current){E.current=!0;try{const Ne=u.get(ei);if(Ne)if(await L(Ne.diff,!0))l(null);else return;if(we>0){const ee=A.current.get(ae),ce=(ee==null?void 0:ee.selectedVariantIndex)??0,ge=(Re=ee==null?void 0:ee.styleVariants)==null?void 0:Re[we-1];ce===we&&(ge==null?void 0:ge.codeStatus)==="ready"&&ge.codeDiff&&await L(ge.codeDiff,!1)&&l({commentId:ae,variantIndex:we,diff:ge.codeDiff})}}finally{E.current=!1}}},[L,l,u]),D=h.useCallback((ae,we)=>{const Re=A.current.get(ae);Re!=null&&Re.finalizedVariant||(r(Ne=>{const ee=Ne.get(ae);if(!(ee!=null&&ee.styleVariants)||ee.styleVariants.length===0)return Ne;const ce=ee.styleVariants.length+1,ge=Math.min(Math.max(ee.selectedVariantIndex??0,0),ce-1),le=((ge+we)%ce+ce)%ce;if(le===ge)return Ne;t==null||t.capture("comment_carousel_navigate",{variant_index:le,variant_count:ee.styleVariants.length});const he=new Map(Ne);return he.set(ae,{...ee,selectedVariantIndex:le}),he}),T(ae),C.current!==null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{const Ne=A.current.get(ae),ee=(Ne==null?void 0:Ne.selectedVariantIndex)??0;M(ae,ee)},300))},[t,T,r,M]),O=h.useCallback(ae=>{const we=A.current.get(ae);if(!(we!=null&&we.styleVariants)||we.styleVariants.length===0)return;const Re=we.styleVariants.length+1,Ne=Math.min(Math.max(we.selectedVariantIndex??0,0),Re-1);t==null||t.capture("comment_variant_apply_clicked",{variant_index:Ne,variant_count:we.styleVariants.length});const ee=Ne===0?void 0:we.styleVariants[Ne-1],ce=u.get(ei);ce&&(ce.variantIndex!==Ne&&L(ce.diff,!0),l(null)),r(ge=>{const le=ge.get(ae);if(!le)return ge;const he=new Map(ge);return he.set(ae,{...le,finalizedVariant:ee,variantGenerationStatus:void 0,variantGenerationError:void 0}),he}),C.current!==null&&(window.clearTimeout(C.current),C.current=null),a(null),e==null||e()},[t,r,L,l,u,e]);h.useEffect(()=>{const ae=s==null?void 0:s.current;if(!ae)return;let we=null;const Re=()=>{const ee=_r(ae);!ee||ee===we||(we&&we.removeEventListener("scroll",I,!0),we=ee,ee.addEventListener("scroll",I,!0))},Ne=()=>{Re(),I()};return Re(),ae.addEventListener("load",Ne),window.addEventListener("resize",I),()=>{ae.removeEventListener("load",Ne),window.removeEventListener("resize",I),we&&we.removeEventListener("scroll",I,!0)}},[s,I]),h.useEffect(()=>i.onChange(()=>w(we=>we+1)),[i]),h.useEffect(()=>{const ae=s==null?void 0:s.current,we=ae?_r(ae):null;if(!we)return;const Re=i.getStyleChanges(),Ne=new Map;for(const ce of Re){const ge=ce.elementId.xpath,le=Ne.get(ge);if(le){le.push(ce);continue}Ne.set(ge,[ce])}const ee=[];for(const ce of n.values()){const ge=ce.styleVariants;if(!ge||ge.length===0)continue;const le=m6(we,ce.elementContext);if(!le)continue;let he=ce.previewBaselineStyle;if(he===void 0){he=le.getAttribute("style")??"";const Ke=we.defaultView,Je=le.getBoundingClientRect();R.current.set(ce.id,{pageLeft:((Ke==null?void 0:Ke.scrollX)??0)+Je.left,pageTop:((Ke==null?void 0:Ke.scrollY)??0)+Je.top,width:Je.width,height:Je.height}),ee.push({id:ce.id,baseline:he})}le.setAttribute("style",he);const Se=Ne.get(ce.elementContext.xpath)??[];for(const Ke of Se)le.style.setProperty(kp(String(Ke.property)),Ke.newValue)}ee.length>0&&r(ce=>{let ge=null;for(const{id:le,baseline:he}of ee){const Se=ce.get(le);!Se||Se.previewBaselineStyle!==void 0||(ge||(ge=new Map(ce)),ge.set(le,{...Se,previewBaselineStyle:he}))}return ge??ce}),I()},[n,s,r,i,k,I]),h.useEffect(()=>{if(!o)return;const ae=we=>{var ce;if(we.key!=="ArrowLeft"&&we.key!=="ArrowRight"&&we.key!=="Enter")return;const Re=(ce=we.target)==null?void 0:ce.tagName;if(Re==="INPUT"||Re==="TEXTAREA"||Re==="SELECT")return;const Ne=A.current.get(o);if(!(Ne!=null&&Ne.styleVariants)||Ne.styleVariants.length===0)return;if(we.preventDefault(),we.key==="Enter"){O(o);return}const ee=we.key==="ArrowLeft"?-1:1;D(o,ee)};return window.addEventListener("keydown",ae,{capture:!0}),()=>window.removeEventListener("keydown",ae,{capture:!0})},[o,D,O]),h.useEffect(()=>()=>{b.current!==null&&window.clearTimeout(b.current),C.current!==null&&window.clearTimeout(C.current)},[]),h.useEffect(()=>{if(o)return()=>{const we=u.get(ei);we&&(fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:we.diff,reverse:!0})}),l(null))}},[o,l,u]);const F=o?n.get(o):void 0;if(!F)return null;const Z=(s==null?void 0:s.current)??null;if(!Z)return null;const V=Z.getBoundingClientRect(),U=_r(Z);if(!U)return null;const K=m6(U,F.elementContext),W=R.current.get(F.id);if(K)P.current.delete(F.id);else if(!P.current.has(F.id)){const ae=q3(U,F.elementContext);console.warn("[CommentCarouselLayer] anchor unresolved",{commentId:F.id,xpath:F.elementContext.xpath,rivetId:F.elementContext.rivetId,byRivetHit:!!ae.byRivet,byXPathHit:!!ae.byXPath,fallback:W?"baseline-rect":"none"}),P.current.add(F.id)}if(!K&&!W)return null;const G=U.defaultView,j=(G==null?void 0:G.scrollX)??0,H=(G==null?void 0:G.scrollY)??0,B=K?K.getBoundingClientRect():{left:W.pageLeft-j,top:W.pageTop-H,width:W.width,height:W.height,right:W.pageLeft-j+W.width,bottom:W.pageTop-H+W.height},N=b4e(B,Z.clientWidth,Z.clientHeight);if(!N)return null;const q=W?{left:W.pageLeft-j,top:W.pageTop-H,width:W.width,height:W.height}:N,X=F.styleVariants,ie=!!X&&X.length>0&&X.every(ae=>ae.changeSpec!=="")&&!F.finalizedVariant,Y=X?X.length+1:1,J=X?Math.min(Math.max(F.selectedVariantIndex??0,0),Y-1):0,ue=X&&J>0?X[J-1]:void 0,be=V.left+q.left,Me=V.top+q.top,_e=q.width,ke=q.height,{dragBox:$e}=F,Qe=$e?V.left+B.left+$e.leftPct*B.width:0,He=$e?V.top+B.top+$e.topPct*B.height:0,ze=$e?$e.widthPct*B.width:0,ye=$e?$e.heightPct*B.height:0,nt=!!X&&X.some(ae=>ae.codeStatus==="pending"||ae.changeSpec===""),$t=!!X&&X.length>0&&J===0,ve=!F.finalizedVariant&&nt,Ae=!F.finalizedVariant&&!ve&&$t&&!!$e;if(!ve&&!Ae&&!ie)return null;let ut=null;if(ie&&X){const ae=J===0?w4e:X[J-1].label,{top:we,left:Re}=k4e(q,V,uR),Ne=m===F.id,ee=F.id;ut=y.jsxs(mn.div,{"data-rivet-carousel-pill":!0,className:"pointer-events-none fixed z-[48] flex items-center gap-1 rounded-lg border border-primary-border bg-main px-1 py-1 shadow-lg",style:{top:we,left:Re,width:uR},initial:{opacity:0,scale:.82,y:-4},animate:{opacity:1,scale:Ne?.985:1,y:0},transition:{type:"spring",stiffness:500,damping:28,mass:.8},onClick:ce=>ce.stopPropagation(),onKeyDown:ce=>{if(ce.key==="ArrowLeft"){ce.preventDefault(),D(ee,-1);return}if(ce.key==="ArrowRight"){ce.preventDefault(),D(ee,1);return}(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),O(ee))},children:[y.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Previous variation",onClick:ce=>{ce.stopPropagation(),D(ee,-1)},disabled:Ne||!!F.finalizedVariant,children:y.jsx(Eq,{className:"h-3.5 w-3.5",weight:"bold"})}),y.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:y.jsx(Fi,{mode:"wait",initial:!1,children:y.jsxs(mn.span,{className:"flex min-w-0 items-center truncate text-xs font-medium text-content",initial:{opacity:0,y:4},animate:{opacity:Ne?.7:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.14},children:[y.jsx("span",{className:"truncate",children:ae}),(ue==null?void 0:ue.codeStatus)==="error"&&y.jsx("span",{className:"ml-1.5 shrink-0 text-accent-error","aria-label":"Code generation failed",children:"!"})]},`overlay-variant-label-${ee}-${J}`)})}),y.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content","aria-label":"Apply this direction",onClick:ce=>{ce.stopPropagation(),O(ee)},children:y.jsx(na,{className:"h-3.5 w-3.5",weight:"bold"})}),y.jsx("button",{type:"button",className:"pointer-events-auto flex h-6 w-6 shrink-0 items-center justify-center rounded text-content-muted hover:text-content disabled:cursor-not-allowed disabled:opacity-50","aria-label":"Next variation",onClick:ce=>{ce.stopPropagation(),D(ee,1)},disabled:Ne||!!F.finalizedVariant,children:y.jsx(B9,{className:"h-3.5 w-3.5",weight:"bold"})})]},`pill-${ee}`)}const qe=ve?y.jsx(mn.div,{className:"pointer-events-none fixed z-[47]",style:{left:be,top:Me,width:_e,height:ke,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.06)",borderRadius:2,boxSizing:"border-box"},initial:{opacity:0},animate:{opacity:1,scale:1},exit:{opacity:0,scale:1.04},transition:{duration:.22,ease:[.32,.72,.34,1]},children:y.jsx("div",{className:"rivet-sparkle absolute left-0 top-0 overflow-hidden font-mono text-sm leading-none text-primary",style:{transform:"translateY(-100%)",height:"1em"},"aria-hidden":"true",children:y.jsx("div",{className:"rivet-sparkle-strip",children:_4e.map((ae,we)=>y.jsx("span",{className:"block",style:{height:"1em",lineHeight:"1em"},children:ae},we))})})},`gen-${F.id}`):null,ne=Ae?y.jsx(mn.div,{className:"pointer-events-none fixed z-[47]",style:{left:Qe,top:He,width:ze,height:ye,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box"},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},transition:{duration:.15,ease:[.32,.72,.34,1]}},`drag-${F.id}`):null;return y.jsxs(y.Fragment,{children:[y.jsx(Fi,{children:qe??ne}),y.jsx(Fi,{children:ut})]})};function E4e({reference:e,onRemove:t}){return y.jsxs("span",{className:"inline-flex max-w-[180px] items-center gap-1 rounded-full border border-divider bg-main-light px-2 py-0.5 text-[11px] text-content",children:[y.jsx(j9,{className:"h-3 w-3 shrink-0 text-content-muted",weight:"bold"}),y.jsx("span",{className:"truncate",title:e.label,children:e.label}),y.jsx("button",{type:"button",onClick:t,"aria-label":`Remove reference to ${e.label}`,className:"-mr-0.5 rounded-full p-0.5 text-content-muted transition-colors hover:bg-divider hover:text-content",children:y.jsx(ua,{className:"h-2.5 w-2.5",weight:"bold"})})]})}const S4e=Vt("CommentReferencePicker"),vg=(e,t)=>`${e}:${t}`,oB=e=>`direction-reference-option-${e}`,fR=(e,t,n)=>e.kind==="variant"&&e.sessionId===t&&e.variantId===n;function A4e({attached:e,commentTarget:t,onChange:n,onClose:r}){const i=Ee(Fs),s=Ee(Mv),o=i.active&&i.projectContext.kind==="fresh"&&i.projectContext.workspaceRoot?i.projectContext.workspaceRoot:s,a=h.useRef(null),l=h.useRef([]),u=h.useRef(!1),f=h.useRef(0),p=h.useRef(void 0),m=h.useRef(null),g=h.useRef(r);g.current=r;const[b,x]=h.useState([]),[k,w]=h.useState(0),C=h.useCallback(async()=>{const V=f.current+1;f.current=V;const U=o?`?projectPath=${encodeURIComponent(o)}`:"";try{const K=await fetch(`/api/variants/history${U}`,{credentials:"same-origin"});if(!K.ok)return;const W=await K.json();if(V!==f.current)return;const G=(W.variants??[]).filter(j=>{var H;return((H=j.preview)==null?void 0:H.kind)==="static"});x(G)}catch(K){S4e.warn("failed to load past directions for picker",K)}},[o]),E=h.useCallback(V=>{var W;if((W=m.current)==null||W.call(m),m.current=null,a.current=V,!V){f.current+=1,p.current=void 0;return}u.current||(u.current=!0,V.focus()),p.current!==o&&(p.current=o,C());const U=G=>{const j=a.current;j&&(j.contains(G.target)||g.current())},K=G=>{G.key==="Escape"&&g.current()};window.addEventListener("pointerdown",U),window.addEventListener("keydown",K),m.current=()=>{window.removeEventListener("pointerdown",U),window.removeEventListener("keydown",K)}},[o,C]),A=h.useMemo(()=>new Set(e.map(V=>vg(V.sessionId,V.variantId))),[e]),R=h.useMemo(()=>i.active?i.variants.filter(V=>V.status==="succeeded").filter(V=>!fR(t,i.sessionId,V.workItemId)).map(V=>({key:vg(i.sessionId,V.workItemId),reference:{sessionId:i.sessionId,variantId:V.workItemId,label:V.label||"Direction",origin:"live"}})):[],[i,t]),P=h.useMemo(()=>b.filter(V=>!fR(t,V.sessionId,V.variantId)).map(V=>({key:vg(V.sessionId,V.variantId),reference:{sessionId:V.sessionId,variantId:V.variantId,label:V.label||"Direction",origin:"history"},brief:V.brief})),[b,t]),I=h.useMemo(()=>{const V=new Set(R.map(U=>U.key));return P.filter(U=>!V.has(U.key))},[R,P]),T=h.useMemo(()=>{const V=[];return R.length>0&&V.push({heading:"This session",rows:R}),I.length>0&&V.push({heading:"Directions",rows:I}),V},[R,I]),L=h.useMemo(()=>T.flatMap(V=>V.rows),[T]),M=h.useMemo(()=>{const V=new Map;return L.forEach((U,K)=>V.set(U.key,K)),V},[L]),D=h.useCallback(V=>{const U=V.key;A.has(U)?n(e.filter(K=>vg(K.sessionId,K.variantId)!==U)):n([...e,V.reference])},[e,A,n]),O=k<L.length?k:0,F=V=>{var U;w(V),(U=l.current[V])==null||U.scrollIntoView({block:"nearest"})},Z=V=>{if(V.key==="Escape"){V.preventDefault(),r();return}const U=L.length;if(U!==0)switch(V.key){case"ArrowDown":{V.preventDefault(),F((O+1)%U);break}case"ArrowUp":{V.preventDefault(),F((O-1+U)%U);break}case"Enter":case" ":{V.preventDefault();const K=L[O];K&&D(K);break}}};return y.jsx("div",{ref:E,tabIndex:-1,onKeyDown:Z,className:"max-h-72 w-72 overflow-y-auto rounded-lg border border-divider bg-main shadow-2xl focus:outline-none",role:"listbox","aria-label":"Reference a direction","aria-activedescendant":L.length>0?oB(O):void 0,children:T.length===0?y.jsx("div",{className:"px-3 py-4 text-xs text-content-muted",children:"No directions available to reference yet."}):T.map(V=>y.jsx(T4e,{section:V,attachedKeys:A,highlightedIndex:O,indexOf:U=>M.get(U)??-1,itemRefs:l,onToggle:D,onHover:w},V.heading))})}function T4e({section:e,attachedKeys:t,highlightedIndex:n,indexOf:r,itemRefs:i,onToggle:s,onHover:o}){return y.jsxs("div",{children:[y.jsx("div",{className:"sticky top-0 z-10 border-b border-divider bg-main px-3 py-1.5 text-[10px] font-medium uppercase tracking-wider text-content-muted",children:e.heading}),y.jsx("ul",{className:"py-1",children:e.rows.map(a=>{const l=t.has(a.key),u=r(a.key),f=u===n;return y.jsx("li",{children:y.jsxs("button",{type:"button",id:oB(u),ref:p=>{i.current[u]=p},role:"option",onClick:()=>s(a),onMouseEnter:()=>o(u),"aria-selected":l,className:`group flex w-full items-start gap-2 px-3 py-2 text-left transition-colors ${f?"bg-main-hover":"hover:bg-main-input"}`,children:[y.jsx("span",{className:`mt-0.5 inline-flex h-4 w-4 shrink-0 items-center justify-center rounded border ${l?"border-primary bg-primary text-white":"border-divider text-transparent group-hover:border-content-muted"}`,children:y.jsx(na,{className:"h-2.5 w-2.5",weight:"bold"})}),y.jsxs("span",{className:"min-w-0 flex-1",children:[y.jsx("span",{className:"block truncate text-sm text-content",children:a.reference.label}),a.brief?y.jsx("span",{className:"block truncate text-[11px] leading-snug text-content-muted",children:a.brief}):null]})]})},a.key)})})]})}const P4e=2,I4e=5,R4e=e=>Math.min(Math.max(e,P4e),I4e),M4e=()=>{const e=Ge($r),t=xi();return{generateVariantsForComment:h.useCallback(async({commentId:r,instruction:i,elementContext:s,requestedVariantCount:o,onVariantsReady:a})=>{const l=R4e(o);e(u=>{const f=u.get(r);if(!f)return u;const p=new Map(u);return p.set(r,{...f,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:l,styleVariants:Array.from({length:l},(m,g)=>({label:`Direction ${g+1}`,summary:"",changeSpec:""})),selectedVariantIndex:1,finalizedVariant:void 0}),p}),t==null||t.capture("variant_directions_generate_started",{instruction_length:i.length,variant_count:l});try{const{computedStyles:u,...f}=s,p=await fetch("/api/design/comment-variations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({instruction:i,variantCount:l,element:f})}),m=await p.json().catch(()=>({}));if(!p.ok)throw new Error(typeof m.error=="string"?m.error:"Could not generate variations");const g=m.variants;if(!Array.isArray(g)||g.length!==l)throw new Error("Invalid variation response");const b=g;if(e(x=>{const k=x.get(r);if(!k)return x;const w=1,C=b.length+1,E=typeof k.selectedVariantIndex=="number"?Math.min(Math.max(k.selectedVariantIndex,0),C-1):w,A=new Map(x);return A.set(r,{...k,styleVariants:b,selectedVariantIndex:E,variantGenerationStatus:"idle",variantGenerationError:void 0,requestedVariantCount:l,finalizedVariant:void 0}),A}),t==null||t.capture("variant_directions_generate_completed",{variant_count:b.length}),a){const x=b.map((k,w)=>({index:w+1,label:k.label,changeSpec:k.changeSpec??""})).filter(k=>k.changeSpec.trim().length>0);x.length>0&&a({commentId:r,sessionId:crypto.randomUUID(),instruction:i,elementContext:s,variants:x})}}catch(u){const f=u instanceof Error?u.message:"Could not generate variations";e(p=>{const m=p.get(r);if(!m)return p;const g=new Map(p);return g.set(r,{...m,variantGenerationStatus:void 0,variantGenerationError:void 0,requestedVariantCount:void 0,styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0}),g}),t==null||t.capture("variant_directions_generate_failed",{error_message:f})}},[t,e])}},$4e=e=>{if(!e.startsWith("data: "))return null;try{return JSON.parse(e.slice(6))}catch{return null}},aB=()=>{const e=Ge($r),t=Pk(),n=da(),r=xi();return{startCodeGeneration:h.useCallback(async({commentId:s,sessionId:o,instruction:a,elementContext:l,variants:u})=>{var g,b;e(x=>{const k=x.get(s);if(!(k!=null&&k.styleVariants))return x;const w=new Map(x),C=new Set(u.map(E=>E.index));return w.set(s,{...k,variantSessionId:o,styleVariants:k.styleVariants.map((E,A)=>C.has(A+1)?{...E,codeStatus:"pending"}:E)}),w}),r==null||r.capture("variant_code_gen_started",{variant_count:u.length,instruction_length:a.length});let f=0,p=0;const m=new AbortController;use(s,m);try{const x=n.get(ei),{computedStyles:k,...w}=l,C=await fetch("/api/design/generate-variant-code",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:o,instruction:a,element:w,variants:u,currentAppliedDiff:x==null?void 0:x.diff}),signal:m.signal});if(!C.ok||!C.body){r==null||r.capture("variant_code_gen_failed",{variant_count:u.length,status:C.status,reason:C.body?"non_ok_response":"missing_body"});return}const E=C.body.getReader(),A=new TextDecoder;let R="";for(;;){const{done:P,value:I}=await E.read();if(P)break;R+=A.decode(I,{stream:!0});const T=R.split(`
|
|
611
|
-
`);R=T.pop()??"";for(const L of T){const M=$4e(L.trim());if(M!=null&&M.type){if(M.type==="variant_completed"){const D=M.variantIndex,O=M.diff;f+=1,r==null||r.capture("variant_code_gen_variant_ready",{variant_index:D,variant_count:u.length}),e(V=>{const U=V.get(s);if(!(U!=null&&U.styleVariants))return V;const K=new Map(V),W=[...U.styleVariants],G=D-1;return W[G]&&(W[G]={...W[G],codeStatus:"ready",codeDiff:O}),K.set(s,{...U,styleVariants:W}),K});const F=n.get(Mc),Z=n.get(ei);F===s&&!Z&&((g=n.get($r).get(s))==null?void 0:g.selectedVariantIndex)===D&&!((b=n.get($r).get(s))!=null&&b.finalizedVariant)&&(t({commentId:s,variantIndex:D,diff:O}),fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:O,reverse:!1})}).then(V=>{V.ok||t(null)}).catch(()=>{t(null)}))}else if(M.type==="variant_error"){const D=M.variantIndex,O=M.error;p+=1,r==null||r.capture("variant_code_gen_variant_failed",{variant_index:D,variant_count:u.length,error_message:O}),e(F=>{const Z=F.get(s);if(!(Z!=null&&Z.styleVariants))return F;const V=new Map(F),U=[...Z.styleVariants],K=D-1;return U[K]&&(U[K]={...U[K],codeStatus:"error",codeError:O}),V.set(s,{...Z,styleVariants:U}),V})}}}}r==null||r.capture("variant_code_gen_completed",{variant_count:u.length,success_count:f,error_count:p})}catch(x){const k=x instanceof DOMException&&x.name==="AbortError",w=x instanceof Error?x.message:"Direction code generation failed";r==null||r.capture("variant_code_gen_failed",{variant_count:u.length,reason:k?"aborted":"exception",error_message:w}),e(C=>{const E=C.get(s);if(!(E!=null&&E.styleVariants))return C;const A=new Map(C);return A.set(s,{...E,styleVariants:E.styleVariants.map(R=>({...R,codeStatus:void 0,codeDiff:void 0}))}),A})}finally{dse(s)}},[r,e,t,n])}};var un;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const s={};for(const o of i)s[o]=o;return s},e.getValidEnumValues=i=>{const s=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(const a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(const o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(un||(un={}));var hR;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(hR||(hR={}));const ct=un.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wa=e=>{switch(typeof e){case"undefined":return ct.undefined;case"string":return ct.string;case"number":return Number.isNaN(e)?ct.nan:ct.number;case"boolean":return ct.boolean;case"function":return ct.function;case"bigint":return ct.bigint;case"symbol":return ct.symbol;case"object":return Array.isArray(e)?ct.array:e===null?ct.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ct.promise:typeof Map<"u"&&e instanceof Map?ct.map:typeof Set<"u"&&e instanceof Set?ct.set:typeof Date<"u"&&e instanceof Date?ct.date:ct.object;default:return ct.unknown}},Fe=un.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 ca 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(s){return s.message},r={_errors:[]},i=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let a=r,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(o))):a[u]=a[u]||{_errors:[]},a=a[u],l++}}};return i(this),r}static assert(t){if(!(t instanceof ca))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,un.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const i of this.issues)if(i.path.length>0){const s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}ca.create=e=>new ca(e);const S8=(e,t)=>{let n;switch(e.code){case Fe.invalid_type:e.received===ct.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Fe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,un.jsonStringifyReplacer)}`;break;case Fe.unrecognized_keys:n=`Unrecognized key(s) in object: ${un.joinValues(e.keys,", ")}`;break;case Fe.invalid_union:n="Invalid input";break;case Fe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${un.joinValues(e.options)}`;break;case Fe.invalid_enum_value:n=`Invalid enum value. Expected ${un.joinValues(e.options)}, received '${e.received}'`;break;case Fe.invalid_arguments:n="Invalid function arguments";break;case Fe.invalid_return_type:n="Invalid function return type";break;case Fe.invalid_date:n="Invalid date";break;case Fe.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}"`:un.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Fe.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 Fe.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 Fe.custom:n="Invalid input";break;case Fe.invalid_intersection_types:n="Intersection results could not be merged";break;case Fe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Fe.not_finite:n="Number must be finite";break;default:n=t.defaultError,un.assertNever(e)}return{message:n}};let D4e=S8;function N4e(){return D4e}const L4e=e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}};function Xe(e,t){const n=N4e(),r=L4e({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===S8?void 0:S8].filter(i=>!!i)});e.common.issues.push(r)}class Bi{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 i of n){if(i.status==="aborted")return Tt;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const i of n){const s=await i.key,o=await i.value;r.push({key:s,value:o})}return Bi.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const i of n){const{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return Tt;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:t.value,value:r}}}const Tt=Object.freeze({status:"aborted"}),Hh=e=>({status:"dirty",value:e}),ls=e=>({status:"valid",value:e}),pR=e=>e.status==="aborted",mR=e=>e.status==="dirty",qd=e=>e.status==="valid",lv=e=>typeof Promise<"u"&&e instanceof Promise;var mt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(mt||(mt={}));class xl{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}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 gR=(e,t)=>{if(qd(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 ca(e.common.issues);return this._error=n,this._error}}};function Ut(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=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:i}:{errorMap:(o,a)=>{const{message:l}=e;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:i}}class ln{get description(){return this._def.description}_getType(t){return Wa(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Wa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Bi,ctx:{common:t.parent.common,data:t.data,parsedType:Wa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(lv(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==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)},i=this._parseSync({data:t,path:r.path,parent:r});return gR(r,i)}"~validate"(t){var r,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return qd(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(i=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>qd(s)?{value:s.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==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(lv(i)?i:Promise.resolve(i));return gR(r,s)}refine(t,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,s)=>{const o=t(i),a=()=>s.addIssue({code:Fe.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Uc({schema:this,typeName:Rt.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 ea.create(this,this._def)}nullable(){return Zc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return po.create(this)}promise(){return hv.create(this,this._def)}or(t){return uv.create([this,t],this._def)}and(t){return dv.create(this,t,this._def)}transform(t){return new Uc({...Ut(this._def),schema:this,typeName:Rt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new pv({...Ut(this._def),innerType:this,defaultValue:n,typeName:Rt.ZodDefault})}brand(){return new dB({typeName:Rt.ZodBranded,type:this,...Ut(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new mv({...Ut(this._def),innerType:this,catchValue:n,typeName:Rt.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Rk.create(this,t)}readonly(){return gv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const j4e=/^c[^\s-]{8,}$/i,F4e=/^[0-9a-z]+$/,O4e=/^[0-9A-HJKMNP-TV-Z]{26}$/i,V4e=/^[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,H4e=/^[a-z0-9_-]{21}$/i,B4e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,z4e=/^[-+]?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)?)??$/,U4e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Z4e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pw;const W4e=/^(?:(?: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])$/,G4e=/^(?:(?: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])$/,q4e=/^(([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]))$/,K4e=/^(([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])$/,Y4e=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,X4e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lB="((\\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])))",Q4e=new RegExp(`^${lB}$`);function cB(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 J4e(e){return new RegExp(`^${cB(e)}$`)}function e6e(e){let t=`${lB}T${cB(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 t6e(e,t){return!!((t==="v4"||!t)&&W4e.test(e)||(t==="v6"||!t)&&q4e.test(e))}function n6e(e,t){if(!B4e.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,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function r6e(e,t){return!!((t==="v4"||!t)&&G4e.test(e)||(t==="v6"||!t)&&K4e.test(e))}class ol extends ln{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ct.string){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.string,received:s.parsedType}),Tt}const r=new Bi;let i;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const o=t.data.length>s.value,a=t.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(t,i),o?Xe(i,{code:Fe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Xe(i,{code:Fe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")U4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"email",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")pw||(pw=new RegExp(Z4e,"u")),pw.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"emoji",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")V4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"uuid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")H4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"nanoid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")j4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cuid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")F4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cuid2",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")O4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"ulid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Xe(i,{validation:"url",code:Fe.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"regex",code:Fe.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?e6e(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Q4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?J4e(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?z4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"duration",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?t6e(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"ip",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?n6e(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"jwt",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?r6e(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cidr",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Y4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"base64",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?X4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"base64url",code:Fe.invalid_string,message:s.message}),r.dirty()):un.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:Fe.invalid_string,...mt.errToObj(r)})}_addCheck(t){return new ol({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...mt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...mt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...mt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...mt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...mt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...mt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...mt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...mt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...mt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...mt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...mt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...mt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...mt.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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...mt.errToObj(t==null?void 0: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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...mt.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...mt.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...mt.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...mt.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...mt.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...mt.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...mt.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...mt.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...mt.errToObj(n)})}nonempty(t){return this.min(1,mt.errToObj(t))}trim(){return new ol({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ol({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ol({...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}}ol.create=e=>new ol({checks:[],typeName:Rt.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Ut(e)});function i6e(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}class Kd extends ln{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)!==ct.number){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.number,received:s.parsedType}),Tt}let r;const i=new Bi;for(const s of this._def.checks)s.kind==="int"?un.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?i6e(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_finite,message:s.message}),i.dirty()):un.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,mt.toString(n))}gt(t,n){return this.setLimit("min",t,!1,mt.toString(n))}lte(t,n){return this.setLimit("max",t,!0,mt.toString(n))}lt(t,n){return this.setLimit("max",t,!1,mt.toString(n))}setLimit(t,n,r,i){return new Kd({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:mt.toString(i)}]})}_addCheck(t){return new Kd({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:mt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:mt.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:mt.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:mt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:mt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:mt.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"&&un.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)}}Kd.create=e=>new Kd({checks:[],typeName:Rt.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ut(e)});class Vp extends ln{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)!==ct.bigint)return this._getInvalidInput(t);let r;const i=new Bi;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):un.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Xe(n,{code:Fe.invalid_type,expected:ct.bigint,received:n.parsedType}),Tt}gte(t,n){return this.setLimit("min",t,!0,mt.toString(n))}gt(t,n){return this.setLimit("min",t,!1,mt.toString(n))}lte(t,n){return this.setLimit("max",t,!0,mt.toString(n))}lt(t,n){return this.setLimit("max",t,!1,mt.toString(n))}setLimit(t,n,r,i){return new Vp({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:mt.toString(i)}]})}_addCheck(t){return new Vp({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:mt.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}}Vp.create=e=>new Vp({checks:[],typeName:Rt.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Ut(e)});class A8 extends ln{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ct.boolean){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.boolean,received:r.parsedType}),Tt}return ls(t.data)}}A8.create=e=>new A8({typeName:Rt.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ut(e)});class cv extends ln{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ct.date){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.date,received:s.parsedType}),Tt}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_date}),Tt}const r=new Bi;let i;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):un.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cv({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:mt.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:mt.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}}cv.create=e=>new cv({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Rt.ZodDate,...Ut(e)});class vR extends ln{_parse(t){if(this._getType(t)!==ct.symbol){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.symbol,received:r.parsedType}),Tt}return ls(t.data)}}vR.create=e=>new vR({typeName:Rt.ZodSymbol,...Ut(e)});class T8 extends ln{_parse(t){if(this._getType(t)!==ct.undefined){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.undefined,received:r.parsedType}),Tt}return ls(t.data)}}T8.create=e=>new T8({typeName:Rt.ZodUndefined,...Ut(e)});class P8 extends ln{_parse(t){if(this._getType(t)!==ct.null){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.null,received:r.parsedType}),Tt}return ls(t.data)}}P8.create=e=>new P8({typeName:Rt.ZodNull,...Ut(e)});class yR extends ln{constructor(){super(...arguments),this._any=!0}_parse(t){return ls(t.data)}}yR.create=e=>new yR({typeName:Rt.ZodAny,...Ut(e)});class I8 extends ln{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ls(t.data)}}I8.create=e=>new I8({typeName:Rt.ZodUnknown,...Ut(e)});class wl extends ln{_parse(t){const n=this._getOrReturnCtx(t);return Xe(n,{code:Fe.invalid_type,expected:ct.never,received:n.parsedType}),Tt}}wl.create=e=>new wl({typeName:Rt.ZodNever,...Ut(e)});class bR extends ln{_parse(t){if(this._getType(t)!==ct.undefined){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.void,received:r.parsedType}),Tt}return ls(t.data)}}bR.create=e=>new bR({typeName:Rt.ZodVoid,...Ut(e)});class po extends ln{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==ct.array)return Xe(n,{code:Fe.invalid_type,expected:ct.array,received:n.parsedType}),Tt;if(i.exactLength!==null){const o=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(o||a)&&(Xe(n,{code:o?Fe.too_big:Fe.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(Xe(n,{code:Fe.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(Xe(n,{code:Fe.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>i.type._parseAsync(new xl(n,o,n.path,a)))).then(o=>Bi.mergeArray(r,o));const s=[...n.data].map((o,a)=>i.type._parseSync(new xl(n,o,n.path,a)));return Bi.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new po({...this._def,minLength:{value:t,message:mt.toString(n)}})}max(t,n){return new po({...this._def,maxLength:{value:t,message:mt.toString(n)}})}length(t,n){return new po({...this._def,exactLength:{value:t,message:mt.toString(n)}})}nonempty(t){return this.min(1,t)}}po.create=(e,t)=>new po({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Rt.ZodArray,...Ut(t)});function qu(e){if(e instanceof or){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ea.create(qu(r))}return new or({...e._def,shape:()=>t})}else return e instanceof po?new po({...e._def,type:qu(e.element)}):e instanceof ea?ea.create(qu(e.unwrap())):e instanceof Zc?Zc.create(qu(e.unwrap())):e instanceof Bc?Bc.create(e.items.map(t=>qu(t))):e}class or extends ln{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=un.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==ct.object){const u=this._getOrReturnCtx(t);return Xe(u,{code:Fe.invalid_type,expected:ct.object,received:u.parsedType}),Tt}const{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof wl&&this._def.unknownKeys==="strip"))for(const u in i.data)o.includes(u)||a.push(u);const l=[];for(const u of o){const f=s[u],p=i.data[u];l.push({key:{status:"valid",value:u},value:f._parse(new xl(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof wl){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(u==="strict")a.length>0&&(Xe(i,{code:Fe.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of a){const p=i.data[f];l.push({key:{status:"valid",value:f},value:u._parse(new xl(i,p,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of l){const p=await f.key,m=await f.value;u.push({key:p,value:m,alwaysSet:f.alwaysSet})}return u}).then(u=>Bi.mergeObjectSync(r,u)):Bi.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return mt.errToObj,new or({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o;const i=((o=(s=this._def).errorMap)==null?void 0:o.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:mt.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new or({...this._def,unknownKeys:"strip"})}passthrough(){return new or({...this._def,unknownKeys:"passthrough"})}extend(t){return new or({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new or({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Rt.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new or({...this._def,catchall:t})}pick(t){const n={};for(const r of un.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new or({...this._def,shape:()=>n})}omit(t){const n={};for(const r of un.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new or({...this._def,shape:()=>n})}deepPartial(){return qu(this)}partial(t){const n={};for(const r of un.objectKeys(this.shape)){const i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new or({...this._def,shape:()=>n})}required(t){const n={};for(const r of un.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ea;)s=s._def.innerType;n[r]=s}return new or({...this._def,shape:()=>n})}keyof(){return uB(un.objectKeys(this.shape))}}or.create=(e,t)=>new or({shape:()=>e,unknownKeys:"strip",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});or.strictCreate=(e,t)=>new or({shape:()=>e,unknownKeys:"strict",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});or.lazycreate=(e,t)=>new or({shape:e,unknownKeys:"strip",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});class uv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=s.map(a=>new ca(a.ctx.common.issues));return Xe(n,{code:Fe.invalid_union,unionErrors:o}),Tt}if(n.common.async)return Promise.all(r.map(async s=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s;const o=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const a=o.map(l=>new ca(l));return Xe(n,{code:Fe.invalid_union,unionErrors:a}),Tt}}get options(){return this._def.options}}uv.create=(e,t)=>new uv({options:e,typeName:Rt.ZodUnion,...Ut(t)});const Ho=e=>e instanceof M8?Ho(e.schema):e instanceof Uc?Ho(e.innerType()):e instanceof fv?[e.value]:e instanceof zc?e.options:e instanceof $8?un.objectValues(e.enum):e instanceof pv?Ho(e._def.innerType):e instanceof T8?[void 0]:e instanceof P8?[null]:e instanceof ea?[void 0,...Ho(e.unwrap())]:e instanceof Zc?[null,...Ho(e.unwrap())]:e instanceof dB||e instanceof gv?Ho(e.unwrap()):e instanceof mv?Ho(e._def.innerType):[];class Ik extends ln{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ct.object)return Xe(n,{code:Fe.invalid_type,expected:ct.object,received:n.parsedType}),Tt;const r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(Xe(n,{code:Fe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const i=new Map;for(const s of n){const o=Ho(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of o){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,s)}}return new Ik({typeName:Rt.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Ut(r)})}}function R8(e,t){const n=Wa(e),r=Wa(t);if(e===t)return{valid:!0,data:e};if(n===ct.object&&r===ct.object){const i=un.objectKeys(t),s=un.objectKeys(e).filter(a=>i.indexOf(a)!==-1),o={...e,...t};for(const a of s){const l=R8(e[a],t[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===ct.array&&r===ct.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],l=R8(o,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===ct.date&&r===ct.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class dv extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=(s,o)=>{if(pR(s)||pR(o))return Tt;const a=R8(s.value,o.value);return a.valid?((mR(s)||mR(o))&&n.dirty(),{status:n.value,value:a.data}):(Xe(r,{code:Fe.invalid_intersection_types}),Tt)};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(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}dv.create=(e,t,n)=>new dv({left:e,right:t,typeName:Rt.ZodIntersection,...Ut(n)});class Bc extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ct.array)return Xe(r,{code:Fe.invalid_type,expected:ct.array,received:r.parsedType}),Tt;if(r.data.length<this._def.items.length)return Xe(r,{code:Fe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Tt;!this._def.rest&&r.data.length>this._def.items.length&&(Xe(r,{code:Fe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new xl(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>Bi.mergeArray(n,o)):Bi.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Bc({...this._def,rest:t})}}Bc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bc({items:e,typeName:Rt.ZodTuple,rest:null,...Ut(t)})};class xR extends ln{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!==ct.map)return Xe(r,{code:Fe.invalid_type,expected:ct.map,received:r.parsedType}),Tt;const i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([a,l],u)=>({key:i._parse(new xl(r,a,r.path,[u,"key"])),value:s._parse(new xl(r,l,r.path,[u,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,f=await l.value;if(u.status==="aborted"||f.status==="aborted")return Tt;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const u=l.key,f=l.value;if(u.status==="aborted"||f.status==="aborted")return Tt;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}}}}xR.create=(e,t,n)=>new xR({valueType:t,keyType:e,typeName:Rt.ZodMap,...Ut(n)});class Hp extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ct.set)return Xe(r,{code:Fe.invalid_type,expected:ct.set,received:r.parsedType}),Tt;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(Xe(r,{code:Fe.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(Xe(r,{code:Fe.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const s=this._def.valueType;function o(l){const u=new Set;for(const f of l){if(f.status==="aborted")return Tt;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}const a=[...r.data.values()].map((l,u)=>s._parse(new xl(r,l,r.path,u)));return r.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(t,n){return new Hp({...this._def,minSize:{value:t,message:mt.toString(n)}})}max(t,n){return new Hp({...this._def,maxSize:{value:t,message:mt.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Hp.create=(e,t)=>new Hp({valueType:e,minSize:null,maxSize:null,typeName:Rt.ZodSet,...Ut(t)});class M8 extends ln{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})}}M8.create=(e,t)=>new M8({getter:e,typeName:Rt.ZodLazy,...Ut(t)});class fv extends ln{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Xe(n,{received:n.data,code:Fe.invalid_literal,expected:this._def.value}),Tt}return{status:"valid",value:t.data}}get value(){return this._def.value}}fv.create=(e,t)=>new fv({value:e,typeName:Rt.ZodLiteral,...Ut(t)});function uB(e,t){return new zc({values:e,typeName:Rt.ZodEnum,...Ut(t)})}class zc extends ln{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Xe(n,{expected:un.joinValues(r),received:n.parsedType,code:Fe.invalid_type}),Tt}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 Xe(n,{received:n.data,code:Fe.invalid_enum_value,options:r}),Tt}return ls(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 zc.create(t,{...this._def,...n})}exclude(t,n=this._def){return zc.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}zc.create=uB;class $8 extends ln{_parse(t){const n=un.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==ct.string&&r.parsedType!==ct.number){const i=un.objectValues(n);return Xe(r,{expected:un.joinValues(i),received:r.parsedType,code:Fe.invalid_type}),Tt}if(this._cache||(this._cache=new Set(un.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const i=un.objectValues(n);return Xe(r,{received:r.data,code:Fe.invalid_enum_value,options:i}),Tt}return ls(t.data)}get enum(){return this._def.values}}$8.create=(e,t)=>new $8({values:e,typeName:Rt.ZodNativeEnum,...Ut(t)});class hv extends ln{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ct.promise&&n.common.async===!1)return Xe(n,{code:Fe.invalid_type,expected:ct.promise,received:n.parsedType}),Tt;const r=n.parsedType===ct.promise?n.data:Promise.resolve(n.data);return ls(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}hv.create=(e,t)=>new hv({type:e,typeName:Rt.ZodPromise,...Ut(t)});class Uc extends ln{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Rt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o=>{Xe(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return Tt;const l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?Tt:l.status==="dirty"||n.value==="dirty"?Hh(l.value):l});{if(n.value==="aborted")return Tt;const a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?Tt:a.status==="dirty"||n.value==="dirty"?Hh(a.value):a}}if(i.type==="refinement"){const o=a=>{const l=i.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Tt:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?Tt:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!qd(o))return Tt;const a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>qd(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:n.value,value:a})):Tt);un.assertNever(i)}}Uc.create=(e,t,n)=>new Uc({schema:e,typeName:Rt.ZodEffects,effect:t,...Ut(n)});Uc.createWithPreprocess=(e,t,n)=>new Uc({schema:t,effect:{type:"preprocess",transform:e},typeName:Rt.ZodEffects,...Ut(n)});class ea extends ln{_parse(t){return this._getType(t)===ct.undefined?ls(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ea.create=(e,t)=>new ea({innerType:e,typeName:Rt.ZodOptional,...Ut(t)});class Zc extends ln{_parse(t){return this._getType(t)===ct.null?ls(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Zc.create=(e,t)=>new Zc({innerType:e,typeName:Rt.ZodNullable,...Ut(t)});class pv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===ct.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}pv.create=(e,t)=>new pv({innerType:e,typeName:Rt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ut(t)});class mv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return lv(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ca(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ca(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}mv.create=(e,t)=>new mv({innerType:e,typeName:Rt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ut(t)});class wR extends ln{_parse(t){if(this._getType(t)!==ct.nan){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.nan,received:r.parsedType}),Tt}return{status:"valid",value:t.data}}}wR.create=e=>new wR({typeName:Rt.ZodNaN,...Ut(e)});class dB extends ln{_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 Rk extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Tt:s.status==="dirty"?(n.dirty(),Hh(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Tt:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new Rk({in:t,out:n,typeName:Rt.ZodPipeline})}}class gv extends ln{_parse(t){const n=this._def.innerType._parse(t),r=i=>(qd(i)&&(i.value=Object.freeze(i.value)),i);return lv(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}}gv.create=(e,t)=>new gv({innerType:e,typeName:Rt.ZodReadonly,...Ut(t)});var Rt;(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"})(Rt||(Rt={}));const Be=ol.create,mo=Kd.create,_l=A8.create,s6e=I8.create;wl.create;const Xn=po.create,kr=or.create;uv.create;const fB=Ik.create;dv.create;Bc.create;const vv=fv.create,ki=zc.create;hv.create;ea.create;Zc.create;var o6e={};const a6e=(o6e.LOG_LEVEL||"INFO").toUpperCase();pi.setLevel(pi.levels[a6e]||pi.levels.INFO);const hB=[/^10\./,/^127\./,/^192\.168\./,/^169\.254\./,/^172\.(1[6-9]|2\d|3[0-1])\./,/^0\./,/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./],l6e=[/^::1$/i,/^fe80:/i,/^f[cd][0-9a-f]{2}:/i],c6e=e=>{const t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(e);if(!t)return!1;const n=t[1];return hB.some(r=>r.test(n))},u6e=[/^localhost$/i,/\.localhost$/i,/^localhost\./i,/\.local$/i,/\.internal$/i,/\.lan$/i,/\.intranet$/i],d6e=e=>{const t=e.trim();if(!t)return{ok:!1,reason:"URL is empty."};let n;try{n=new URL(t)}catch{return{ok:!1,reason:`URL is not valid: ${t}`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{ok:!1,reason:`Only HTTP and HTTPS inspiration links are supported (got '${n.protocol.replace(/:$/,"")}').`};const r=n.hostname.toLowerCase();return r?f6e(r)?{ok:!1,reason:`URL hostname '${r}' resolves to a local or private-network target.`}:(n.hash="",{ok:!0,url:n,normalized:n.toString()}):{ok:!1,reason:"URL is missing a hostname."}},f6e=e=>{const t=e.replace(/^\[|\]$/g,"");return!!(hB.some(n=>n.test(t))||l6e.some(n=>n.test(t))||c6e(t)||u6e.some(n=>n.test(t)))},h6e=kr({kind:vv("existing")}),pB=5e4,p6e=120,ta=2048,m6e=80,g6e=8e3,Ss=400,gi=24,v6e=16,y6e=ki(["design_source","interaction_reference","asset_source","content_reference","other"]),b6e=ki(["low","medium","high"]),x6e=kr({url:Be().min(1).max(ta).optional(),imageRef:Be().min(1).max(64).optional(),role:y6e,confidence:b6e,reason:Be().min(1).max(Ss)}).refine(e=>!!e.url!=!!e.imageRef,{message:"sourceIntent entry must specify exactly one of `url` or `imageRef`."}),mB=kr({sources:Xn(x6e).min(1).max(gi)}),gB=fB("kind",[kr({kind:vv("slug"),slug:Be().min(1).max(p6e)}),kr({kind:vv("markdown"),content:Be().min(1).max(pB),label:Be().min(1).max(60)})]),w6e=ki(["urlText","siteBrief","visualBrief","screenshotNotes","motionBrief"]),vB=kr({kind:w6e,label:Be().min(1).max(m6e),content:Be().min(1).max(g6e)}),_6e=ki(["primary","inspiration","competitor"]),k6e=kr({url:Be().min(1).max(ta),role:_6e,rationale:Be().min(1).max(Ss).optional()}),yB=kr({sourceFindings:Xn(Be().min(1).max(Ss)).min(1).max(gi),sectionInventory:Xn(Be().min(1).max(Ss)).min(1).max(gi),visualObservations:Xn(Be().min(1).max(Ss)).min(1).max(gi),sourceRoles:Xn(k6e).min(1).max(gi),qualityBar:Xn(Be().min(1).max(Ss)).min(1).max(gi),screenshotReferences:Xn(Be().min(1).max(Ss)).max(v6e).optional(),risks:Xn(Be().min(1).max(Ss)).max(gi).optional()}),bB=kr({sourceUrls:Xn(Be().min(1).max(ta)).max(gi).optional(),preserveBrand:_l().optional(),sourceArtifacts:Xn(vB).max(gi).optional(),artifact:yB.optional(),sourceIntent:mB.optional(),designDecision:ki(["let_rivet_choose","go_custom"]).optional()}),C6e=ki(["static_preview","vite_app"]),E6e=ki(["low","medium","high"]),S6e=kr({source:Be().min(1).max(ta),destination:Be().min(1).max(ta),referenceAs:Be().min(1).max(ta)}),xB=kr({mode:C6e,confidence:E6e,reason:Be().min(1).max(Ss),assetPlan:Xn(S6e).max(gi).optional(),runtimeRequirements:Xn(Be().min(1).max(Ss)).max(gi).optional(),userQuestion:Be().min(1).max(Ss).optional()}),A6e=kr({kind:vv("fresh"),workspacePath:Be().min(1),workspaceRoot:Be().min(1),framework:ki(["vite","next","astro","remix"]).optional(),assetSourceRoot:Be().min(1).max(ta).optional(),designContext:Xn(gB).optional(),sourceContext:bB.optional(),executionPlan:xB.optional()}),T6e=fB("kind",[h6e,A6e]),wB=kr({type:ki(["element","file","route"]),ref:Be().min(1)}),_B=kr({briefId:Be().min(1),label:Be().min(1).max(40).describe('≤ 4 words. Rendered as the variant card title in the UI. e.g. "Spring blur", "Linear sharp".'),body:Be().min(1).max(200).describe(`Exactly ONE sentence, ≤ 12 words. Single evocative descriptor of the variant's direction — what makes it distinct. Rendered as the card subtitle. e.g. "Apple-style spring physics with ambient blur and soft edges". No bullets, no lists, no line breaks.`),visualReferenceUrl:Be().url().refine(e=>d6e(e).ok,{message:"visualReferenceUrl must be an HTTP(S) URL that does not target local or private networks"}).optional().describe("Optional HTTP(S) inspiration URL. Subject to SSRF guard — must not resolve to local or private network targets.")}),Yd=2,Xd=8;Be().optional(),Be().optional(),Be().min(1),mo().int().min(Yd).max(Xd).optional(),wB.optional(),T6e.optional();Be().min(1),Be().min(1),mo().int().nonnegative(),Be().optional(),Xn(_B).min(1).max(8);const P6e=kr({url:Be().min(1).max(ta).optional(),imageRef:Be().min(1).max(64).optional(),label:Be().min(1).max(60),markdown:Be().min(1).max(pB)}).refine(e=>!!e.url!=!!e.imageRef,{message:"designContexts entry must specify exactly one of `url` or `imageRef`."});kr({sourceIntent:mB,sourceContext:yB,designContexts:Xn(P6e).max(gi).optional(),executionPlan:xB});Be().min(1),Be().min(1),mo().int().nonnegative(),Be().min(1);Be().min(1),Xn(Be().min(1)).min(1).max(8).optional(),_l().optional(),_l().optional(),Be().min(1).optional(),Xn(kr({briefId:Be().min(1),bodyOverride:Be().optional()})).min(1).max(8).optional();Be().min(1),Be().min(1),_l().optional(),_l().optional(),Be().min(1).optional();ki(["check","wait","request_work","refine_variant"]).optional();Be().min(1),Be().optional(),mo().int().min(1).max(8).optional(),Be().min(1).optional(),Be().min(1).optional();ki(["running","succeeded","failed","cancelled"]);Be().min(1),Be().min(1),Be().min(1),mo().int().nonnegative(),s6e().optional(),kr({code:Be(),message:Be()}).optional(),Be().optional(),mo().int().nonnegative().optional(),mo().int().nonnegative().optional(),Be().optional();Be().min(1),mo().int().min(Yd).max(Xd),Xn(Be().min(1).max(ta)).max(gi).optional(),_l().optional(),Xn(vB).max(gi).optional(),_l().optional(),Be().optional();Be().min(1),Be().optional();Be().min(1),Be().min(1),Be().optional();ki(["existing","zero_to_one"]).describe('"existing": vary an existing project at projectPath/cwd (spawns code_gen items). "zero_to_one": prompt-only fresh project; server derives destinationPath (spawns static_preview items).');const I6e=_B.omit({briefId:!0});Be().min(1),mo().int().min(Yd).max(Xd).optional(),wB.optional(),Xn(I6e).min(Yd).max(Xd).optional().describe("One brief per variant. `briefs.length` sets the variant count (3-5); do NOT also pass `count`. Each brief MUST describe a distinct direction — never copy the user prompt verbatim into a body."),ki(["vite"]).optional(),Be().optional(),Be().optional(),Xn(gB).optional(),bB.optional(),Be().optional();const R6e=ki(["completed","committed","rejected","cancelled"]);Be().optional(),mo().int().min(1).max(500).optional(),R6e.optional();Be().optional(),Be().min(1),Be().min(1),_l().optional();const _R=3,M6e=[/\bvariants?\s*[:=]\s*(\d+)(?!\.\d)\b/i,/\b(\d+)(?!\.\d)\s*variants?\b/i,/\bvariants?\s+(\d+)(?!\.\d)\b/i],$6e=e=>e<Yd?Yd:e>Xd?Xd:e,kR=e=>{if(!e)return _R;for(const t of M6e){const n=t.exec(e);if(!n)continue;const r=n[1];if(!/^\d+$/.test(r))continue;const i=Number.parseInt(r,10);if(!(!Number.isInteger(i)||i<=0))return $6e(i)}return _R},CR=8,ER=320,SR=8,AR=3,D6e=15e3,N6e=.65,L6e=({elementContext:e,target:t=uo,pin:n,dragBox:r,position:i,onClose:s,existingCommentId:o,isMCPSession:a=!1,onInputChange:l,shake:u})=>{var ce,ge;const f=xi(),p=gee(),[m,g]=zn($r),b=Ee(nf),k=Ee(vo).variants.isEnabled,w=Ge(Mc),C=Ge(yo),E=Ge(Qp),A=Ge($c),R=Ge(H3),P=da(),{generateVariantsForComment:I}=M4e(),{sendVariantRequestComment:T}=jD(),{startCodeGeneration:L}=aB(),D=Ee(Fs).active===!0,O=Ee(Iv),F=o?m.get(o):void 0,Z=(F==null?void 0:F.instruction)??"",[V,U]=h.useState(Z),[K,W]=h.useState((F==null?void 0:F.images)??[]),[G,j]=h.useState((F==null?void 0:F.references)??[]),[H,B]=h.useState(!1),N=h.useRef(null),q=h.useRef(null),X=h.useRef(null);h.useEffect(()=>{const le=setTimeout(()=>{const he=N.current;he&&(he.focus(),he.selectionStart=he.selectionEnd=he.value.length)},150);return()=>clearTimeout(le)},[]);const te=h.useCallback(()=>{X.current&&(clearTimeout(X.current),X.current=null)},[]);h.useEffect(()=>()=>{te()},[te]);const ie=h.useRef(u);h.useEffect(()=>{u!==ie.current&&p.start({x:[0,-5,5,-4,4,-2,2,0],y:[0,1.5,-1.5,1,-1,.5,-.5,0],transition:{duration:.45,ease:"easeInOut"}})},[u,p]);const Y=V.trim()!==Z.trim()&&V.trim()!==""||K.length!==(((ce=F==null?void 0:F.images)==null?void 0:ce.length)??0)||G.length!==(((ge=F==null?void 0:F.references)==null?void 0:ge.length)??0),J=o?Y:V.trim()!=="",ue=h.useCallback(le=>{j(le),l==null||l(V.trim()!==""||K.length>0||le.length>0)},[V,K.length,l]),be=h.useCallback(le=>{ue(G.filter(he=>!(he.sessionId===le.sessionId&&he.variantId===le.variantId)))},[G,ue]),Me=h.useCallback(le=>{s(le)},[s]),_e=h.useCallback(le=>{le.style.height="auto",le.style.height=`${le.scrollHeight}px`},[]),ke=h.useCallback(le=>{S_(le).then(he=>{W(Se=>[...Se,he])}).catch(()=>{console.warn("[CommentPopover] Failed to process image:",le.name)})},[]),$e=h.useCallback(le=>{W(he=>[...he,le]),l==null||l(!0)},[l]),{isDragOver:Qe,dropHandlers:He}=BL($e),ze=le=>{const he=le.target.files;if(!he)return;let Se=!1;for(const Ke of Array.from(he))Ke.type.startsWith("image/")&&(ke(Ke),Se=!0);q.current&&(q.current.value=""),Se&&(l==null||l(!0))},ye=le=>{var Se;const he=(Se=le.clipboardData)==null?void 0:Se.items;if(he){for(const Ke of Array.from(he))if(Ke.type.startsWith("image/")){le.preventDefault();const Je=Ke.getAsFile();Je&&(ke(Je),l==null||l(!0))}}},nt=le=>{const he=K.filter((Se,Ke)=>Ke!==le);W(he),l==null||l(V.trim()!==""||he.length>0)},$t=h.useCallback(async le=>{var vt,nn;const he=V.trim();if(!he)return;const Se=(le==null?void 0:le.forceGenerateVariants)===!0&&!a,Ke=Se?{styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:AR}:{};if(Se&&o){IT(o);const Ft=P.get(ei);Ft&&Ft.commentId===o&&(await rd(Ft.diff),P.set(ei,null));const Jt=(nn=(vt=m.get(o))==null?void 0:vt.finalizedVariant)==null?void 0:nn.codeDiff;Jt&&await rd(Jt)}let Je;if(o)Je=o,g(Ft=>{const Jt=Ft.get(o);if(!Jt)return Ft;const dn=new Map(Ft);return dn.set(o,{...Jt,instruction:he,images:K.length>0?K:void 0,references:G.length>0?G:void 0,variantRequest:void 0,...Ke}),dn}),f==null||f.capture("comment_edited",{instruction_length:he.length,image_count:K.length,reference_count:G.length,has_variants:Se});else{const Ft=crypto.randomUUID();Je=Ft;const Jt={id:Ft,target:t,elementContext:e,pin:n,dragBox:r,instruction:he,images:K.length>0?K:void 0,references:G.length>0?G:void 0,...Ke,status:"pending"};g(dn=>{const Ce=new Map(dn);return Ce.set(Ft,Jt),Ce}),f==null||f.capture("comment_added",{instruction_length:he.length,image_count:K.length,reference_count:G.length,has_variants:Se})}Me({preserveSelection:!0}),Se&&(w(Je),I({commentId:Je,instruction:he,elementContext:e,requestedVariantCount:AR,onVariantsReady:Ft=>void L(Ft)}))},[V,K,G,o,e,t,n,r,m,g,f,a,I,L,Me,w,P]),ve=h.useCallback(async()=>{const le=V.trim();if(!le)return;const he=kR(V),Se=o??crypto.randomUUID();if(o)g(Je=>{const vt=Je.get(o);if(!vt)return Je;const nn=new Map(Je);return nn.set(o,{...vt,instruction:le,images:void 0,references:G.length>0?G:void 0,variantRequest:{count:he}}),nn}),f==null||f.capture("comment_edited",{instruction_length:le.length,image_count:0,reference_count:G.length,has_variants:!1});else{const Je={id:Se,target:t,elementContext:e,pin:n,dragBox:r,instruction:le,references:G.length>0?G:void 0,variantRequest:{count:he},status:"pending"};g(vt=>{const nn=new Map(vt);return nn.set(Se,Je),nn}),f==null||f.capture("comment_added",{instruction_length:le.length,image_count:0,reference_count:G.length,has_variants:!1})}f==null||f.capture("comment_variant_trigger_started",{source:"mcp",requestedCount:he}),te(),R(!0),X.current=setTimeout(()=>{X.current=null,R(!1)},D6e),A(!0),E(!0),C("view"),Me({preserveSelection:!0});const Ke=await T(Se);Ke.success||(te(),R(!1),Nt.error(Ke.error||"Failed to queue direction request"))},[V,G,o,e,t,n,r,g,f,Me,C,E,A,R,T,te]),Ae=$t,ut=h.useCallback(async()=>{var le;if(o){IT(o);const he=(b==null?void 0:b.current)??null;he&&hd(he,m.values());const Se=P.get(ei);Se&&Se.commentId===o&&(await rd(Se.diff),P.set(ei,null));const Ke=m.get(o),Je=(le=Ke==null?void 0:Ke.finalizedVariant)==null?void 0:le.codeDiff;Je&&await rd(Je),g(vt=>{const nn=new Map(vt);return nn.delete(o),nn}),f==null||f.capture("comment_deleted")}Me()},[o,m,b,g,Me,f,P]),qe=h.useCallback(le=>{le.key==="Enter"&&(le.metaKey||le.ctrlKey)&&(le.preventDefault(),le.nativeEvent.stopImmediatePropagation(),Ae()),le.key==="Escape"&&(le.nativeEvent.stopImmediatePropagation(),Me({preserveSelection:!0}))},[Ae,Me]),ne=window.innerHeight,ae=i.y/ne>N6e,we=o?"Save":"Add",Re=(()=>{if(V.trim()==="")return"empty_instruction";if(K.length>0)return"images_attached";if(D)return"active_session";if(O.getStyleChanges().length>0||O.getTextChanges().length>0)return"mixed_batch";const he=Array.from(m.values()).filter(Je=>Je.status==="pending"&&Je.id!==o);return he.some(Je=>!!Je.variantRequest)?"duplicate_variant_request":he.some(Je=>!Je.variantRequest)?"mixed_batch":null})(),Ne=kR(V),ee=(()=>{switch(Re){case"empty_instruction":return"Add an instruction to generate directions.";case"images_attached":return"Remove attached images — image context is not supported for directions yet.";case"mixed_batch":return"Directions must be sent on their own — clear other pending changes first.";case"duplicate_variant_request":return"A direction request is already pending — send or cancel it first.";case"active_session":return"A directions session is already running — finish or cancel it first.";default:return`Generate ${Ne} design directions for the selected element. You'll preview and pick one.`}})();return y.jsx("div",{className:"fixed z-comment-preview cursor-auto",style:{top:ae?i.y-CR:i.y+CR,left:Math.max(SR,Math.min(i.x-ER/2,window.innerWidth-ER-SR)),transform:ae?"translateY(-100%)":void 0},onClick:le=>le.stopPropagation(),children:y.jsx(mn.div,{animate:p,children:y.jsxs(mn.div,{className:"relative flex w-80 flex-col gap-2 rounded-xl bg-main p-4 shadow-2xl",style:{transformOrigin:"center 24px"},initial:{scale:.82,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.82,opacity:0,transition:{duration:.1,ease:[.55,0,1,.45]}},transition:{type:"spring",stiffness:500,damping:28,mass:.8},...He,children:[Qe?y.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-xl border-2 border-dashed border-primary bg-primary/10",children:y.jsx("span",{className:"text-sm font-medium text-content",children:"Drop image here"})}):null,G.length>0?y.jsx("div",{className:"flex flex-wrap gap-1.5",children:G.map(le=>y.jsx(E4e,{reference:le,onRemove:()=>be(le)},`${le.sessionId}:${le.variantId}`))}):null,y.jsx("textarea",{ref:le=>{N.current=le,le&&_e(le)},value:V,onChange:le=>{const he=le.target.value;U(le.target.value),_e(le.target),l==null||l(he.trim()!==""||K.length>0)},onKeyDown:qe,onPaste:ye,placeholder:"What should change?",rows:3,style:{maxHeight:"9rem",overflowY:"auto"},className:"w-full resize-none rounded-lg border border-divider bg-main-light p-3 text-sm text-content outline-none transition-colors duration-100 placeholder:text-content-subtle focus:border-primary focus:ring-1 focus:ring-primary/30"}),K.length>0?y.jsx("div",{className:"max-h-40 overflow-y-auto rounded",children:y.jsx("div",{className:`grid gap-1.5 ${K.length===1?"grid-cols-1":"grid-cols-2"}`,children:K.map((le,he)=>y.jsxs("div",{className:"relative",children:[y.jsx("img",{src:le,alt:`Reference ${he+1}`,className:`w-full rounded border border-divider object-cover ${K.length===1?"max-h-32":"aspect-[4/3]"}`}),y.jsx("button",{onClick:()=>nt(he),className:"absolute right-1 top-1 rounded-full bg-red-500/80 p-0.5 text-white backdrop-blur-sm hover:bg-red-600",children:y.jsx(ua,{className:"h-2.5 w-2.5",weight:"bold"})})]},he))})}):null,y.jsx("input",{ref:q,type:"file",accept:"image/*",multiple:!0,onChange:ze,className:"hidden"}),y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("div",{className:"flex items-center gap-1",children:[o?y.jsx("button",{type:"button",onClick:ut,className:"p-1 text-content-subtle transition-colors hover:text-accent-error",title:"Delete comment",children:y.jsx(Vq,{className:"h-4 w-4",weight:"bold"})}):null,y.jsx(Ts,{label:"Attach",children:y.jsx("button",{type:"button","aria-label":"Attach reference image",onClick:()=>{var le;return(le=q.current)==null?void 0:le.click()},className:"p-1 text-content-subtle transition-colors hover:text-content",children:y.jsx(J9,{className:"h-4 w-4",weight:"bold"})})}),y.jsx(Ts,{label:"Reference a direction",children:y.jsxs("div",{className:"relative",children:[y.jsx("button",{type:"button","aria-label":"Reference a direction","aria-haspopup":"listbox","aria-expanded":H,onClick:()=>B(le=>!le),className:`p-1 transition-colors ${H||G.length>0?"text-content":"text-content-subtle hover:text-content"}`,children:y.jsx(j9,{className:"h-4 w-4",weight:"bold"})}),H?y.jsx("div",{className:"absolute bottom-full left-0 z-20 mb-2",children:y.jsx(A4e,{attached:G,commentTarget:t,onChange:ue,onClose:()=>B(!1)})}):null]})}),!a&&k?y.jsx(Ts,{label:"Vary",children:y.jsx("button",{type:"button","aria-label":"Generate 3 directions",onClick:()=>Ae({forceGenerateVariants:!0}),disabled:!J,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:y.jsx(g1,{className:"h-4 w-4",weight:"bold"})})}):null,a?y.jsx(Ts,{label:ee,children:y.jsx("button",{type:"button","aria-label":"Generate directions","data-testid":"mcp-variant-trigger",onClick:()=>void ve(),disabled:Re!==null,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:y.jsx(g1,{className:"h-4 w-4",weight:"bold"})})}):null]}),y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsx("button",{type:"button",onClick:()=>Me(),className:"px-2 py-1.5 text-sm text-content-muted transition-colors hover:text-content",children:"Cancel"}),y.jsx("button",{onClick:()=>Ae(),disabled:!J,className:"rounded-full bg-primary px-5 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:we})]})]})]})})})},j6e="allow-scripts allow-same-origin allow-forms allow-popups allow-modals",F6e="allow-scripts allow-forms allow-popups allow-modals",O6e=e=>e==="embedded"?F6e:j6e,TR=Vt("PreviewSurface"),kB=({target:e,src:t,framework:n,mode:r,isUpstreamReady:i,remountKey:s})=>{const o=ra(e),a=Ge(cte),l=Ge(ute),u=Ge(Ms),f=Ee($r),p=Ge(O3),m=Ge(Mc),g=Ee(Jp),b=Ee($v),x=b==="embedded",k=Ee($c),w=Ge(Dc),[C,E]=zn(ED),[A,R]=h.useState(null),P=h.useRef(null),I=da(),[T,L]=zn(P1),M=h.useCallback(()=>I.get(Dc),[I]),D=T&&xp(T.target,e)?T:null,O=h.useRef(null),{enterEditMode:F}=l4e({iframeRef:O}),Z=Ee(vo);c4e({iframeRef:O,enabled:Z.resize.isEnabled&&!x,surfaceId:o});const V=h.useCallback(_e=>w(_e),[w]),U=h.useCallback((_e,ke,$e)=>{if(M()){E(Qe=>Qe+1);return}V(!1),p(null),m(null),u(e),L({key:crypto.randomUUID(),target:e,elementContext:_e,pin:ke,dragBox:$e})},[M,E,V,p,m,u,L,e]),K=h.useCallback(()=>{if(M()){E(_e=>_e+1);return}L(null),p(null),m(null),V(!1)},[M,E,L,V,p,m]),W=h.useCallback((_e,ke,$e)=>{F(_e,ke,$e)},[F]),{setupIframe:G,clearSelectionState:j,iframeRef:H}=a4e({surfaceId:o,target:e,mode:r,isBoxModelVisible:!0,onTextEdit:W,onCommentClick:U,onCommentSelectionClear:K,isPreviewBridgeEnabled:x}),B=h.useCallback(_e=>{L(null),p(null),m(null),V(!1),_e!=null&&_e.preserveSelection||j()},[j,L,V,p,m]),N=h.useCallback(()=>B({preserveSelection:!0}),[B]),{startCodeGeneration:q}=aB(),X=h.useCallback(_e=>{const ke=f.get(_e);if(!ke)return;V(!1);const $e=ke.styleVariants&&ke.styleVariants.length>0;if(p(_e),m($e?_e:null),u(e),L({key:crypto.randomUUID(),target:e,elementContext:ke.elementContext,pin:ke.pin,dragBox:ke.dragBox,existingCommentId:_e}),ke.variantGenerationStatus!=="generating"&&!ke.finalizedVariant&&ke.styleVariants&&!fse(_e)){const Qe=ke.styleVariants.map((He,ze)=>({v:He,index:ze+1})).filter(({v:He})=>He.changeSpec&&!He.codeDiff&&!He.codeStatus);Qe.length>0&&q({commentId:_e,sessionId:crypto.randomUUID(),instruction:ke.instruction,elementContext:ke.elementContext,variants:Qe.map(({v:He,index:ze})=>({index:ze,label:He.label,changeSpec:He.changeSpec}))})}},[f,V,p,m,u,L,e,q]),te=h.useCallback((_e,ke,$e=!1)=>{const Qe=H.current;if(!Qe)return null;const He=Qe.getBoundingClientRect(),ze=x?null:_r(Qe),ye=ze?fd(ze,_e):null,nt=(ye==null?void 0:ye.getBoundingClientRect())??_e.boundingRect,$t={top:He.top+nt.top,bottom:He.top+nt.bottom},ve=$e&&x4e($t);let Ae=He.top+nt.top+ke.elementYPct*nt.height;return $e&&(Ae=ve?He.top+nt.bottom+av+ov:He.top+nt.top-av-ov),{x:He.left+nt.left+ke.elementXPct*nt.width,y:Ae}},[x,H]),[,ie]=h.useState(0),Y=h.useCallback(()=>ie(_e=>_e+1),[]);h.useEffect(()=>{const _e=H.current;if(!D||!_e)return;const ke=x?null:_r(_e);ke&&ke.addEventListener("scroll",Y,!0);const $e=new ResizeObserver(Y);return $e.observe(_e),_e.addEventListener("load",Y),()=>{ke&&ke.removeEventListener("scroll",Y,!0),$e.disconnect(),_e.removeEventListener("load",Y)}},[D,H,Y,x]);const J=D!=null&&D.existingCommentId?(()=>{var ke;const _e=f.get(D.existingCommentId);return!!((ke=_e==null?void 0:_e.styleVariants)!=null&&ke.length&&!_e.finalizedVariant)})():!1,ue=D?te(D.elementContext,D.pin,J):null,be=i&&!k&&!x;h.useEffect(()=>{if(x){A&&(P.current=null,R(null),l({surfaceId:o,adapter:null}));return}if(n!=="static"&&!i){A&&(P.current=null,R(null),l({surfaceId:o,adapter:null}));return}const _e=H.current;if(A&&P.current!==_e){P.current=null,R(null),l({surfaceId:o,adapter:null});return}if(_e&&!A){const ke=n==="static";TR.debug(`Creating ${ke?"Static":""}IframeDisplayAdapter`);const $e=r==="edit"?"edit":"view",Qe=ke?new u4e(_e,{mode:$e,isBoxModelVisible:!0}):new tB(_e,{mode:$e,isBoxModelVisible:!0});Qe.initialize(),P.current=_e,R(Qe),l({surfaceId:o,adapter:Qe})}},[A,n,i,x,r,H,l,o]);const Me=h.useCallback(_e=>{_e?(G(_e),O.current=_e):O.current=null},[G]);return h.useEffect(()=>(a({surfaceId:o,ref:H}),()=>{a({surfaceId:o,ref:null}),l({surfaceId:o,adapter:null})}),[a,l,o,H]),h.useEffect(()=>{r!=="comment"&&(M()||(L(null),p(null),m(null),r==="view"&&j()))},[r,M,j,L,p,m]),y.jsxs("div",{className:"relative h-full w-full",children:[y.jsx("iframe",{ref:Me,src:t,className:"h-full w-full border-none",title:"Project Preview",sandbox:O6e(b),onLoad:()=>{St==null||St.capture("preview_iframe_loaded",{framework:n,src:t})},onError:()=>{St==null||St.capture("preview_iframe_load_failed",{framework:n,src:t}),TR.warn("Preview iframe failed to load",{framework:n,src:t})}},s),be?y.jsx(p4e,{onEditComment:X,target:e,iframeRef:H}):null,e.kind==="base"&&i&&!x&&!g&&!k?y.jsx(C4e,{onCommentClose:N}):null,(D==null?void 0:D.dragBox)&&!D.existingCommentId&&H.current&&(()=>{const _e=H.current,ke=_e.getBoundingClientRect(),$e=x?null:_r(_e),Qe=$e?fd($e,D.elementContext):null,He=(Qe==null?void 0:Qe.getBoundingClientRect())??D.elementContext.boundingRect,{leftPct:ze,topPct:ye,widthPct:nt,heightPct:$t}=D.dragBox;return y.jsx("div",{"data-comment-drag-box":"true",style:{position:"fixed",pointerEvents:"none",zIndex:45,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box",left:ke.left+He.left+ze*He.width,top:ke.top+He.top+ye*He.height,width:nt*He.width,height:$t*He.height}})})(),D&&ue&&!D.existingCommentId&&y.jsx(nB,{comment:{id:"draft",elementContext:D.elementContext,pin:D.pin,instruction:"",status:"pending"},index:f.size,position:ue,onDismiss:()=>{},onEdit:()=>{}}),tf.createPortal(y.jsx(Fi,{children:D&&ue?y.jsx(L6e,{elementContext:D.elementContext,target:e,pin:D.pin,dragBox:D.dragBox,position:ue,onClose:B,existingCommentId:D.existingCommentId,isMCPSession:g,onInputChange:_e=>{V(_e)},shake:C},D.key):null}),document.body)]})},V6e=({isInteractionDisabled:e=!1,framework:t,userPort:n,activeDemoSessionId:r=null,holdPreviewNavigation:i=!1})=>{const s=Ee(yo),o=Ee(c6),a=Ge(c6),l=Ee(I1),u=Ge(I1),f=Ee(Fs),p=Ee($v),m=Ee(u6),g=Ge(u6),b=f.active&&f.projectContext.kind==="fresh";h.useEffect(()=>{f.active||g(!1)},[f.active,g]);const x=h.useMemo(()=>{var G;if(m||l||!f.active)return null;const{stage:Z,variants:V}=f,U=Z==="ready"||Z==="degraded",K=V.some(j=>{var H,B;return((H=j.refinement)==null?void 0:H.status)==="pending"||((B=j.refinement)==null?void 0:B.status)==="running"});if(!U&&!K)return null;const W=V.find(j=>{var H;return j.status==="succeeded"&&((H=j.preview)==null?void 0:H.kind)==="static_artifact"});return((G=W==null?void 0:W.preview)==null?void 0:G.kind)==="static_artifact"?W.preview.url:null},[l,m,f]),k=l??x,w=h.useMemo(()=>!f.active||!k?null:f.variants.find(Z=>{var V;return((V=Z.preview)==null?void 0:V.kind)==="static_artifact"&&k.startsWith(Z.preview.url)})??null,[k,f]),C=h.useMemo(()=>!f.active||!w?uo:{kind:"variant",sessionId:f.sessionId,variantId:w.workItemId},[w,f]),E=h.useRef(null);h.useEffect(()=>{var K,W;if(!w||((K=w.preview)==null?void 0:K.kind)!=="static_artifact"||((W=w.refinement)==null?void 0:W.status)!=="succeeded")return;const Z=`${w.workItemId}:${w.refinement.workItemId}`;if(E.current===Z)return;E.current=Z;const V=w.preview.url.includes("?")?"&":"?",U=`${w.preview.url}${V}refinement=${encodeURIComponent(w.refinement.workItemId)}`;k!==U&&(u(U),a(G=>G+1))},[k,w,a,u,f]);const A=k!==null||b&&!m,{isUpstreamReady:R,iframeRemountKey:P,initialProbeComplete:I}=Dxe(t,{rerunProbeImmediatelyOnVersion:o,skip:A}),T=!!k||R,L=`${P}:${o}`,M=r?`/try/${encodeURIComponent(r)}`:"",D=t==="static"?`${M}/static/`:`${M}/`,O=p==="embedded"&&typeof window<"u"?`${window.location.protocol}//localhost:${window.location.port}`:"",F=k??(i||!T?"about:blank":`${O}${D}`);return y.jsxs("div",{className:"relative h-full w-full",children:[!T&&I?y.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",children:y.jsx("div",{role:"alert","aria-live":"polite",className:"flex max-w-sm flex-col items-center gap-5 text-center",children:b?y.jsxs(y.Fragment,{children:[y.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Directions will appear here"}),y.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"Select one from the panel to preview it."})]}):y.jsxs(y.Fragment,{children:[y.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Preview isn't connected"}),y.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"The connection between Rivet and your project is offline. Try restarting Rivet, then click reload below."}),y.jsx("button",{onClick:()=>window.location.reload(),className:"rounded-md bg-primary px-10 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover",children:"Reload"})]})})}):null,y.jsx(kB,{target:C,src:F,framework:t,mode:e?"view":s,isUpstreamReady:T,remountKey:L})]})},Mk=({message:e,isLoading:t=!0})=>y.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[t?y.jsx(dl,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,y.jsx("span",{className:"whitespace-pre-wrap font-sans",children:e})]});function PR({side:e,sessionId:t,variantId:n,url:r,label:i,isFallback:s=!1}){var b;const o=Ge(of),a=Ee(yo),l=Ee(Fs),u=h.useCallback(()=>{if(s){o(null);return}o(x=>{if(!x)return null;const k={...x};return delete k[e],k.left||k.right?k:null})},[o,e,s]),f=h.useMemo(()=>({kind:"variant",sessionId:t,variantId:n}),[t,n]),p=h.useMemo(()=>!l.active||l.sessionId!==t?null:l.variants.find(x=>x.workItemId===n)??null,[t,n,l]),m=h.useMemo(()=>{var k,w;if(((k=p==null?void 0:p.preview)==null?void 0:k.kind)!=="static_artifact"||((w=p.refinement)==null?void 0:w.status)!=="succeeded")return r;const x=p.preview.url.includes("?")?"&":"?";return`${p.preview.url}${x}refinement=${encodeURIComponent(p.refinement.workItemId)}`},[p,r]),g=((b=p==null?void 0:p.refinement)==null?void 0:b.status)==="succeeded"?`${n}:${p.refinement.workItemId}`:n;return y.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":n,children:[y.jsxs("div",{className:"variant-split-secondary-toolbar",children:[y.jsx("span",{className:"variant-split-secondary-label",title:i,children:i}),y.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:u,"aria-label":"Exit split view",children:y.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:y.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),y.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:y.jsx(kB,{target:f,src:m,framework:"static",mode:a,isUpstreamReady:!0,remountKey:g})})]})}const IR=220,H6e=64;function B6e(){const e=Ee(_p),t=Ee(V3),n=h.useRef(null);return h.useEffect(()=>{if(!e||!t||!n.current)return;const r=t.x-IR/2,i=t.y-22;n.current.style.transform=`translate3d(${r}px, ${i}px, 0)`},[e,t]),e?y.jsx("div",{ref:n,"aria-hidden":"true",className:"variant-drag-ghost",style:{width:IR,height:H6e},children:y.jsx("div",{className:"variant-drag-ghost-row",children:y.jsx("div",{className:"variant-drag-ghost-title",children:e.label})})}):null}function z6e(){const e=Ee(_p),t=Ee(V3),n=Ge(_p),r=Ge(of),i=h.useRef(null),[s,o]=h.useState(null),[a,l]=h.useState("hidden");h.useEffect(()=>{if(!e){l("hidden"),o(null);return}const p=requestAnimationFrame(()=>l("visible"));return()=>cancelAnimationFrame(p)},[e]);const u=h.useCallback((p,m)=>{const g=i.current;if(!g)return null;const b=g.getBoundingClientRect();return p<b.left||p>b.right||m<b.top||m>b.bottom?null:p<(b.left+b.right)/2?"left":"right"},[]);if(h.useEffect(()=>{if(!e||!t)return;const p=u(t.x,t.y);o(m=>m===p?m:p)},[e,t,u]),h.useEffect(()=>{if(!e)return;const p=m=>{const g=u(m.clientX,m.clientY);if(g&&e.url){const b={sessionId:e.sessionId,variantId:e.variantId,label:e.label,url:e.url};r(x=>({...x??{},[g]:b})),l("exiting"),window.setTimeout(()=>n(null),220)}else l("exiting"),window.setTimeout(()=>n(null),220)};return window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),()=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p)}},[e,u,n,r]),!e)return null;const f=["variant-drop-zones",a==="visible"&&"is-visible",a==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return y.jsxs("div",{ref:i,className:f,"aria-hidden":"true",children:[y.jsx(RR,{side:"left",hovered:s==="left",canDrop:!!e.url,label:e.label}),y.jsx(RR,{side:"right",hovered:s==="right",canDrop:!!e.url,label:e.label})]})}function RR({side:e,hovered:t,canDrop:n,label:r}){return y.jsxs("div",{className:["variant-drop-zone",`is-${e}`,t&&"is-hover",!n&&"is-disabled"].filter(Boolean).join(" "),children:[y.jsxs("div",{className:"variant-drop-zone-inner",children:[y.jsx("div",{className:`variant-drop-zone-icon is-${e}`}),y.jsx("div",{className:"variant-drop-zone-caption",children:n?`Add ${e} split`:"Split unavailable for this direction"})]}),y.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:y.jsx("div",{className:"variant-drop-zone-preview-label",children:r})}),y.jsx("div",{className:"variant-drop-zone-border"})]})}const CB=(e,t,n)=>{var s,o;if(!e.active||e.sessionId!==t)return null;const r=e.variants.find(a=>a.workItemId===n);if(((s=r==null?void 0:r.preview)==null?void 0:s.kind)!=="static_artifact")return null;if(((o=r.refinement)==null?void 0:o.status)!=="succeeded")return r.preview.url;const i=r.preview.url.includes("?")?"&":"?";return`${r.preview.url}${i}refinement=${encodeURIComponent(r.refinement.workItemId)}`},MR=(e,t)=>{if(!e)return;const n=CB(t,e.sessionId,e.variantId);return!n||n===e.url?e:{...e,url:n}},U6e=({isLoading:e=!1,isInteractionDisabled:t=!1,activeDemoSessionId:n=null,holdHostedTryoutPreviewNavigation:r=!1})=>{const{config:i,fetchConfig:s,isLoading:o,error:a}=Sxe();return h.useEffect(()=>{s().catch(l=>{St==null||St.capture("preview_config_load_failed",{message:l instanceof Error?l.message:"unknown_error"})})},[s]),o?r?y.jsx("div",{className:"flex h-full min-h-0 w-full flex-1 bg-main","aria-busy":"true"}):y.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:y.jsx(Mk,{message:"Loading..."})})}):a||!i?y.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:y.jsxs("div",{className:"max-w-md rounded-lg border border-divider bg-main-light p-4 text-center shadow-lg",children:[y.jsx("p",{className:"text-sm font-medium text-content",children:"We couldn't load your app preview."}),y.jsx("p",{className:"mt-2 text-sm text-content-subtle",children:a||"Missing preview configuration from the server."}),y.jsx("p",{className:"mt-2 text-sm text-content-subtle",children:"If this keeps happening, restart your Rivet session and try again."}),y.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{St==null||St.capture("preview_config_retry_clicked"),s().catch(l=>{St==null||St.capture("preview_config_load_failed",{message:l instanceof Error?l.message:"unknown_error"})})},children:"Retry preview"})]})}):y.jsx(Z6e,{isLoading:e,isInteractionDisabled:t,framework:i.framework,userPort:i.userPort,activeDemoSessionId:n,holdHostedTryoutPreviewNavigation:r})};function Z6e(e){const t=Ee(of),n=Ee(_p),r=Ee(yo),i=Ge(j3),s=Ee(Fs),o=Ee(I1),a=t==null?void 0:t.left,l=t==null?void 0:t.right,u=h.useMemo(()=>{var I,T;if(!s.active||s.projectContext.kind!=="fresh"||!(!!a!=!!l))return;const w=(I=a??l)==null?void 0:I.variantId,C=s.variants.filter(L=>{var M;return L.status==="succeeded"&&((M=L.preview)==null?void 0:M.kind)==="static_artifact"&&L.workItemId!==w}),E=o==null?void 0:o.replace(/[?&]refinement=[^&]*$/,""),R=C.find(L=>{var M;return((M=L.preview)==null?void 0:M.kind)==="static_artifact"&&L.preview.url===E})??C[0];if(((T=R==null?void 0:R.preview)==null?void 0:T.kind)!=="static_artifact")return;const P=CB(s,s.sessionId,R.workItemId);if(P)return{sessionId:s.sessionId,variantId:R.workItemId,label:R.label,url:P}},[s,a,l,o]),f=MR(a,s)??(l?u:void 0),p=MR(l,s)??(a?u:void 0),m=!a&&!!f,g=!l&&!!p,b=!!(f||p),x=y.jsx(V6e,{isInteractionDisabled:e.isInteractionDisabled,framework:e.framework,userPort:e.userPort,activeDemoSessionId:e.activeDemoSessionId,holdPreviewNavigation:e.holdHostedTryoutPreviewNavigation});return y.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${n?"is-dragging":""} ${b?"is-split":""}`,children:[e.isInteractionDisabled?null:y.jsx(Pxe,{mode:r,onModeChange:i,isLoading:e.isLoading}),y.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[f&&y.jsx(PR,{side:"left",sessionId:f.sessionId,variantId:f.variantId,url:f.url,label:f.label,isFallback:m},`left-${f.sessionId}:${f.variantId}:${f.url}`),!(f&&p)&&y.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",children:x}),p&&y.jsx(PR,{side:"right",sessionId:p.sessionId,variantId:p.variantId,url:p.url,label:p.label,isFallback:g},`right-${p.sessionId}:${p.variantId}:${p.url}`)]}),y.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),y.jsx(z6e,{}),y.jsx(B6e,{})]})}const W6e=Vt("SupportTicketModal"),$R=5e3,mw="feedback",G6e=e=>{var r;if(!e)return null;const t=(r=e.formErrors)==null?void 0:r[0];if(t)return t;const n=e.fieldErrors??{};for(const i of Object.values(n)){const s=i==null?void 0:i[0];if(s)return s}return null},q6e=async e=>{let t;try{t=await e.json()}catch{t=void 0}if(e.status===400){if(typeof(t==null?void 0:t.details)=="string"&&t.details.trim())return t.details;if(typeof(t==null?void 0:t.details)=="object"&&t.details!==null){const n=G6e(t.details);if(n)return n}return"Please check your feedback and try again."}return e.status>=500?typeof(t==null?void 0:t.details)=="string"&&t.details.trim()?t.details:"Could not send feedback right now. Please try again later.":typeof(t==null?void 0:t.error)=="string"&&t.error.trim()?t.error:`HTTP ${e.status}`},K6e=({isOpen:e,onClose:t,contactEmail:n})=>{const r=xi(),[i,s]=h.useState(""),[o,a]=h.useState(!1),l=h.useCallback(()=>{s("")},[]),u=h.useCallback(()=>{o||(l(),t())},[o,t,l]),f=h.useCallback(async()=>{const b=i.trim();if(!(!b||o)){a(!0);try{const x=typeof(r==null?void 0:r.get_session_id)=="function"?r.get_session_id():void 0,k=typeof(r==null?void 0:r.get_distinct_id)=="function"?r.get_distinct_id():void 0,w=n==null?void 0:n.trim(),C=await fetch("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:mw,message:b,contactEmail:w||void 0,metadata:{posthogSessionId:x??void 0,posthogDistinctId:k??void 0,appVersion:"0.10.2",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!C.ok){const E=await q6e(C);throw new Error(E)}r==null||r.capture("support_ticket_submitted",{ticket_type:mw,has_posthog_session_id:!!x}),Nt.success("Feedback sent",{description:"Thanks for sharing this."}),l(),t()}catch(x){const k=x instanceof Error?x.message:"Failed to send message";r==null||r.capture("support_ticket_submit_failed",{ticket_type:mw,error:k}),W6e.error("Failed to submit support ticket:",k),Nt.error("Could not send feedback",{description:k})}finally{a(!1)}}},[n,o,i,t,r,l]),p=h.useCallback(b=>{b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),f())},[f]),m=$R-i.length,g=o||i.trim().length===0;return y.jsx(xy,{open:e,onOpenChange:b=>!b&&u(),children:y.jsxs(wy,{children:[y.jsx(_y,{className:"fixed inset-0 z-max bg-black/40"}),y.jsx(ky,{className:"fixed left-1/2 top-1/2 z-max w-[480px] -translate-x-1/2 -translate-y-1/2 rounded-lg border border-divider bg-main p-6 shadow-xl outline-none",children:y.jsxs("div",{className:"flex flex-col gap-4",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx(Op,{className:"text-lg font-semibold text-content",children:"Send feedback"}),y.jsx(Ck,{asChild:!0,children:y.jsx("button",{className:"rounded p-1 text-content-subtle transition-colors hover:text-content",disabled:o,children:y.jsx(ua,{className:"h-4 w-4",weight:"bold"})})})]}),y.jsx("p",{className:"text-sm text-content-subtle",children:"Tell us what happened or what we can improve."}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{htmlFor:"support-ticket-message",className:"text-xs font-medium text-content-muted",children:"Your feedback"}),y.jsx("textarea",{id:"support-ticket-message",value:i,onChange:b=>s(b.target.value),onKeyDown:p,maxLength:$R,rows:7,disabled:o,placeholder:"What happened?",className:"w-full resize-none rounded-md border border-divider bg-main-input px-3 py-2 text-sm text-content outline-none placeholder:text-content-subtle disabled:opacity-50"}),y.jsxs("div",{className:"flex justify-between text-xs text-content-subtle",children:[y.jsx("span",{children:"Context details are included automatically."}),y.jsx("span",{children:m})]})]}),y.jsx("button",{onClick:f,disabled:g,className:"flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-xs text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:o?y.jsxs(y.Fragment,{children:[y.jsx(dl,{className:"h-4 w-4 animate-spin",weight:"bold"}),y.jsx("span",{children:"Sending..."})]}):y.jsx("span",{children:"Send feedback"})})]})})]})})},EB="data:image/svg+xml,%3csvg%20width='94'%20height='24'%20viewBox='0%200%2094%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M-0.000156164%2023.832V7.704H5.11184L6.47984%208.424C7.58384%207.704%209.04784%207.344%2010.8718%207.344C12.0718%207.344%2013.1278%207.476%2014.0398%207.74C14.9518%207.98%2015.6838%208.244%2016.2358%208.532C16.8118%208.82%2017.1718%209.024%2017.3158%209.144L15.5158%2013.824C15.2758%2013.656%2014.8198%2013.428%2014.1478%2013.14C13.4998%2012.852%2012.7318%2012.588%2011.8438%2012.348C10.9558%2012.084%2010.0198%2011.952%209.03584%2011.952H8.63984C7.96784%2011.952%207.45184%2012.072%207.09184%2012.312C6.73184%2012.528%206.55184%2013.02%206.55184%2013.788V23.832H-0.000156164ZM23.464%206.156C21.04%206.156%2019.828%205.124%2019.828%203.06C19.828%201.908%2020.128%201.116%2020.728%200.684C21.352%200.227999%2022.264%20-1.43051e-06%2023.464%20-1.43051e-06C24.736%20-1.43051e-06%2025.66%200.227999%2026.236%200.684C26.836%201.116%2027.136%201.908%2027.136%203.06C27.136%205.124%2025.912%206.156%2023.464%206.156ZM20.152%2023.832V7.704H26.704V23.832H20.152ZM37.4767%2023.832L29.6647%207.704H36.9007L40.3207%2016.524L41.2567%2019.116H41.6167L42.5527%2016.524L46.0087%207.704H53.1727L52.5967%209.9L45.4327%2023.832H37.4767ZM61.1953%2023.832C59.6113%2023.832%2058.3873%2023.604%2057.5233%2023.148C56.6833%2022.692%2056.1073%2022.068%2055.7953%2021.276C55.4833%2020.46%2055.3273%2019.524%2055.3273%2018.468V13.032C55.3273%2012.072%2055.4833%2011.196%2055.7953%2010.404C56.1313%209.588%2056.7193%208.94%2057.5593%208.46C58.3993%207.956%2059.6113%207.704%2061.1953%207.704H68.6473C70.5193%207.704%2071.9473%207.932%2072.9313%208.388C73.9393%208.82%2074.6233%209.444%2074.9833%2010.26C75.3673%2011.052%2075.5593%2011.976%2075.5593%2013.032V17.64H69.2593C67.0993%2017.64%2065.4553%2017.592%2064.3273%2017.496C63.2233%2017.4%2062.4433%2017.34%2061.9873%2017.316V17.856C61.9633%2018.816%2062.5393%2019.296%2063.7153%2019.296H64.8313C66.7513%2019.296%2068.5273%2019.26%2070.1593%2019.188C71.7913%2019.092%2073.0033%2019.008%2073.7953%2018.936L75.9553%2022.356C75.9553%2022.596%2075.7513%2022.824%2075.3433%2023.04C74.9353%2023.256%2074.2153%2023.448%2073.1833%2023.616C72.1753%2023.76%2070.7353%2023.832%2068.8633%2023.832H61.1953ZM61.9873%2014.184H68.8993V13.68C68.8993%2013.2%2068.8513%2012.864%2068.7553%2012.672C68.6833%2012.48%2068.4313%2012.36%2067.9993%2012.312C67.5673%2012.264%2066.8353%2012.24%2065.8033%2012.24H63.7153C62.5633%2012.24%2061.9873%2012.72%2061.9873%2013.68V14.184ZM85.8224%2023.832C83.9984%2023.832%2082.7504%2023.448%2082.0784%2022.68C81.4064%2021.912%2081.0704%2020.76%2081.0704%2019.224V12.24H78.1184V7.704H79.6304C80.0384%207.704%2080.3624%207.632%2080.6024%207.488C80.8664%207.32%2081.0344%207.032%2081.1064%206.624L81.7904%202.772H87.6944V7.704H93.7064V12.24H87.6944V17.82C87.6944%2018.42%2087.8384%2018.816%2088.1264%2019.008C88.4144%2019.2%2088.8464%2019.296%2089.4224%2019.296H93.0224L93.7424%2023.472C93.2384%2023.544%2092.4704%2023.628%2091.4384%2023.724C90.4064%2023.796%2089.2784%2023.832%2088.0544%2023.832H85.8224Z'%20fill='%23FF3300'/%3e%3c/svg%3e",SB=({isSigningIn:e,onStartSignIn:t,errorMessage:n=null,isDesktopShell:r=!1,displayMode:i="full"})=>{const s=i==="modal";return y.jsxs("div",{className:s?"glass-panel relative w-full max-w-sm rounded-2xl border border-white/10 px-8 py-14 font-main text-white shadow-2xl":"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:[r&&!s?y.jsx("div",{className:"fixed left-0 right-0 top-0 z-10 h-8",style:{WebkitAppRegion:"drag"}}):null,y.jsxs("div",{className:"flex flex-col items-center gap-10",children:[y.jsx("img",{src:EB,alt:"Rivet",className:"h-8 w-auto object-contain"}),y.jsxs("div",{className:"text-center",children:[y.jsx("h1",{className:"mb-2 text-xl font-medium text-content",children:"Welcome to Rivet"}),y.jsx("p",{className:"text-sm text-content-muted",children:"Sign in to get started"})]}),y.jsx("button",{onClick:t,disabled:e,className:"glass-panel active-push flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium transition-all hover:bg-white/10 disabled:opacity-50",children:e?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"}),y.jsx("span",{children:"Signing in..."})]}):y.jsxs(y.Fragment,{children:[y.jsx("img",{src:"https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg",alt:"Google",className:"h-5 w-5 brightness-110"}),y.jsx("span",{children:"Sign in with Google"})]})}),n?y.jsx("p",{className:"text-center text-xs text-red-200",children:n}):null]})]})},Y6e=({message:e})=>y.jsx("div",{className:"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:y.jsxs("div",{className:"flex flex-col items-center gap-10",children:[y.jsx("img",{src:EB,alt:"Rivet",className:"h-8 w-auto object-contain"}),y.jsxs("div",{className:"glass-panel flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium",children:[y.jsx(dl,{className:"h-5 w-5 shrink-0 animate-spin text-primary",weight:"bold"}),y.jsx("span",{children:e})]})]})}),DR=Vt("useConfig"),X6e=()=>{var e;return typeof window>"u"?null:((e=window.__RIVET_BOOTSTRAP__)==null?void 0:e.queueAccessToken)??null},Q6e=()=>{var e;return typeof window>"u"?null:((e=window.__RIVET_BOOTSTRAP__)==null?void 0:e.agentApplyMode)??null},J6e=()=>{const e=Ee(vo),t=Ge(vo),n=Ge(Jp),r=Ge(B3),i=Ge($v),s=Ge(z3),o=Ge(kD),a=Ge(_D),l=Ge(yD),u=h.useCallback(b=>{o(b.agentModeAvailable),l({name:b.name??null,email:b.email??null}),t(b.featureFlags??vD),a(!0),b.isMCPSession&&n(!0),b.mcpEditor&&r(b.mcpEditor),i(b.agentApplyMode??Q6e()??null),s(b.queueAccessToken??X6e())},[i,o,t,a,n,r,s,l]),f=mZ({queryKey:["rivet-config"],queryFn:async()=>{const b=await fetch("/api/config");if(!b.ok)throw new Error(`Failed to fetch config: ${b.statusText}`);return await b.json()},staleTime:3e4}),{refetch:p}=f;h.useEffect(()=>{f.data&&(u(f.data),DR.info("Config loaded:",f.data))},[f.data,u]),h.useEffect(()=>{f.error&&(a(!0),DR.warn("Failed to load config:",f.error instanceof Error?f.error.message:"Failed to load config"))},[f.error,a]);const m=h.useCallback(async()=>{const b=await p();return b.data?b.data:(a(!0),null)},[p,a]);let g=null;return f.error instanceof Error?g=f.error.message:f.error&&(g="Failed to load config"),{config:f.data??null,featureFlags:e,loading:f.isPending,error:g,refetchConfig:m}};var Ay={};const e8e="https://rivet-proxy.onrender.com";var qR;const gw=(qR=Ay.RIVET_PROXY_URL)==null?void 0:qR.trim(),D8=gw&&gw.length>0?gw:e8e,t8e="https://rivet-core-production.up.railway.app";var KR;const vw=(KR=Ay.RIVET_GATEWAY_URL)==null?void 0:KR.trim();vw&&vw.length>0;const n8e="https://rivet-prototype-host.onrender.com";var YR;const yw=(YR=Ay.RIVET_PROTOTYPE_HOST_URL)==null?void 0:YR.trim();yw&&yw.length>0;const r8e="https://us.i.posthog.com";var XR;const bw=(XR=Ay.RIVET_POSTHOG_HOST)==null?void 0:XR.trim();bw&&bw.length>0;const Hu=Vt("useOAuthCallback"),i8e=()=>{const[e,t]=h.useState({isProcessing:!1,isComplete:!1,error:null});return h.useEffect(()=>{const n=new AbortController;let r=!1;return(async()=>{var a,l,u;const s=window.location.hash,o=window.location.search;if(!(!s||!s.includes("access_token"))&&!r){t({isProcessing:!0,isComplete:!1,error:null});try{Hu.info("Processing OAuth callback...");const f=new URLSearchParams(s.substring(1)),p=f.get("access_token"),m=f.get("refresh_token"),b=new URLSearchParams(o).get("session");if(!p)throw new Error("No access token found in URL");if(!b)throw new Error("No session ID found in URL");Hu.info(`Completing OAuth with session: ${b}`);const x=await fetch(`${D8}/api/auth/google/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:b,accessToken:p,refreshToken:m}),signal:n.signal}),k=await x.json();if(!x.ok||!k.success)throw new Error(k.error||k.message||"Failed to complete authentication");if(Hu.info("OAuth authentication completed successfully"),r)return;if((a=k.user)!=null&&a.id?(St.identify(k.user.id,{...k.user.email?{email:k.user.email}:{}}),k.user.email&&St.alias(k.user.email,k.user.id)):(l=k.user)!=null&&l.email&&St.identify(k.user.email,{email:k.user.email}),(u=k.user)!=null&&u.email&&p)try{const C=await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:k.user.email,token:p,refreshToken:m,userId:k.user.id}),signal:n.signal});C.ok||Hu.warn(`Local auth store returned ${C.status}`)}catch(C){if(r)return;Hu.warn("Failed to store auth locally:",C)}if(r)return;const w=window.location.pathname;window.history.replaceState({},document.title,w),t({isProcessing:!1,isComplete:!0,error:null})}catch(f){if(r)return;const p=f instanceof Error?f.message:"Unknown error occurred";Hu.warn("OAuth callback error:",f),t({isProcessing:!1,isComplete:!1,error:p})}}})(),()=>{r=!0,n.abort()}},[]),e},xw=Vt("useAgentVariantsSession"),s8e=()=>{const e=Ge(Fs),t=Ge($c),n=Ge(Qp),r=Ge(yo),i=Ge(H3),s=Ge(hte),o=da(),a=h.useRef(null);h.useEffect(()=>{const l=new EventSource("/api/variants/events");return l.onmessage=u=>{try{const f=JSON.parse(u.data),p=a.current;f.active?(i(!1),f.sessionId!==a.current&&(a.current=f.sessionId,t(!0),n(!0),r("view"))):(a.current!==null&&t(!1),a.current=null,i(!1)),e(f);const m=!f.active&&p!==null,g=f.active&&f.sessionId!==p;if(g&&fetch(`/api/variants/${f.sessionId}/preview-port`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({variantId:null})}).catch(b=>xw.warn("failed to reset preview-port on session switch",b)),m||g){const b=new Set;if(f.active)for(const k of f.variants)b.add(ra({kind:"variant",sessionId:f.sessionId,variantId:k.workItemId}));const x=o.get(of);for(const k of[x==null?void 0:x.left,x==null?void 0:x.right])k&&b.add(ra({kind:"variant",sessionId:k.sessionId,variantId:k.variantId}));s(b)}}catch(f){xw.warn("failed to parse SSE event payload",f)}},l.onerror=u=>{xw.warn("SSE error (auto-reconnects)",u),i(!1)},()=>{l.close()}},[e,t,n,r,i,s,o])},Bu=Vt("useTokenEditor"),o8e=()=>{const[e,t]=h.useState(null),[n,r]=h.useState(null),[i,s]=h.useState(new Map),[o,a]=h.useState(!0),[l,u]=h.useState(!1),[f,p]=h.useState(null),m=h.useCallback(async()=>{a(!0),p(null);try{const k=await fetch("/api/tokens");if(!k.ok)throw new Error(`Failed to fetch tokens: ${k.statusText}`);const w=await k.json();t(w.registry),r(w.framework),Bu.info(`Loaded ${w.framework} tokens`)}catch(k){const w=k instanceof Error?k.message:"Unknown error";p(w),Bu.warn("Failed to fetch tokens:",k)}finally{a(!1)}},[]);h.useEffect(()=>{m()},[m]);const g=h.useCallback((k,w,C,E)=>{const A=`${k}.${w}`;s(R=>{const P=new Map(R);return E===C?P.delete(A):P.set(A,{category:k,path:w,originalValue:C,newValue:E}),P})},[]),b=h.useCallback(async()=>{if(i.size===0)return!0;u(!0),p(null);const k=Array.from(i.values());let w=!0;for(const C of k)try{Bu.info(`Saving ${C.category}.${C.path} = "${C.newValue}"`);const A=await(await fetch("/api/tokens/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:C.category,path:C.path,value:C.newValue})})).json();if(!A.success)throw new Error(A.error||"Update failed");Bu.info(`Successfully saved ${C.category}.${C.path}`)}catch(E){const A=E instanceof Error?E.message:"Unknown error";p(`Failed to update ${C.category}.${C.path}: ${A}`),Bu.warn(`Failed to save ${C.category}.${C.path}:`,E),w=!1;break}return w&&(s(new Map),await m()),u(!1),w},[i,m]),x=h.useCallback(()=>{s(new Map),Bu.info("Reverted all pending changes")},[]);return{tokens:e,framework:n,pendingChanges:i,isLoading:o,isSaving:l,error:f,updateToken:g,saveChanges:b,revertChanges:x,refetch:m}};var ww="rovingFocusGroup.onEntryFocus",a8e={bubbles:!1,cancelable:!0},f0="RovingFocusGroup",[N8,AB,l8e]=ny(f0),[c8e,TB]=Os(f0,[l8e]),[u8e,d8e]=c8e(f0),PB=h.forwardRef((e,t)=>y.jsx(N8.Provider,{scope:e.__scopeRovingFocusGroup,children:y.jsx(N8.Slot,{scope:e.__scopeRovingFocusGroup,children:y.jsx(f8e,{...e,ref:t})})}));PB.displayName=f0;var f8e=h.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:f=!1,...p}=e,m=h.useRef(null),g=an(t,m),b=l0(s),[x,k]=Ls({prop:o,defaultProp:a??null,onChange:l,caller:f0}),[w,C]=h.useState(!1),E=ml(u),A=AB(n),R=h.useRef(!1),[P,I]=h.useState(0);return h.useEffect(()=>{const T=m.current;if(T)return T.addEventListener(ww,E),()=>T.removeEventListener(ww,E)},[E]),y.jsx(u8e,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:x,onItemFocus:h.useCallback(T=>k(T),[k]),onItemShiftTab:h.useCallback(()=>C(!0),[]),onFocusableItemAdd:h.useCallback(()=>I(T=>T+1),[]),onFocusableItemRemove:h.useCallback(()=>I(T=>T-1),[]),children:y.jsx(Mt.div,{tabIndex:w||P===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:bt(e.onMouseDown,()=>{R.current=!0}),onFocus:bt(e.onFocus,T=>{const L=!R.current;if(T.target===T.currentTarget&&L&&!w){const M=new CustomEvent(ww,a8e);if(T.currentTarget.dispatchEvent(M),!M.defaultPrevented){const D=A().filter(U=>U.focusable),O=D.find(U=>U.active),F=D.find(U=>U.id===x),V=[O,F,...D].filter(Boolean).map(U=>U.ref.current);MB(V,f)}}R.current=!1}),onBlur:bt(e.onBlur,()=>C(!1))})})}),IB="RovingFocusGroupItem",RB=h.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...a}=e,l=is(),u=s||l,f=d8e(IB,n),p=f.currentTabStopId===u,m=AB(n),{onFocusableItemAdd:g,onFocusableItemRemove:b,currentTabStopId:x}=f;return h.useEffect(()=>{if(r)return g(),()=>b()},[r,g,b]),y.jsx(N8.ItemSlot,{scope:n,id:u,focusable:r,active:i,children:y.jsx(Mt.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...a,ref:t,onMouseDown:bt(e.onMouseDown,k=>{r?f.onItemFocus(u):k.preventDefault()}),onFocus:bt(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:bt(e.onKeyDown,k=>{if(k.key==="Tab"&&k.shiftKey){f.onItemShiftTab();return}if(k.target!==k.currentTarget)return;const w=m8e(k,f.orientation,f.dir);if(w!==void 0){if(k.metaKey||k.ctrlKey||k.altKey||k.shiftKey)return;k.preventDefault();let E=m().filter(A=>A.focusable).map(A=>A.ref.current);if(w==="last")E.reverse();else if(w==="prev"||w==="next"){w==="prev"&&E.reverse();const A=E.indexOf(k.currentTarget);E=f.loop?g8e(E,A+1):E.slice(A+1)}setTimeout(()=>MB(E))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:x!=null}):o})})});RB.displayName=IB;var h8e={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function p8e(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function m8e(e,t,n){const r=p8e(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return h8e[r]}function MB(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function g8e(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var v8e=PB,y8e=RB,Ty="Tabs",[b8e]=Os(Ty,[TB]),$B=TB(),[x8e,$k]=b8e(Ty),DB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:s,orientation:o="horizontal",dir:a,activationMode:l="automatic",...u}=e,f=l0(a),[p,m]=Ls({prop:r,onChange:i,defaultProp:s??"",caller:Ty});return y.jsx(x8e,{scope:n,baseId:is(),value:p,onValueChange:m,orientation:o,dir:f,activationMode:l,children:y.jsx(Mt.div,{dir:f,"data-orientation":o,...u,ref:t})})});DB.displayName=Ty;var NB="TabsList",LB=h.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,s=$k(NB,n),o=$B(n);return y.jsx(v8e,{asChild:!0,...o,orientation:s.orientation,dir:s.dir,loop:r,children:y.jsx(Mt.div,{role:"tablist","aria-orientation":s.orientation,...i,ref:t})})});LB.displayName=NB;var jB="TabsTrigger",FB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...s}=e,o=$k(jB,n),a=$B(n),l=HB(o.baseId,r),u=BB(o.baseId,r),f=r===o.value;return y.jsx(y8e,{asChild:!0,...a,focusable:!i,active:f,children:y.jsx(Mt.button,{type:"button",role:"tab","aria-selected":f,"aria-controls":u,"data-state":f?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...s,ref:t,onMouseDown:bt(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?o.onValueChange(r):p.preventDefault()}),onKeyDown:bt(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&o.onValueChange(r)}),onFocus:bt(e.onFocus,()=>{const p=o.activationMode!=="manual";!f&&!i&&p&&o.onValueChange(r)})})})});FB.displayName=jB;var OB="TabsContent",VB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:s,...o}=e,a=$k(OB,n),l=HB(a.baseId,r),u=BB(a.baseId,r),f=r===a.value,p=h.useRef(f);return h.useEffect(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),y.jsx(wo,{present:i||f,children:({present:m})=>y.jsx(Mt.div,{"data-state":f?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:u,tabIndex:0,...o,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&s})})});VB.displayName=OB;function HB(e,t){return`${e}-trigger-${t}`}function BB(e,t){return`${e}-content-${t}`}var w8e=DB,_8e=LB,k8e=FB,C8e=VB;const E8e=({tokens:e,pendingChanges:t,category:n,onUpdateToken:r,highlightToken:i})=>{const[s,o]=h.useState(null),[a,l]=h.useState(""),u=h.useRef(null);if(h.useEffect(()=>{i&&u.current&&setTimeout(()=>{var x;(x=u.current)==null||x.scrollIntoView({behavior:"smooth",block:"center"})},100)},[i]),!e||Object.keys(e).length===0)return y.jsx("div",{className:"flex items-center justify-center py-12 text-sm text-gray-500",children:"No tokens defined for this category"});const f=(x,k)=>{const w=`${n}.${x}`,C=t.get(w);return C?C.newValue:k},p=x=>{if(x.includes("var(")||x.includes("--"))return{textClass:"text-white",mutedClass:"text-white/70"};let k=0,w=0,C=0,E=!1;if(x.startsWith("#")){const I=x.slice(1);I.length===3?(k=parseInt(I[0]+I[0],16),w=parseInt(I[1]+I[1],16),C=parseInt(I[2]+I[2],16),E=!0):I.length>=6&&(k=parseInt(I.slice(0,2),16),w=parseInt(I.slice(2,4),16),C=parseInt(I.slice(4,6),16),E=!0)}const A=x.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(A&&(k=parseInt(A[1],10),w=parseInt(A[2],10),C=parseInt(A[3],10),E=!0),!E){const I=x.match(/rgba?\(\s*(\d+)\s+(\d+)\s+(\d+)/);I&&(k=parseInt(I[1],10),w=parseInt(I[2],10),C=parseInt(I[3],10),E=!0)}if(!E){const I=x.match(/hsla?\(\s*(\d+)\s*,\s*(\d+)%?\s*,\s*(\d+)%?/);if(I){const T=xT(parseInt(I[1],10),parseInt(I[2],10),parseInt(I[3],10));k=T.r,w=T.g,C=T.b,E=!0}}if(!E){const I=x.match(/hsla?\(\s*(\d+)\s+(\d+)%?\s+(\d+)%?/);if(I){const T=xT(parseInt(I[1],10),parseInt(I[2],10),parseInt(I[3],10));k=T.r,w=T.g,C=T.b,E=!0}}if(!E){const I=x.match(/oklch\(\s*([\d.]+)(%?)/);if(I){const T=parseFloat(I[1]),M=(I[2]==="%"?T/100:T)>.5;return{textClass:M?"text-gray-900":"text-white",mutedClass:M?"text-gray-600":"text-white/70"}}}if(!E)return{textClass:"text-white",mutedClass:"text-white/70"};const P=vie(k,w,C)>.5;return{textClass:P?"text-gray-900":"text-white",mutedClass:P?"text-gray-600":"text-white/70"}},m=(x,k,w,C)=>{const E=f(k,w),A=s===k,R=A&&a?a:E,P=k.replace(/\./g,"-"),I=i===P||i===x,T=R.includes("rgba")||R.startsWith("#")&&R.length===9||/oklch\(/.test(R)&&R.includes("/"),{textClass:L}=p(R),M=Z=>{l(Z)},D=Z=>{r(n,k,w,Z),o(null),l("")},O=Z=>{Z?(o(k),l(E)):(a&&a!==E&&r(n,k,w,a),o(null),l(""))},F=C?"h-44":"h-52";return y.jsxs(oa,{open:A,onOpenChange:O,children:[y.jsx(Tl,{asChild:!0,children:y.jsxs("div",{ref:I?u:null,className:`group relative flex ${F} cursor-pointer flex-col justify-between overflow-hidden rounded-lg border border-white/10 p-4 transition-all ${I?"animate-token-highlight":""}`,children:[y.jsxs("div",{className:"absolute inset-0",children:[T&&y.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`
|
|
611
|
+
`);R=T.pop()??"";for(const L of T){const M=$4e(L.trim());if(M!=null&&M.type){if(M.type==="variant_completed"){const D=M.variantIndex,O=M.diff;f+=1,r==null||r.capture("variant_code_gen_variant_ready",{variant_index:D,variant_count:u.length}),e(V=>{const U=V.get(s);if(!(U!=null&&U.styleVariants))return V;const K=new Map(V),W=[...U.styleVariants],G=D-1;return W[G]&&(W[G]={...W[G],codeStatus:"ready",codeDiff:O}),K.set(s,{...U,styleVariants:W}),K});const F=n.get(Mc),Z=n.get(ei);F===s&&!Z&&((g=n.get($r).get(s))==null?void 0:g.selectedVariantIndex)===D&&!((b=n.get($r).get(s))!=null&&b.finalizedVariant)&&(t({commentId:s,variantIndex:D,diff:O}),fetch("/api/design/apply-variant-diff",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({diff:O,reverse:!1})}).then(V=>{V.ok||t(null)}).catch(()=>{t(null)}))}else if(M.type==="variant_error"){const D=M.variantIndex,O=M.error;p+=1,r==null||r.capture("variant_code_gen_variant_failed",{variant_index:D,variant_count:u.length,error_message:O}),e(F=>{const Z=F.get(s);if(!(Z!=null&&Z.styleVariants))return F;const V=new Map(F),U=[...Z.styleVariants],K=D-1;return U[K]&&(U[K]={...U[K],codeStatus:"error",codeError:O}),V.set(s,{...Z,styleVariants:U}),V})}}}}r==null||r.capture("variant_code_gen_completed",{variant_count:u.length,success_count:f,error_count:p})}catch(x){const k=x instanceof DOMException&&x.name==="AbortError",w=x instanceof Error?x.message:"Direction code generation failed";r==null||r.capture("variant_code_gen_failed",{variant_count:u.length,reason:k?"aborted":"exception",error_message:w}),e(C=>{const E=C.get(s);if(!(E!=null&&E.styleVariants))return C;const A=new Map(C);return A.set(s,{...E,styleVariants:E.styleVariants.map(R=>({...R,codeStatus:void 0,codeDiff:void 0}))}),A})}finally{dse(s)}},[r,e,t,n])}};var un;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{const s={};for(const o of i)s[o]=o;return s},e.getValidEnumValues=i=>{const s=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),o={};for(const a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=i=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const o in i)Object.prototype.hasOwnProperty.call(i,o)&&s.push(o);return s},e.find=(i,s)=>{for(const o of i)if(s(o))return o},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(o=>typeof o=="string"?`'${o}'`:o).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(un||(un={}));var hR;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(hR||(hR={}));const ct=un.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Wa=e=>{switch(typeof e){case"undefined":return ct.undefined;case"string":return ct.string;case"number":return Number.isNaN(e)?ct.nan:ct.number;case"boolean":return ct.boolean;case"function":return ct.function;case"bigint":return ct.bigint;case"symbol":return ct.symbol;case"object":return Array.isArray(e)?ct.array:e===null?ct.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?ct.promise:typeof Map<"u"&&e instanceof Map?ct.map:typeof Set<"u"&&e instanceof Set?ct.set:typeof Date<"u"&&e instanceof Date?ct.date:ct.object;default:return ct.unknown}},Fe=un.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 ca 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(s){return s.message},r={_errors:[]},i=s=>{for(const o of s.issues)if(o.code==="invalid_union")o.unionErrors.map(i);else if(o.code==="invalid_return_type")i(o.returnTypeError);else if(o.code==="invalid_arguments")i(o.argumentsError);else if(o.path.length===0)r._errors.push(n(o));else{let a=r,l=0;for(;l<o.path.length;){const u=o.path[l];l===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(o))):a[u]=a[u]||{_errors:[]},a=a[u],l++}}};return i(this),r}static assert(t){if(!(t instanceof ca))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,un.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){const n={},r=[];for(const i of this.issues)if(i.path.length>0){const s=i.path[0];n[s]=n[s]||[],n[s].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}ca.create=e=>new ca(e);const S8=(e,t)=>{let n;switch(e.code){case Fe.invalid_type:e.received===ct.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case Fe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,un.jsonStringifyReplacer)}`;break;case Fe.unrecognized_keys:n=`Unrecognized key(s) in object: ${un.joinValues(e.keys,", ")}`;break;case Fe.invalid_union:n="Invalid input";break;case Fe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${un.joinValues(e.options)}`;break;case Fe.invalid_enum_value:n=`Invalid enum value. Expected ${un.joinValues(e.options)}, received '${e.received}'`;break;case Fe.invalid_arguments:n="Invalid function arguments";break;case Fe.invalid_return_type:n="Invalid function return type";break;case Fe.invalid_date:n="Invalid date";break;case Fe.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}"`:un.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case Fe.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 Fe.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 Fe.custom:n="Invalid input";break;case Fe.invalid_intersection_types:n="Intersection results could not be merged";break;case Fe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Fe.not_finite:n="Number must be finite";break;default:n=t.defaultError,un.assertNever(e)}return{message:n}};let D4e=S8;function N4e(){return D4e}const L4e=e=>{const{data:t,path:n,errorMaps:r,issueData:i}=e,s=[...n,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="";const l=r.filter(u=>!!u).slice().reverse();for(const u of l)a=u(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}};function Xe(e,t){const n=N4e(),r=L4e({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===S8?void 0:S8].filter(i=>!!i)});e.common.issues.push(r)}class Bi{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 i of n){if(i.status==="aborted")return Tt;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const i of n){const s=await i.key,o=await i.value;r.push({key:s,value:o})}return Bi.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const i of n){const{key:s,value:o}=i;if(s.status==="aborted"||o.status==="aborted")return Tt;s.status==="dirty"&&t.dirty(),o.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof o.value<"u"||i.alwaysSet)&&(r[s.value]=o.value)}return{status:t.value,value:r}}}const Tt=Object.freeze({status:"aborted"}),Hh=e=>({status:"dirty",value:e}),ls=e=>({status:"valid",value:e}),pR=e=>e.status==="aborted",mR=e=>e.status==="dirty",qd=e=>e.status==="valid",lv=e=>typeof Promise<"u"&&e instanceof Promise;var mt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(mt||(mt={}));class xl{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}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 gR=(e,t)=>{if(qd(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 ca(e.common.issues);return this._error=n,this._error}}};function Ut(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:i}=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:i}:{errorMap:(o,a)=>{const{message:l}=e;return o.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:i}}class ln{get description(){return this._def.description}_getType(t){return Wa(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Wa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Bi,ctx:{common:t.parent.common,data:t.data,parsedType:Wa(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(lv(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==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)},i=this._parseSync({data:t,path:r.path,parent:r});return gR(r,i)}"~validate"(t){var r,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)};if(!this["~standard"].async)try{const s=this._parseSync({data:t,path:[],parent:n});return qd(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(i=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(s=>qd(s)?{value:s.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==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Wa(t)},i=this._parse({data:t,path:r.path,parent:r}),s=await(lv(i)?i:Promise.resolve(i));return gR(r,s)}refine(t,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,s)=>{const o=t(i),a=()=>s.addIssue({code:Fe.custom,...r(i)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Uc({schema:this,typeName:Rt.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 ea.create(this,this._def)}nullable(){return Zc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return po.create(this)}promise(){return hv.create(this,this._def)}or(t){return uv.create([this,t],this._def)}and(t){return dv.create(this,t,this._def)}transform(t){return new Uc({...Ut(this._def),schema:this,typeName:Rt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new pv({...Ut(this._def),innerType:this,defaultValue:n,typeName:Rt.ZodDefault})}brand(){return new dB({typeName:Rt.ZodBranded,type:this,...Ut(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new mv({...Ut(this._def),innerType:this,catchValue:n,typeName:Rt.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Rk.create(this,t)}readonly(){return gv.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const j4e=/^c[^\s-]{8,}$/i,F4e=/^[0-9a-z]+$/,O4e=/^[0-9A-HJKMNP-TV-Z]{26}$/i,V4e=/^[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,H4e=/^[a-z0-9_-]{21}$/i,B4e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,z4e=/^[-+]?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)?)??$/,U4e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Z4e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pw;const W4e=/^(?:(?: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])$/,G4e=/^(?:(?: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])$/,q4e=/^(([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]))$/,K4e=/^(([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])$/,Y4e=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,X4e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lB="((\\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])))",Q4e=new RegExp(`^${lB}$`);function cB(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 J4e(e){return new RegExp(`^${cB(e)}$`)}function e6e(e){let t=`${lB}T${cB(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 t6e(e,t){return!!((t==="v4"||!t)&&W4e.test(e)||(t==="v6"||!t)&&q4e.test(e))}function n6e(e,t){if(!B4e.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,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function r6e(e,t){return!!((t==="v4"||!t)&&G4e.test(e)||(t==="v6"||!t)&&K4e.test(e))}class ol extends ln{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==ct.string){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.string,received:s.parsedType}),Tt}const r=new Bi;let i;for(const s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const o=t.data.length>s.value,a=t.data.length<s.value;(o||a)&&(i=this._getOrReturnCtx(t,i),o?Xe(i,{code:Fe.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Xe(i,{code:Fe.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")U4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"email",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")pw||(pw=new RegExp(Z4e,"u")),pw.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"emoji",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")V4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"uuid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")H4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"nanoid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")j4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cuid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")F4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cuid2",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")O4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"ulid",code:Fe.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Xe(i,{validation:"url",code:Fe.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"regex",code:Fe.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?e6e(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Q4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?J4e(s).test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?z4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"duration",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?t6e(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"ip",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?n6e(t.data,s.alg)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"jwt",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?r6e(t.data,s.version)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"cidr",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Y4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"base64",code:Fe.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?X4e.test(t.data)||(i=this._getOrReturnCtx(t,i),Xe(i,{validation:"base64url",code:Fe.invalid_string,message:s.message}),r.dirty()):un.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:Fe.invalid_string,...mt.errToObj(r)})}_addCheck(t){return new ol({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...mt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...mt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...mt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...mt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...mt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...mt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...mt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...mt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...mt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...mt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...mt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...mt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...mt.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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(t==null?void 0:t.offset)??!1,local:(t==null?void 0:t.local)??!1,...mt.errToObj(t==null?void 0: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==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,...mt.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...mt.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...mt.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...mt.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...mt.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...mt.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...mt.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...mt.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...mt.errToObj(n)})}nonempty(t){return this.min(1,mt.errToObj(t))}trim(){return new ol({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ol({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ol({...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}}ol.create=e=>new ol({checks:[],typeName:Rt.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Ut(e)});function i6e(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}class Kd extends ln{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)!==ct.number){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.number,received:s.parsedType}),Tt}let r;const i=new Bi;for(const s of this._def.checks)s.kind==="int"?un.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?i6e(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_finite,message:s.message}),i.dirty()):un.assertNever(s);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,mt.toString(n))}gt(t,n){return this.setLimit("min",t,!1,mt.toString(n))}lte(t,n){return this.setLimit("max",t,!0,mt.toString(n))}lt(t,n){return this.setLimit("max",t,!1,mt.toString(n))}setLimit(t,n,r,i){return new Kd({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:mt.toString(i)}]})}_addCheck(t){return new Kd({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:mt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:mt.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:mt.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:mt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:mt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:mt.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"&&un.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)}}Kd.create=e=>new Kd({checks:[],typeName:Rt.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Ut(e)});class Vp extends ln{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)!==ct.bigint)return this._getInvalidInput(t);let r;const i=new Bi;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Xe(r,{code:Fe.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):un.assertNever(s);return{status:i.value,value:t.data}}_getInvalidInput(t){const n=this._getOrReturnCtx(t);return Xe(n,{code:Fe.invalid_type,expected:ct.bigint,received:n.parsedType}),Tt}gte(t,n){return this.setLimit("min",t,!0,mt.toString(n))}gt(t,n){return this.setLimit("min",t,!1,mt.toString(n))}lte(t,n){return this.setLimit("max",t,!0,mt.toString(n))}lt(t,n){return this.setLimit("max",t,!1,mt.toString(n))}setLimit(t,n,r,i){return new Vp({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:mt.toString(i)}]})}_addCheck(t){return new Vp({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:mt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:mt.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:mt.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}}Vp.create=e=>new Vp({checks:[],typeName:Rt.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Ut(e)});class A8 extends ln{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==ct.boolean){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.boolean,received:r.parsedType}),Tt}return ls(t.data)}}A8.create=e=>new A8({typeName:Rt.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Ut(e)});class cv extends ln{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==ct.date){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_type,expected:ct.date,received:s.parsedType}),Tt}if(Number.isNaN(t.data.getTime())){const s=this._getOrReturnCtx(t);return Xe(s,{code:Fe.invalid_date}),Tt}const r=new Bi;let i;for(const s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(i=this._getOrReturnCtx(t,i),Xe(i,{code:Fe.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):un.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new cv({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:mt.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:mt.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}}cv.create=e=>new cv({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Rt.ZodDate,...Ut(e)});class vR extends ln{_parse(t){if(this._getType(t)!==ct.symbol){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.symbol,received:r.parsedType}),Tt}return ls(t.data)}}vR.create=e=>new vR({typeName:Rt.ZodSymbol,...Ut(e)});class T8 extends ln{_parse(t){if(this._getType(t)!==ct.undefined){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.undefined,received:r.parsedType}),Tt}return ls(t.data)}}T8.create=e=>new T8({typeName:Rt.ZodUndefined,...Ut(e)});class P8 extends ln{_parse(t){if(this._getType(t)!==ct.null){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.null,received:r.parsedType}),Tt}return ls(t.data)}}P8.create=e=>new P8({typeName:Rt.ZodNull,...Ut(e)});class yR extends ln{constructor(){super(...arguments),this._any=!0}_parse(t){return ls(t.data)}}yR.create=e=>new yR({typeName:Rt.ZodAny,...Ut(e)});class I8 extends ln{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ls(t.data)}}I8.create=e=>new I8({typeName:Rt.ZodUnknown,...Ut(e)});class wl extends ln{_parse(t){const n=this._getOrReturnCtx(t);return Xe(n,{code:Fe.invalid_type,expected:ct.never,received:n.parsedType}),Tt}}wl.create=e=>new wl({typeName:Rt.ZodNever,...Ut(e)});class bR extends ln{_parse(t){if(this._getType(t)!==ct.undefined){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.void,received:r.parsedType}),Tt}return ls(t.data)}}bR.create=e=>new bR({typeName:Rt.ZodVoid,...Ut(e)});class po extends ln{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==ct.array)return Xe(n,{code:Fe.invalid_type,expected:ct.array,received:n.parsedType}),Tt;if(i.exactLength!==null){const o=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(o||a)&&(Xe(n,{code:o?Fe.too_big:Fe.too_small,minimum:a?i.exactLength.value:void 0,maximum:o?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(Xe(n,{code:Fe.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(Xe(n,{code:Fe.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((o,a)=>i.type._parseAsync(new xl(n,o,n.path,a)))).then(o=>Bi.mergeArray(r,o));const s=[...n.data].map((o,a)=>i.type._parseSync(new xl(n,o,n.path,a)));return Bi.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new po({...this._def,minLength:{value:t,message:mt.toString(n)}})}max(t,n){return new po({...this._def,maxLength:{value:t,message:mt.toString(n)}})}length(t,n){return new po({...this._def,exactLength:{value:t,message:mt.toString(n)}})}nonempty(t){return this.min(1,t)}}po.create=(e,t)=>new po({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Rt.ZodArray,...Ut(t)});function qu(e){if(e instanceof or){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=ea.create(qu(r))}return new or({...e._def,shape:()=>t})}else return e instanceof po?new po({...e._def,type:qu(e.element)}):e instanceof ea?ea.create(qu(e.unwrap())):e instanceof Zc?Zc.create(qu(e.unwrap())):e instanceof Bc?Bc.create(e.items.map(t=>qu(t))):e}class or extends ln{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=un.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==ct.object){const u=this._getOrReturnCtx(t);return Xe(u,{code:Fe.invalid_type,expected:ct.object,received:u.parsedType}),Tt}const{status:r,ctx:i}=this._processInputParams(t),{shape:s,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof wl&&this._def.unknownKeys==="strip"))for(const u in i.data)o.includes(u)||a.push(u);const l=[];for(const u of o){const f=s[u],p=i.data[u];l.push({key:{status:"valid",value:u},value:f._parse(new xl(i,p,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof wl){const u=this._def.unknownKeys;if(u==="passthrough")for(const f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(u==="strict")a.length>0&&(Xe(i,{code:Fe.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const f of a){const p=i.data[f];l.push({key:{status:"valid",value:f},value:u._parse(new xl(i,p,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const u=[];for(const f of l){const p=await f.key,m=await f.value;u.push({key:p,value:m,alwaysSet:f.alwaysSet})}return u}).then(u=>Bi.mergeObjectSync(r,u)):Bi.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(t){return mt.errToObj,new or({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var s,o;const i=((o=(s=this._def).errorMap)==null?void 0:o.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:mt.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new or({...this._def,unknownKeys:"strip"})}passthrough(){return new or({...this._def,unknownKeys:"passthrough"})}extend(t){return new or({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new or({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Rt.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new or({...this._def,catchall:t})}pick(t){const n={};for(const r of un.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new or({...this._def,shape:()=>n})}omit(t){const n={};for(const r of un.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new or({...this._def,shape:()=>n})}deepPartial(){return qu(this)}partial(t){const n={};for(const r of un.objectKeys(this.shape)){const i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new or({...this._def,shape:()=>n})}required(t){const n={};for(const r of un.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof ea;)s=s._def.innerType;n[r]=s}return new or({...this._def,shape:()=>n})}keyof(){return uB(un.objectKeys(this.shape))}}or.create=(e,t)=>new or({shape:()=>e,unknownKeys:"strip",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});or.strictCreate=(e,t)=>new or({shape:()=>e,unknownKeys:"strict",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});or.lazycreate=(e,t)=>new or({shape:e,unknownKeys:"strip",catchall:wl.create(),typeName:Rt.ZodObject,...Ut(t)});class uv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function i(s){for(const a of s)if(a.result.status==="valid")return a.result;for(const a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;const o=s.map(a=>new ca(a.ctx.common.issues));return Xe(n,{code:Fe.invalid_union,unionErrors:o}),Tt}if(n.common.async)return Promise.all(r.map(async s=>{const o={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:o}),ctx:o}})).then(i);{let s;const o=[];for(const l of r){const u={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!s&&(s={result:f,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const a=o.map(l=>new ca(l));return Xe(n,{code:Fe.invalid_union,unionErrors:a}),Tt}}get options(){return this._def.options}}uv.create=(e,t)=>new uv({options:e,typeName:Rt.ZodUnion,...Ut(t)});const Ho=e=>e instanceof M8?Ho(e.schema):e instanceof Uc?Ho(e.innerType()):e instanceof fv?[e.value]:e instanceof zc?e.options:e instanceof $8?un.objectValues(e.enum):e instanceof pv?Ho(e._def.innerType):e instanceof T8?[void 0]:e instanceof P8?[null]:e instanceof ea?[void 0,...Ho(e.unwrap())]:e instanceof Zc?[null,...Ho(e.unwrap())]:e instanceof dB||e instanceof gv?Ho(e.unwrap()):e instanceof mv?Ho(e._def.innerType):[];class Ik extends ln{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ct.object)return Xe(n,{code:Fe.invalid_type,expected:ct.object,received:n.parsedType}),Tt;const r=this.discriminator,i=n.data[r],s=this.optionsMap.get(i);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(Xe(n,{code:Fe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Tt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const i=new Map;for(const s of n){const o=Ho(s.shape[t]);if(!o.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const a of o){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,s)}}return new Ik({typeName:Rt.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Ut(r)})}}function R8(e,t){const n=Wa(e),r=Wa(t);if(e===t)return{valid:!0,data:e};if(n===ct.object&&r===ct.object){const i=un.objectKeys(t),s=un.objectKeys(e).filter(a=>i.indexOf(a)!==-1),o={...e,...t};for(const a of s){const l=R8(e[a],t[a]);if(!l.valid)return{valid:!1};o[a]=l.data}return{valid:!0,data:o}}else if(n===ct.array&&r===ct.array){if(e.length!==t.length)return{valid:!1};const i=[];for(let s=0;s<e.length;s++){const o=e[s],a=t[s],l=R8(o,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===ct.date&&r===ct.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class dv extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=(s,o)=>{if(pR(s)||pR(o))return Tt;const a=R8(s.value,o.value);return a.valid?((mR(s)||mR(o))&&n.dirty(),{status:n.value,value:a.data}):(Xe(r,{code:Fe.invalid_intersection_types}),Tt)};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(([s,o])=>i(s,o)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}dv.create=(e,t,n)=>new dv({left:e,right:t,typeName:Rt.ZodIntersection,...Ut(n)});class Bc extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ct.array)return Xe(r,{code:Fe.invalid_type,expected:ct.array,received:r.parsedType}),Tt;if(r.data.length<this._def.items.length)return Xe(r,{code:Fe.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Tt;!this._def.rest&&r.data.length>this._def.items.length&&(Xe(r,{code:Fe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((o,a)=>{const l=this._def.items[a]||this._def.rest;return l?l._parse(new xl(r,o,r.path,a)):null}).filter(o=>!!o);return r.common.async?Promise.all(s).then(o=>Bi.mergeArray(n,o)):Bi.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new Bc({...this._def,rest:t})}}Bc.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Bc({items:e,typeName:Rt.ZodTuple,rest:null,...Ut(t)})};class xR extends ln{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!==ct.map)return Xe(r,{code:Fe.invalid_type,expected:ct.map,received:r.parsedType}),Tt;const i=this._def.keyType,s=this._def.valueType,o=[...r.data.entries()].map(([a,l],u)=>({key:i._parse(new xl(r,a,r.path,[u,"key"])),value:s._parse(new xl(r,l,r.path,[u,"value"]))}));if(r.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const l of o){const u=await l.key,f=await l.value;if(u.status==="aborted"||f.status==="aborted")return Tt;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}})}else{const a=new Map;for(const l of o){const u=l.key,f=l.value;if(u.status==="aborted"||f.status==="aborted")return Tt;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}}}}xR.create=(e,t,n)=>new xR({valueType:t,keyType:e,typeName:Rt.ZodMap,...Ut(n)});class Hp extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==ct.set)return Xe(r,{code:Fe.invalid_type,expected:ct.set,received:r.parsedType}),Tt;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(Xe(r,{code:Fe.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(Xe(r,{code:Fe.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const s=this._def.valueType;function o(l){const u=new Set;for(const f of l){if(f.status==="aborted")return Tt;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}const a=[...r.data.values()].map((l,u)=>s._parse(new xl(r,l,r.path,u)));return r.common.async?Promise.all(a).then(l=>o(l)):o(a)}min(t,n){return new Hp({...this._def,minSize:{value:t,message:mt.toString(n)}})}max(t,n){return new Hp({...this._def,maxSize:{value:t,message:mt.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}Hp.create=(e,t)=>new Hp({valueType:e,minSize:null,maxSize:null,typeName:Rt.ZodSet,...Ut(t)});class M8 extends ln{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})}}M8.create=(e,t)=>new M8({getter:e,typeName:Rt.ZodLazy,...Ut(t)});class fv extends ln{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Xe(n,{received:n.data,code:Fe.invalid_literal,expected:this._def.value}),Tt}return{status:"valid",value:t.data}}get value(){return this._def.value}}fv.create=(e,t)=>new fv({value:e,typeName:Rt.ZodLiteral,...Ut(t)});function uB(e,t){return new zc({values:e,typeName:Rt.ZodEnum,...Ut(t)})}class zc extends ln{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Xe(n,{expected:un.joinValues(r),received:n.parsedType,code:Fe.invalid_type}),Tt}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 Xe(n,{received:n.data,code:Fe.invalid_enum_value,options:r}),Tt}return ls(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 zc.create(t,{...this._def,...n})}exclude(t,n=this._def){return zc.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}}zc.create=uB;class $8 extends ln{_parse(t){const n=un.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==ct.string&&r.parsedType!==ct.number){const i=un.objectValues(n);return Xe(r,{expected:un.joinValues(i),received:r.parsedType,code:Fe.invalid_type}),Tt}if(this._cache||(this._cache=new Set(un.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const i=un.objectValues(n);return Xe(r,{received:r.data,code:Fe.invalid_enum_value,options:i}),Tt}return ls(t.data)}get enum(){return this._def.values}}$8.create=(e,t)=>new $8({values:e,typeName:Rt.ZodNativeEnum,...Ut(t)});class hv extends ln{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==ct.promise&&n.common.async===!1)return Xe(n,{code:Fe.invalid_type,expected:ct.promise,received:n.parsedType}),Tt;const r=n.parsedType===ct.promise?n.data:Promise.resolve(n.data);return ls(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}hv.create=(e,t)=>new hv({type:e,typeName:Rt.ZodPromise,...Ut(t)});class Uc extends ln{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Rt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,s={addIssue:o=>{Xe(r,o),o.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const o=i.transform(r.data,s);if(r.common.async)return Promise.resolve(o).then(async a=>{if(n.value==="aborted")return Tt;const l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?Tt:l.status==="dirty"||n.value==="dirty"?Hh(l.value):l});{if(n.value==="aborted")return Tt;const a=this._def.schema._parseSync({data:o,path:r.path,parent:r});return a.status==="aborted"?Tt:a.status==="dirty"||n.value==="dirty"?Hh(a.value):a}}if(i.type==="refinement"){const o=a=>{const l=i.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Tt:(a.status==="dirty"&&n.dirty(),o(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?Tt:(a.status==="dirty"&&n.dirty(),o(a.value).then(()=>({status:n.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!qd(o))return Tt;const a=i.transform(o.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>qd(o)?Promise.resolve(i.transform(o.value,s)).then(a=>({status:n.value,value:a})):Tt);un.assertNever(i)}}Uc.create=(e,t,n)=>new Uc({schema:e,typeName:Rt.ZodEffects,effect:t,...Ut(n)});Uc.createWithPreprocess=(e,t,n)=>new Uc({schema:t,effect:{type:"preprocess",transform:e},typeName:Rt.ZodEffects,...Ut(n)});class ea extends ln{_parse(t){return this._getType(t)===ct.undefined?ls(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ea.create=(e,t)=>new ea({innerType:e,typeName:Rt.ZodOptional,...Ut(t)});class Zc extends ln{_parse(t){return this._getType(t)===ct.null?ls(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Zc.create=(e,t)=>new Zc({innerType:e,typeName:Rt.ZodNullable,...Ut(t)});class pv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===ct.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}pv.create=(e,t)=>new pv({innerType:e,typeName:Rt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ut(t)});class mv extends ln{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return lv(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ca(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ca(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}mv.create=(e,t)=>new mv({innerType:e,typeName:Rt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ut(t)});class wR extends ln{_parse(t){if(this._getType(t)!==ct.nan){const r=this._getOrReturnCtx(t);return Xe(r,{code:Fe.invalid_type,expected:ct.nan,received:r.parsedType}),Tt}return{status:"valid",value:t.data}}}wR.create=e=>new wR({typeName:Rt.ZodNaN,...Ut(e)});class dB extends ln{_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 Rk extends ln{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Tt:s.status==="dirty"?(n.dirty(),Hh(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Tt:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new Rk({in:t,out:n,typeName:Rt.ZodPipeline})}}class gv extends ln{_parse(t){const n=this._def.innerType._parse(t),r=i=>(qd(i)&&(i.value=Object.freeze(i.value)),i);return lv(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}}gv.create=(e,t)=>new gv({innerType:e,typeName:Rt.ZodReadonly,...Ut(t)});var Rt;(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"})(Rt||(Rt={}));const Be=ol.create,mo=Kd.create,_l=A8.create,s6e=I8.create;wl.create;const Xn=po.create,kr=or.create;uv.create;const fB=Ik.create;dv.create;Bc.create;const vv=fv.create,ki=zc.create;hv.create;ea.create;Zc.create;var o6e={};const a6e=(o6e.LOG_LEVEL||"INFO").toUpperCase();pi.setLevel(pi.levels[a6e]||pi.levels.INFO);const hB=[/^10\./,/^127\./,/^192\.168\./,/^169\.254\./,/^172\.(1[6-9]|2\d|3[0-1])\./,/^0\./,/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./],l6e=[/^::1$/i,/^fe80:/i,/^f[cd][0-9a-f]{2}:/i],c6e=e=>{const t=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(e);if(!t)return!1;const n=t[1];return hB.some(r=>r.test(n))},u6e=[/^localhost$/i,/\.localhost$/i,/^localhost\./i,/\.local$/i,/\.internal$/i,/\.lan$/i,/\.intranet$/i],d6e=e=>{const t=e.trim();if(!t)return{ok:!1,reason:"URL is empty."};let n;try{n=new URL(t)}catch{return{ok:!1,reason:`URL is not valid: ${t}`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{ok:!1,reason:`Only HTTP and HTTPS inspiration links are supported (got '${n.protocol.replace(/:$/,"")}').`};const r=n.hostname.toLowerCase();return r?f6e(r)?{ok:!1,reason:`URL hostname '${r}' resolves to a local or private-network target.`}:(n.hash="",{ok:!0,url:n,normalized:n.toString()}):{ok:!1,reason:"URL is missing a hostname."}},f6e=e=>{const t=e.replace(/^\[|\]$/g,"");return!!(hB.some(n=>n.test(t))||l6e.some(n=>n.test(t))||c6e(t)||u6e.some(n=>n.test(t)))},h6e=kr({kind:vv("existing")}),pB=5e4,p6e=120,ta=2048,m6e=80,g6e=8e3,Ss=400,gi=24,v6e=16,y6e=ki(["design_source","interaction_reference","asset_source","content_reference","other"]),b6e=ki(["low","medium","high"]),x6e=kr({url:Be().min(1).max(ta).optional(),imageRef:Be().min(1).max(64).optional(),role:y6e,confidence:b6e,reason:Be().min(1).max(Ss)}).refine(e=>!!e.url!=!!e.imageRef,{message:"sourceIntent entry must specify exactly one of `url` or `imageRef`."}),mB=kr({sources:Xn(x6e).min(1).max(gi)}),gB=fB("kind",[kr({kind:vv("slug"),slug:Be().min(1).max(p6e)}),kr({kind:vv("markdown"),content:Be().min(1).max(pB),label:Be().min(1).max(60)})]),w6e=ki(["urlText","siteBrief","visualBrief","screenshotNotes","motionBrief"]),vB=kr({kind:w6e,label:Be().min(1).max(m6e),content:Be().min(1).max(g6e)}),_6e=ki(["primary","inspiration","competitor"]),k6e=kr({url:Be().min(1).max(ta),role:_6e,rationale:Be().min(1).max(Ss).optional()}),yB=kr({sourceFindings:Xn(Be().min(1).max(Ss)).min(1).max(gi),sectionInventory:Xn(Be().min(1).max(Ss)).min(1).max(gi),visualObservations:Xn(Be().min(1).max(Ss)).min(1).max(gi),sourceRoles:Xn(k6e).min(1).max(gi),qualityBar:Xn(Be().min(1).max(Ss)).min(1).max(gi),screenshotReferences:Xn(Be().min(1).max(Ss)).max(v6e).optional(),risks:Xn(Be().min(1).max(Ss)).max(gi).optional()}),bB=kr({sourceUrls:Xn(Be().min(1).max(ta)).max(gi).optional(),preserveBrand:_l().optional(),sourceArtifacts:Xn(vB).max(gi).optional(),artifact:yB.optional(),sourceIntent:mB.optional(),designDecision:ki(["let_rivet_choose","go_custom"]).optional()}),C6e=ki(["static_preview","vite_app"]),E6e=ki(["low","medium","high"]),S6e=kr({source:Be().min(1).max(ta),destination:Be().min(1).max(ta),referenceAs:Be().min(1).max(ta)}),xB=kr({mode:C6e,confidence:E6e,reason:Be().min(1).max(Ss),assetPlan:Xn(S6e).max(gi).optional(),runtimeRequirements:Xn(Be().min(1).max(Ss)).max(gi).optional(),userQuestion:Be().min(1).max(Ss).optional()}),A6e=kr({kind:vv("fresh"),workspacePath:Be().min(1),workspaceRoot:Be().min(1),framework:ki(["vite","next","astro","remix"]).optional(),assetSourceRoot:Be().min(1).max(ta).optional(),designContext:Xn(gB).optional(),sourceContext:bB.optional(),executionPlan:xB.optional()}),T6e=fB("kind",[h6e,A6e]),wB=kr({type:ki(["element","file","route"]),ref:Be().min(1)}),_B=kr({briefId:Be().min(1),label:Be().min(1).max(40).describe('≤ 4 words. Rendered as the variant card title in the UI. e.g. "Spring blur", "Linear sharp".'),body:Be().min(1).max(200).describe(`Exactly ONE sentence, ≤ 12 words. Single evocative descriptor of the variant's direction — what makes it distinct. Rendered as the card subtitle. e.g. "Apple-style spring physics with ambient blur and soft edges". No bullets, no lists, no line breaks.`),visualReferenceUrl:Be().url().refine(e=>d6e(e).ok,{message:"visualReferenceUrl must be an HTTP(S) URL that does not target local or private networks"}).optional().describe("Optional HTTP(S) inspiration URL. Subject to SSRF guard — must not resolve to local or private network targets.")}),Yd=2,Xd=8;Be().optional(),Be().optional(),Be().min(1),mo().int().min(Yd).max(Xd).optional(),wB.optional(),T6e.optional();Be().min(1),Be().min(1),mo().int().nonnegative(),Be().optional(),Xn(_B).min(1).max(8);const P6e=kr({url:Be().min(1).max(ta).optional(),imageRef:Be().min(1).max(64).optional(),label:Be().min(1).max(60),markdown:Be().min(1).max(pB)}).refine(e=>!!e.url!=!!e.imageRef,{message:"designContexts entry must specify exactly one of `url` or `imageRef`."});kr({sourceIntent:mB,sourceContext:yB,designContexts:Xn(P6e).max(gi).optional(),executionPlan:xB});Be().min(1),Be().min(1),mo().int().nonnegative(),Be().min(1);Be().min(1),Xn(Be().min(1)).min(1).max(8).optional(),_l().optional(),_l().optional(),Be().min(1).optional(),Xn(kr({briefId:Be().min(1),bodyOverride:Be().optional()})).min(1).max(8).optional();Be().min(1),Be().min(1),_l().optional(),_l().optional(),Be().min(1).optional();ki(["check","wait","request_work","refine_variant"]).optional();Be().min(1),Be().optional(),mo().int().min(1).max(8).optional(),Be().min(1).optional(),Be().min(1).optional();ki(["running","succeeded","failed","cancelled"]);Be().min(1),Be().min(1),Be().min(1),mo().int().nonnegative(),s6e().optional(),kr({code:Be(),message:Be()}).optional(),Be().optional(),mo().int().nonnegative().optional(),mo().int().nonnegative().optional(),Be().optional();Be().min(1),mo().int().min(Yd).max(Xd),Xn(Be().min(1).max(ta)).max(gi).optional(),_l().optional(),Xn(vB).max(gi).optional(),_l().optional(),Be().optional();Be().min(1),Be().optional();Be().min(1),Be().min(1),Be().optional();ki(["existing","zero_to_one"]).describe('"existing": vary an existing project at projectPath/cwd (spawns code_gen items). "zero_to_one": prompt-only fresh project; server derives destinationPath (spawns static_preview items).');const I6e=_B.omit({briefId:!0});Be().min(1),mo().int().min(Yd).max(Xd).optional(),wB.optional(),Xn(I6e).min(Yd).max(Xd).optional().describe("One brief per variant. `briefs.length` sets the variant count (3-5); do NOT also pass `count`. Each brief MUST describe a distinct direction — never copy the user prompt verbatim into a body."),ki(["vite"]).optional(),Be().optional(),Be().optional(),Xn(gB).optional(),bB.optional(),Be().optional();const R6e=ki(["completed","committed","rejected","cancelled"]);Be().optional(),mo().int().min(1).max(500).optional(),R6e.optional();Be().optional(),Be().min(1),Be().min(1),_l().optional();const _R=3,M6e=[/\bvariants?\s*[:=]\s*(\d+)(?!\.\d)\b/i,/\b(\d+)(?!\.\d)\s*variants?\b/i,/\bvariants?\s+(\d+)(?!\.\d)\b/i],$6e=e=>e<Yd?Yd:e>Xd?Xd:e,kR=e=>{if(!e)return _R;for(const t of M6e){const n=t.exec(e);if(!n)continue;const r=n[1];if(!/^\d+$/.test(r))continue;const i=Number.parseInt(r,10);if(!(!Number.isInteger(i)||i<=0))return $6e(i)}return _R},CR=8,ER=320,SR=8,AR=3,D6e=15e3,N6e=.65,L6e=({elementContext:e,target:t=uo,pin:n,dragBox:r,position:i,onClose:s,existingCommentId:o,isMCPSession:a=!1,onInputChange:l,shake:u})=>{var ce,ge;const f=xi(),p=gee(),[m,g]=zn($r),b=Ee(nf),k=Ee(vo).variants.isEnabled,w=Ge(Mc),C=Ge(yo),E=Ge(Qp),A=Ge($c),R=Ge(H3),P=da(),{generateVariantsForComment:I}=M4e(),{sendVariantRequestComment:T}=jD(),{startCodeGeneration:L}=aB(),D=Ee(Fs).active===!0,O=Ee(Iv),F=o?m.get(o):void 0,Z=(F==null?void 0:F.instruction)??"",[V,U]=h.useState(Z),[K,W]=h.useState((F==null?void 0:F.images)??[]),[G,j]=h.useState((F==null?void 0:F.references)??[]),[H,B]=h.useState(!1),N=h.useRef(null),q=h.useRef(null),X=h.useRef(null);h.useEffect(()=>{const le=setTimeout(()=>{const he=N.current;he&&(he.focus(),he.selectionStart=he.selectionEnd=he.value.length)},150);return()=>clearTimeout(le)},[]);const te=h.useCallback(()=>{X.current&&(clearTimeout(X.current),X.current=null)},[]);h.useEffect(()=>()=>{te()},[te]);const ie=h.useRef(u);h.useEffect(()=>{u!==ie.current&&p.start({x:[0,-5,5,-4,4,-2,2,0],y:[0,1.5,-1.5,1,-1,.5,-.5,0],transition:{duration:.45,ease:"easeInOut"}})},[u,p]);const Y=V.trim()!==Z.trim()&&V.trim()!==""||K.length!==(((ce=F==null?void 0:F.images)==null?void 0:ce.length)??0)||G.length!==(((ge=F==null?void 0:F.references)==null?void 0:ge.length)??0),J=o?Y:V.trim()!=="",ue=h.useCallback(le=>{j(le),l==null||l(V.trim()!==""||K.length>0||le.length>0)},[V,K.length,l]),be=h.useCallback(le=>{ue(G.filter(he=>!(he.sessionId===le.sessionId&&he.variantId===le.variantId)))},[G,ue]),Me=h.useCallback(le=>{s(le)},[s]),_e=h.useCallback(le=>{le.style.height="auto",le.style.height=`${le.scrollHeight}px`},[]),ke=h.useCallback(le=>{S_(le).then(he=>{W(Se=>[...Se,he])}).catch(()=>{console.warn("[CommentPopover] Failed to process image:",le.name)})},[]),$e=h.useCallback(le=>{W(he=>[...he,le]),l==null||l(!0)},[l]),{isDragOver:Qe,dropHandlers:He}=BL($e),ze=le=>{const he=le.target.files;if(!he)return;let Se=!1;for(const Ke of Array.from(he))Ke.type.startsWith("image/")&&(ke(Ke),Se=!0);q.current&&(q.current.value=""),Se&&(l==null||l(!0))},ye=le=>{var Se;const he=(Se=le.clipboardData)==null?void 0:Se.items;if(he){for(const Ke of Array.from(he))if(Ke.type.startsWith("image/")){le.preventDefault();const Je=Ke.getAsFile();Je&&(ke(Je),l==null||l(!0))}}},nt=le=>{const he=K.filter((Se,Ke)=>Ke!==le);W(he),l==null||l(V.trim()!==""||he.length>0)},$t=h.useCallback(async le=>{var vt,nn;const he=V.trim();if(!he)return;const Se=(le==null?void 0:le.forceGenerateVariants)===!0&&!a,Ke=Se?{styleVariants:void 0,selectedVariantIndex:void 0,finalizedVariant:void 0,variantGenerationStatus:"generating",variantGenerationError:void 0,requestedVariantCount:AR}:{};if(Se&&o){IT(o);const Ft=P.get(ei);Ft&&Ft.commentId===o&&(await rd(Ft.diff),P.set(ei,null));const Jt=(nn=(vt=m.get(o))==null?void 0:vt.finalizedVariant)==null?void 0:nn.codeDiff;Jt&&await rd(Jt)}let Je;if(o)Je=o,g(Ft=>{const Jt=Ft.get(o);if(!Jt)return Ft;const dn=new Map(Ft);return dn.set(o,{...Jt,instruction:he,images:K.length>0?K:void 0,references:G.length>0?G:void 0,variantRequest:void 0,...Ke}),dn}),f==null||f.capture("comment_edited",{instruction_length:he.length,image_count:K.length,reference_count:G.length,has_variants:Se});else{const Ft=crypto.randomUUID();Je=Ft;const Jt={id:Ft,target:t,elementContext:e,pin:n,dragBox:r,instruction:he,images:K.length>0?K:void 0,references:G.length>0?G:void 0,...Ke,status:"pending"};g(dn=>{const Ce=new Map(dn);return Ce.set(Ft,Jt),Ce}),f==null||f.capture("comment_added",{instruction_length:he.length,image_count:K.length,reference_count:G.length,has_variants:Se})}Me({preserveSelection:!0}),Se&&(w(Je),I({commentId:Je,instruction:he,elementContext:e,requestedVariantCount:AR,onVariantsReady:Ft=>void L(Ft)}))},[V,K,G,o,e,t,n,r,m,g,f,a,I,L,Me,w,P]),ve=h.useCallback(async()=>{const le=V.trim();if(!le)return;const he=kR(V),Se=o??crypto.randomUUID();if(o)g(Je=>{const vt=Je.get(o);if(!vt)return Je;const nn=new Map(Je);return nn.set(o,{...vt,instruction:le,images:void 0,references:G.length>0?G:void 0,variantRequest:{count:he}}),nn}),f==null||f.capture("comment_edited",{instruction_length:le.length,image_count:0,reference_count:G.length,has_variants:!1});else{const Je={id:Se,target:t,elementContext:e,pin:n,dragBox:r,instruction:le,references:G.length>0?G:void 0,variantRequest:{count:he},status:"pending"};g(vt=>{const nn=new Map(vt);return nn.set(Se,Je),nn}),f==null||f.capture("comment_added",{instruction_length:le.length,image_count:0,reference_count:G.length,has_variants:!1})}f==null||f.capture("comment_variant_trigger_started",{source:"mcp",requestedCount:he}),te(),R(!0),X.current=setTimeout(()=>{X.current=null,R(!1)},D6e),A(!0),E(!0),C("view"),Me({preserveSelection:!0});const Ke=await T(Se);Ke.success||(te(),R(!1),Nt.error(Ke.error||"Failed to queue direction request"))},[V,G,o,e,t,n,r,g,f,Me,C,E,A,R,T,te]),Ae=$t,ut=h.useCallback(async()=>{var le;if(o){IT(o);const he=(b==null?void 0:b.current)??null;he&&hd(he,m.values());const Se=P.get(ei);Se&&Se.commentId===o&&(await rd(Se.diff),P.set(ei,null));const Ke=m.get(o),Je=(le=Ke==null?void 0:Ke.finalizedVariant)==null?void 0:le.codeDiff;Je&&await rd(Je),g(vt=>{const nn=new Map(vt);return nn.delete(o),nn}),f==null||f.capture("comment_deleted")}Me()},[o,m,b,g,Me,f,P]),qe=h.useCallback(le=>{le.key==="Enter"&&(le.metaKey||le.ctrlKey)&&(le.preventDefault(),le.nativeEvent.stopImmediatePropagation(),Ae()),le.key==="Escape"&&(le.nativeEvent.stopImmediatePropagation(),Me({preserveSelection:!0}))},[Ae,Me]),ne=window.innerHeight,ae=i.y/ne>N6e,we=o?"Save":"Add",Re=(()=>{if(V.trim()==="")return"empty_instruction";if(K.length>0)return"images_attached";if(D)return"active_session";if(O.getStyleChanges().length>0||O.getTextChanges().length>0)return"mixed_batch";const he=Array.from(m.values()).filter(Je=>Je.status==="pending"&&Je.id!==o);return he.some(Je=>!!Je.variantRequest)?"duplicate_variant_request":he.some(Je=>!Je.variantRequest)?"mixed_batch":null})(),Ne=kR(V),ee=(()=>{switch(Re){case"empty_instruction":return"Add an instruction to generate directions.";case"images_attached":return"Remove attached images — image context is not supported for directions yet.";case"mixed_batch":return"Directions must be sent on their own — clear other pending changes first.";case"duplicate_variant_request":return"A direction request is already pending — send or cancel it first.";case"active_session":return"A directions session is already running — finish or cancel it first.";default:return`Generate ${Ne} design directions for the selected element. You'll preview and pick one.`}})();return y.jsx("div",{className:"fixed z-comment-preview cursor-auto",style:{top:ae?i.y-CR:i.y+CR,left:Math.max(SR,Math.min(i.x-ER/2,window.innerWidth-ER-SR)),transform:ae?"translateY(-100%)":void 0},onClick:le=>le.stopPropagation(),children:y.jsx(mn.div,{animate:p,children:y.jsxs(mn.div,{className:"relative flex w-80 flex-col gap-2 rounded-xl bg-main p-4 shadow-2xl",style:{transformOrigin:"center 24px"},initial:{scale:.82,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.82,opacity:0,transition:{duration:.1,ease:[.55,0,1,.45]}},transition:{type:"spring",stiffness:500,damping:28,mass:.8},...He,children:[Qe?y.jsx("div",{className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-xl border-2 border-dashed border-primary bg-primary/10",children:y.jsx("span",{className:"text-sm font-medium text-content",children:"Drop image here"})}):null,G.length>0?y.jsx("div",{className:"flex flex-wrap gap-1.5",children:G.map(le=>y.jsx(E4e,{reference:le,onRemove:()=>be(le)},`${le.sessionId}:${le.variantId}`))}):null,y.jsx("textarea",{ref:le=>{N.current=le,le&&_e(le)},value:V,onChange:le=>{const he=le.target.value;U(le.target.value),_e(le.target),l==null||l(he.trim()!==""||K.length>0)},onKeyDown:qe,onPaste:ye,placeholder:"What should change?",rows:3,style:{maxHeight:"9rem",overflowY:"auto"},className:"w-full resize-none rounded-lg border border-divider bg-main-light p-3 text-sm text-content outline-none transition-colors duration-100 placeholder:text-content-subtle focus:border-primary focus:ring-1 focus:ring-primary/30"}),K.length>0?y.jsx("div",{className:"max-h-40 overflow-y-auto rounded",children:y.jsx("div",{className:`grid gap-1.5 ${K.length===1?"grid-cols-1":"grid-cols-2"}`,children:K.map((le,he)=>y.jsxs("div",{className:"relative",children:[y.jsx("img",{src:le,alt:`Reference ${he+1}`,className:`w-full rounded border border-divider object-cover ${K.length===1?"max-h-32":"aspect-[4/3]"}`}),y.jsx("button",{onClick:()=>nt(he),className:"absolute right-1 top-1 rounded-full bg-red-500/80 p-0.5 text-white backdrop-blur-sm hover:bg-red-600",children:y.jsx(ua,{className:"h-2.5 w-2.5",weight:"bold"})})]},he))})}):null,y.jsx("input",{ref:q,type:"file",accept:"image/*",multiple:!0,onChange:ze,className:"hidden"}),y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsxs("div",{className:"flex items-center gap-1",children:[o?y.jsx("button",{type:"button",onClick:ut,className:"p-1 text-content-subtle transition-colors hover:text-accent-error",title:"Delete comment",children:y.jsx(Vq,{className:"h-4 w-4",weight:"bold"})}):null,y.jsx(Ts,{label:"Attach",children:y.jsx("button",{type:"button","aria-label":"Attach reference image",onClick:()=>{var le;return(le=q.current)==null?void 0:le.click()},className:"p-1 text-content-subtle transition-colors hover:text-content",children:y.jsx(J9,{className:"h-4 w-4",weight:"bold"})})}),y.jsx(Ts,{label:"Reference a direction",children:y.jsxs("div",{className:"relative",children:[y.jsx("button",{type:"button","aria-label":"Reference a direction","aria-haspopup":"listbox","aria-expanded":H,onClick:()=>B(le=>!le),className:`p-1 transition-colors ${H||G.length>0?"text-content":"text-content-subtle hover:text-content"}`,children:y.jsx(j9,{className:"h-4 w-4",weight:"bold"})}),H?y.jsx("div",{className:"absolute bottom-full left-0 z-20 mb-2",children:y.jsx(A4e,{attached:G,commentTarget:t,onChange:ue,onClose:()=>B(!1)})}):null]})}),!a&&k?y.jsx(Ts,{label:"Vary",children:y.jsx("button",{type:"button","aria-label":"Generate 3 directions",onClick:()=>Ae({forceGenerateVariants:!0}),disabled:!J,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:y.jsx(g1,{className:"h-4 w-4",weight:"bold"})})}):null,a?y.jsx(Ts,{label:ee,children:y.jsx("button",{type:"button","aria-label":"Generate directions","data-testid":"mcp-variant-trigger",onClick:()=>void ve(),disabled:Re!==null,className:"p-1 text-content-subtle transition-colors hover:text-content disabled:opacity-50",children:y.jsx(g1,{className:"h-4 w-4",weight:"bold"})})}):null]}),y.jsxs("div",{className:"flex items-center gap-3",children:[y.jsx("button",{type:"button",onClick:()=>Me(),className:"px-2 py-1.5 text-sm text-content-muted transition-colors hover:text-content",children:"Cancel"}),y.jsx("button",{onClick:()=>Ae(),disabled:!J,className:"rounded-full bg-primary px-5 py-1.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:we})]})]})]})})})},j6e="allow-scripts allow-same-origin allow-forms allow-popups allow-modals",F6e="allow-scripts allow-forms allow-popups allow-modals",O6e=e=>e==="embedded"?F6e:j6e,TR=Vt("PreviewSurface"),kB=({target:e,src:t,framework:n,mode:r,isUpstreamReady:i,remountKey:s})=>{const o=ra(e),a=Ge(cte),l=Ge(ute),u=Ge(Ms),f=Ee($r),p=Ge(O3),m=Ge(Mc),g=Ee(Jp),b=Ee($v),x=b==="embedded",k=Ee($c),w=Ge(Dc),[C,E]=zn(ED),[A,R]=h.useState(null),P=h.useRef(null),I=da(),[T,L]=zn(P1),M=h.useCallback(()=>I.get(Dc),[I]),D=T&&xp(T.target,e)?T:null,O=h.useRef(null),{enterEditMode:F}=l4e({iframeRef:O}),Z=Ee(vo);c4e({iframeRef:O,enabled:Z.resize.isEnabled&&!x,surfaceId:o});const V=h.useCallback(_e=>w(_e),[w]),U=h.useCallback((_e,ke,$e)=>{if(M()){E(Qe=>Qe+1);return}V(!1),p(null),m(null),u(e),L({key:crypto.randomUUID(),target:e,elementContext:_e,pin:ke,dragBox:$e})},[M,E,V,p,m,u,L,e]),K=h.useCallback(()=>{if(M()){E(_e=>_e+1);return}L(null),p(null),m(null),V(!1)},[M,E,L,V,p,m]),W=h.useCallback((_e,ke,$e)=>{F(_e,ke,$e)},[F]),{setupIframe:G,clearSelectionState:j,iframeRef:H}=a4e({surfaceId:o,target:e,mode:r,isBoxModelVisible:!0,onTextEdit:W,onCommentClick:U,onCommentSelectionClear:K,isPreviewBridgeEnabled:x}),B=h.useCallback(_e=>{L(null),p(null),m(null),V(!1),_e!=null&&_e.preserveSelection||j()},[j,L,V,p,m]),N=h.useCallback(()=>B({preserveSelection:!0}),[B]),{startCodeGeneration:q}=aB(),X=h.useCallback(_e=>{const ke=f.get(_e);if(!ke)return;V(!1);const $e=ke.styleVariants&&ke.styleVariants.length>0;if(p(_e),m($e?_e:null),u(e),L({key:crypto.randomUUID(),target:e,elementContext:ke.elementContext,pin:ke.pin,dragBox:ke.dragBox,existingCommentId:_e}),ke.variantGenerationStatus!=="generating"&&!ke.finalizedVariant&&ke.styleVariants&&!fse(_e)){const Qe=ke.styleVariants.map((He,ze)=>({v:He,index:ze+1})).filter(({v:He})=>He.changeSpec&&!He.codeDiff&&!He.codeStatus);Qe.length>0&&q({commentId:_e,sessionId:crypto.randomUUID(),instruction:ke.instruction,elementContext:ke.elementContext,variants:Qe.map(({v:He,index:ze})=>({index:ze,label:He.label,changeSpec:He.changeSpec}))})}},[f,V,p,m,u,L,e,q]),te=h.useCallback((_e,ke,$e=!1)=>{const Qe=H.current;if(!Qe)return null;const He=Qe.getBoundingClientRect(),ze=x?null:_r(Qe),ye=ze?fd(ze,_e):null,nt=(ye==null?void 0:ye.getBoundingClientRect())??_e.boundingRect,$t={top:He.top+nt.top,bottom:He.top+nt.bottom},ve=$e&&x4e($t);let Ae=He.top+nt.top+ke.elementYPct*nt.height;return $e&&(Ae=ve?He.top+nt.bottom+av+ov:He.top+nt.top-av-ov),{x:He.left+nt.left+ke.elementXPct*nt.width,y:Ae}},[x,H]),[,ie]=h.useState(0),Y=h.useCallback(()=>ie(_e=>_e+1),[]);h.useEffect(()=>{const _e=H.current;if(!D||!_e)return;const ke=x?null:_r(_e);ke&&ke.addEventListener("scroll",Y,!0);const $e=new ResizeObserver(Y);return $e.observe(_e),_e.addEventListener("load",Y),()=>{ke&&ke.removeEventListener("scroll",Y,!0),$e.disconnect(),_e.removeEventListener("load",Y)}},[D,H,Y,x]);const J=D!=null&&D.existingCommentId?(()=>{var ke;const _e=f.get(D.existingCommentId);return!!((ke=_e==null?void 0:_e.styleVariants)!=null&&ke.length&&!_e.finalizedVariant)})():!1,ue=D?te(D.elementContext,D.pin,J):null,be=i&&!k&&!x;h.useEffect(()=>{if(x){A&&(P.current=null,R(null),l({surfaceId:o,adapter:null}));return}if(n!=="static"&&!i){A&&(P.current=null,R(null),l({surfaceId:o,adapter:null}));return}const _e=H.current;if(A&&P.current!==_e){P.current=null,R(null),l({surfaceId:o,adapter:null});return}if(_e&&!A){const ke=n==="static";TR.debug(`Creating ${ke?"Static":""}IframeDisplayAdapter`);const $e=r==="edit"?"edit":"view",Qe=ke?new u4e(_e,{mode:$e,isBoxModelVisible:!0}):new tB(_e,{mode:$e,isBoxModelVisible:!0});Qe.initialize(),P.current=_e,R(Qe),l({surfaceId:o,adapter:Qe})}},[A,n,i,x,r,H,l,o]);const Me=h.useCallback(_e=>{_e?(G(_e),O.current=_e):O.current=null},[G]);return h.useEffect(()=>(a({surfaceId:o,ref:H}),()=>{a({surfaceId:o,ref:null}),l({surfaceId:o,adapter:null})}),[a,l,o,H]),h.useEffect(()=>{r!=="comment"&&(M()||(L(null),p(null),m(null),r==="view"&&j()))},[r,M,j,L,p,m]),y.jsxs("div",{className:"relative h-full w-full",children:[y.jsx("iframe",{ref:Me,src:t,className:"h-full w-full border-none",title:"Project Preview",sandbox:O6e(b),onLoad:()=>{St==null||St.capture("preview_iframe_loaded",{framework:n,src:t})},onError:()=>{St==null||St.capture("preview_iframe_load_failed",{framework:n,src:t}),TR.warn("Preview iframe failed to load",{framework:n,src:t})}},s),be?y.jsx(p4e,{onEditComment:X,target:e,iframeRef:H}):null,e.kind==="base"&&i&&!x&&!g&&!k?y.jsx(C4e,{onCommentClose:N}):null,(D==null?void 0:D.dragBox)&&!D.existingCommentId&&H.current&&(()=>{const _e=H.current,ke=_e.getBoundingClientRect(),$e=x?null:_r(_e),Qe=$e?fd($e,D.elementContext):null,He=(Qe==null?void 0:Qe.getBoundingClientRect())??D.elementContext.boundingRect,{leftPct:ze,topPct:ye,widthPct:nt,heightPct:$t}=D.dragBox;return y.jsx("div",{"data-comment-drag-box":"true",style:{position:"fixed",pointerEvents:"none",zIndex:45,border:"1px dashed var(--color-primary, #FF3300)",background:"rgba(255, 51, 0, 0.08)",borderRadius:2,boxSizing:"border-box",left:ke.left+He.left+ze*He.width,top:ke.top+He.top+ye*He.height,width:nt*He.width,height:$t*He.height}})})(),D&&ue&&!D.existingCommentId&&y.jsx(nB,{comment:{id:"draft",elementContext:D.elementContext,pin:D.pin,instruction:"",status:"pending"},index:f.size,position:ue,onDismiss:()=>{},onEdit:()=>{}}),tf.createPortal(y.jsx(Fi,{children:D&&ue?y.jsx(L6e,{elementContext:D.elementContext,target:e,pin:D.pin,dragBox:D.dragBox,position:ue,onClose:B,existingCommentId:D.existingCommentId,isMCPSession:g,onInputChange:_e=>{V(_e)},shake:C},D.key):null}),document.body)]})},V6e=({isInteractionDisabled:e=!1,framework:t,userPort:n,activeDemoSessionId:r=null,holdPreviewNavigation:i=!1})=>{const s=Ee(yo),o=Ee(c6),a=Ge(c6),l=Ee(I1),u=Ge(I1),f=Ee(Fs),p=Ee($v),m=Ee(u6),g=Ge(u6),b=f.active&&f.projectContext.kind==="fresh";h.useEffect(()=>{f.active||g(!1)},[f.active,g]);const x=h.useMemo(()=>{var G;if(m||l||!f.active)return null;const{stage:Z,variants:V}=f,U=Z==="ready"||Z==="degraded",K=V.some(j=>{var H,B;return((H=j.refinement)==null?void 0:H.status)==="pending"||((B=j.refinement)==null?void 0:B.status)==="running"});if(!U&&!K)return null;const W=V.find(j=>{var H;return j.status==="succeeded"&&((H=j.preview)==null?void 0:H.kind)==="static_artifact"});return((G=W==null?void 0:W.preview)==null?void 0:G.kind)==="static_artifact"?W.preview.url:null},[l,m,f]),k=l??x,w=h.useMemo(()=>!f.active||!k?null:f.variants.find(Z=>{var V;return((V=Z.preview)==null?void 0:V.kind)==="static_artifact"&&k.startsWith(Z.preview.url)})??null,[k,f]),C=h.useMemo(()=>!f.active||!w?uo:{kind:"variant",sessionId:f.sessionId,variantId:w.workItemId},[w,f]),E=h.useRef(null);h.useEffect(()=>{var K,W;if(!w||((K=w.preview)==null?void 0:K.kind)!=="static_artifact"||((W=w.refinement)==null?void 0:W.status)!=="succeeded")return;const Z=`${w.workItemId}:${w.refinement.workItemId}`;if(E.current===Z)return;E.current=Z;const V=w.preview.url.includes("?")?"&":"?",U=`${w.preview.url}${V}refinement=${encodeURIComponent(w.refinement.workItemId)}`;k!==U&&(u(U),a(G=>G+1))},[k,w,a,u,f]);const A=k!==null||b&&!m,{isUpstreamReady:R,iframeRemountKey:P,initialProbeComplete:I}=Dxe(t,{rerunProbeImmediatelyOnVersion:o,skip:A}),T=!!k||R,L=`${P}:${o}`,M=r?`/try/${encodeURIComponent(r)}`:"",D=t==="static"?`${M}/static/`:`${M}/`,O=p==="embedded"&&typeof window<"u"?`${window.location.protocol}//localhost:${window.location.port}`:"",F=k??(i||!T?"about:blank":`${O}${D}`);return y.jsxs("div",{className:"relative h-full w-full",children:[!T&&I?y.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-main/90 px-6",children:y.jsx("div",{role:"alert","aria-live":"polite",className:"flex max-w-sm flex-col items-center gap-5 text-center",children:b?y.jsxs(y.Fragment,{children:[y.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Directions will appear here"}),y.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"Select one from the panel to preview it."})]}):y.jsxs(y.Fragment,{children:[y.jsx("h2",{className:"text-3xl font-semibold text-content",children:"Preview isn't connected"}),y.jsx("p",{className:"text-base leading-relaxed text-content-muted",children:"The connection between Rivet and your project is offline. Try restarting Rivet, then click reload below."}),y.jsx("button",{onClick:()=>window.location.reload(),className:"rounded-md bg-primary px-10 py-2.5 text-sm font-medium text-white transition-colors hover:bg-primary-hover",children:"Reload"})]})})}):null,y.jsx(kB,{target:C,src:F,framework:t,mode:e?"view":s,isUpstreamReady:T,remountKey:L})]})},Mk=({message:e,isLoading:t=!0})=>y.jsxs("div",{className:"flex items-center gap-2 text-sm text-content",children:[t?y.jsx(dl,{className:"h-4 w-4 shrink-0 animate-spin text-primary",weight:"bold"}):null,y.jsx("span",{className:"whitespace-pre-wrap font-sans",children:e})]});function PR({side:e,sessionId:t,variantId:n,url:r,label:i,isFallback:s=!1}){var b;const o=Ge(of),a=Ee(yo),l=Ee(Fs),u=h.useCallback(()=>{if(s){o(null);return}o(x=>{if(!x)return null;const k={...x};return delete k[e],k.left||k.right?k:null})},[o,e,s]),f=h.useMemo(()=>({kind:"variant",sessionId:t,variantId:n}),[t,n]),p=h.useMemo(()=>!l.active||l.sessionId!==t?null:l.variants.find(x=>x.workItemId===n)??null,[t,n,l]),m=h.useMemo(()=>{var k,w;if(((k=p==null?void 0:p.preview)==null?void 0:k.kind)!=="static_artifact"||((w=p.refinement)==null?void 0:w.status)!=="succeeded")return r;const x=p.preview.url.includes("?")?"&":"?";return`${p.preview.url}${x}refinement=${encodeURIComponent(p.refinement.workItemId)}`},[p,r]),g=((b=p==null?void 0:p.refinement)==null?void 0:b.status)==="succeeded"?`${n}:${p.refinement.workItemId}`:n;return y.jsxs("div",{className:"variant-split-secondary","data-cy":"variant-split-pane","data-variant-id":n,children:[y.jsxs("div",{className:"variant-split-secondary-toolbar",children:[y.jsx("span",{className:"variant-split-secondary-label",title:i,children:i}),y.jsx("button",{type:"button",className:"variant-split-secondary-close",onClick:u,"aria-label":"Exit split view",children:y.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",focusable:"false",children:y.jsx("path",{d:"M2.5 2.5 L9.5 9.5 M9.5 2.5 L2.5 9.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"})})})]}),y.jsx("div",{className:"variant-split-secondary-body relative min-h-0 flex-1",children:y.jsx(kB,{target:f,src:m,framework:"static",mode:a,isUpstreamReady:!0,remountKey:g})})]})}const IR=220,H6e=64;function B6e(){const e=Ee(_p),t=Ee(V3),n=h.useRef(null);return h.useEffect(()=>{if(!e||!t||!n.current)return;const r=t.x-IR/2,i=t.y-22;n.current.style.transform=`translate3d(${r}px, ${i}px, 0)`},[e,t]),e?y.jsx("div",{ref:n,"aria-hidden":"true",className:"variant-drag-ghost",style:{width:IR,height:H6e},children:y.jsx("div",{className:"variant-drag-ghost-row",children:y.jsx("div",{className:"variant-drag-ghost-title",children:e.label})})}):null}function z6e(){const e=Ee(_p),t=Ee(V3),n=Ge(_p),r=Ge(of),i=h.useRef(null),[s,o]=h.useState(null),[a,l]=h.useState("hidden");h.useEffect(()=>{if(!e){l("hidden"),o(null);return}const p=requestAnimationFrame(()=>l("visible"));return()=>cancelAnimationFrame(p)},[e]);const u=h.useCallback((p,m)=>{const g=i.current;if(!g)return null;const b=g.getBoundingClientRect();return p<b.left||p>b.right||m<b.top||m>b.bottom?null:p<(b.left+b.right)/2?"left":"right"},[]);if(h.useEffect(()=>{if(!e||!t)return;const p=u(t.x,t.y);o(m=>m===p?m:p)},[e,t,u]),h.useEffect(()=>{if(!e)return;const p=m=>{const g=u(m.clientX,m.clientY);if(g&&e.url){const b={sessionId:e.sessionId,variantId:e.variantId,label:e.label,url:e.url};r(x=>({...x??{},[g]:b})),l("exiting"),window.setTimeout(()=>n(null),220)}else l("exiting"),window.setTimeout(()=>n(null),220)};return window.addEventListener("pointerup",p),window.addEventListener("pointercancel",p),()=>{window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p)}},[e,u,n,r]),!e)return null;const f=["variant-drop-zones",a==="visible"&&"is-visible",a==="exiting"&&"is-exiting"].filter(Boolean).join(" ");return y.jsxs("div",{ref:i,className:f,"aria-hidden":"true",children:[y.jsx(RR,{side:"left",hovered:s==="left",canDrop:!!e.url,label:e.label}),y.jsx(RR,{side:"right",hovered:s==="right",canDrop:!!e.url,label:e.label})]})}function RR({side:e,hovered:t,canDrop:n,label:r}){return y.jsxs("div",{className:["variant-drop-zone",`is-${e}`,t&&"is-hover",!n&&"is-disabled"].filter(Boolean).join(" "),children:[y.jsxs("div",{className:"variant-drop-zone-inner",children:[y.jsx("div",{className:`variant-drop-zone-icon is-${e}`}),y.jsx("div",{className:"variant-drop-zone-caption",children:n?`Add ${e} split`:"Split unavailable for this direction"})]}),y.jsx("div",{className:"variant-drop-zone-preview","aria-hidden":"true",children:y.jsx("div",{className:"variant-drop-zone-preview-label",children:r})}),y.jsx("div",{className:"variant-drop-zone-border"})]})}const CB=(e,t,n)=>{var s,o;if(!e.active||e.sessionId!==t)return null;const r=e.variants.find(a=>a.workItemId===n);if(((s=r==null?void 0:r.preview)==null?void 0:s.kind)!=="static_artifact")return null;if(((o=r.refinement)==null?void 0:o.status)!=="succeeded")return r.preview.url;const i=r.preview.url.includes("?")?"&":"?";return`${r.preview.url}${i}refinement=${encodeURIComponent(r.refinement.workItemId)}`},MR=(e,t)=>{if(!e)return;const n=CB(t,e.sessionId,e.variantId);return!n||n===e.url?e:{...e,url:n}},U6e=({isLoading:e=!1,isInteractionDisabled:t=!1,activeDemoSessionId:n=null,holdHostedTryoutPreviewNavigation:r=!1})=>{const{config:i,fetchConfig:s,isLoading:o,error:a}=Sxe();return h.useEffect(()=>{s().catch(l=>{St==null||St.capture("preview_config_load_failed",{message:l instanceof Error?l.message:"unknown_error"})})},[s]),o?r?y.jsx("div",{className:"flex h-full min-h-0 w-full flex-1 bg-main","aria-busy":"true"}):y.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:y.jsx(Mk,{message:"Loading..."})})}):a||!i?y.jsx("div",{className:"flex h-full w-full items-center justify-center bg-main px-6",children:y.jsxs("div",{className:"max-w-md rounded-lg border border-divider bg-main-light p-4 text-center shadow-lg",children:[y.jsx("p",{className:"text-sm font-medium text-content",children:"We couldn't load your app preview."}),y.jsx("p",{className:"mt-2 text-sm text-content-subtle",children:a||"Missing preview configuration from the server."}),y.jsx("p",{className:"mt-2 text-sm text-content-subtle",children:"If this keeps happening, restart your Rivet session and try again."}),y.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{St==null||St.capture("preview_config_retry_clicked"),s().catch(l=>{St==null||St.capture("preview_config_load_failed",{message:l instanceof Error?l.message:"unknown_error"})})},children:"Retry preview"})]})}):y.jsx(Z6e,{isLoading:e,isInteractionDisabled:t,framework:i.framework,userPort:i.userPort,activeDemoSessionId:n,holdHostedTryoutPreviewNavigation:r})};function Z6e(e){const t=Ee(of),n=Ee(_p),r=Ee(yo),i=Ge(j3),s=Ee(Fs),o=Ee(I1),a=t==null?void 0:t.left,l=t==null?void 0:t.right,u=h.useMemo(()=>{var I,T;if(!s.active||s.projectContext.kind!=="fresh"||!(!!a!=!!l))return;const w=(I=a??l)==null?void 0:I.variantId,C=s.variants.filter(L=>{var M;return L.status==="succeeded"&&((M=L.preview)==null?void 0:M.kind)==="static_artifact"&&L.workItemId!==w}),E=o==null?void 0:o.replace(/[?&]refinement=[^&]*$/,""),R=C.find(L=>{var M;return((M=L.preview)==null?void 0:M.kind)==="static_artifact"&&L.preview.url===E})??C[0];if(((T=R==null?void 0:R.preview)==null?void 0:T.kind)!=="static_artifact")return;const P=CB(s,s.sessionId,R.workItemId);if(P)return{sessionId:s.sessionId,variantId:R.workItemId,label:R.label,url:P}},[s,a,l,o]),f=MR(a,s)??(l?u:void 0),p=MR(l,s)??(a?u:void 0),m=!a&&!!f,g=!l&&!!p,b=!!(f||p),x=y.jsx(V6e,{isInteractionDisabled:e.isInteractionDisabled,framework:e.framework,userPort:e.userPort,activeDemoSessionId:e.activeDemoSessionId,holdPreviewNavigation:e.holdHostedTryoutPreviewNavigation});return y.jsxs("div",{className:`variant-preview-region relative flex h-full min-h-0 w-full flex-1 flex-col ${n?"is-dragging":""} ${b?"is-split":""}`,children:[e.isInteractionDisabled?null:y.jsx(Pxe,{mode:r,onModeChange:i,isLoading:e.isLoading}),y.jsxs("div",{className:"variant-preview-row flex h-full min-h-0 w-full flex-1",children:[f&&y.jsx(PR,{side:"left",sessionId:f.sessionId,variantId:f.variantId,url:f.url,label:f.label,isFallback:m},`left-${f.sessionId}:${f.variantId}:${f.url}`),!(f&&p)&&y.jsx("div",{className:"variant-preview-primary flex h-full min-h-0 flex-1 flex-col",children:x}),p&&y.jsx(PR,{side:"right",sessionId:p.sessionId,variantId:p.variantId,url:p.url,label:p.label,isFallback:g},`right-${p.sessionId}:${p.variantId}:${p.url}`)]}),y.jsx("div",{className:"variant-preview-atmosphere","aria-hidden":"true"}),y.jsx(z6e,{}),y.jsx(B6e,{})]})}const W6e=Vt("SupportTicketModal"),$R=5e3,mw="feedback",G6e=e=>{var r;if(!e)return null;const t=(r=e.formErrors)==null?void 0:r[0];if(t)return t;const n=e.fieldErrors??{};for(const i of Object.values(n)){const s=i==null?void 0:i[0];if(s)return s}return null},q6e=async e=>{let t;try{t=await e.json()}catch{t=void 0}if(e.status===400){if(typeof(t==null?void 0:t.details)=="string"&&t.details.trim())return t.details;if(typeof(t==null?void 0:t.details)=="object"&&t.details!==null){const n=G6e(t.details);if(n)return n}return"Please check your feedback and try again."}return e.status>=500?typeof(t==null?void 0:t.details)=="string"&&t.details.trim()?t.details:"Could not send feedback right now. Please try again later.":typeof(t==null?void 0:t.error)=="string"&&t.error.trim()?t.error:`HTTP ${e.status}`},K6e=({isOpen:e,onClose:t,contactEmail:n})=>{const r=xi(),[i,s]=h.useState(""),[o,a]=h.useState(!1),l=h.useCallback(()=>{s("")},[]),u=h.useCallback(()=>{o||(l(),t())},[o,t,l]),f=h.useCallback(async()=>{const b=i.trim();if(!(!b||o)){a(!0);try{const x=typeof(r==null?void 0:r.get_session_id)=="function"?r.get_session_id():void 0,k=typeof(r==null?void 0:r.get_distinct_id)=="function"?r.get_distinct_id():void 0,w=n==null?void 0:n.trim(),C=await fetch("/api/support/tickets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:mw,message:b,contactEmail:w||void 0,metadata:{posthogSessionId:x??void 0,posthogDistinctId:k??void 0,appVersion:"0.10.3",appEnvironment:"production",pageUrl:window.location.href,userAgent:navigator.userAgent,submittedAt:new Date().toISOString()}})});if(!C.ok){const E=await q6e(C);throw new Error(E)}r==null||r.capture("support_ticket_submitted",{ticket_type:mw,has_posthog_session_id:!!x}),Nt.success("Feedback sent",{description:"Thanks for sharing this."}),l(),t()}catch(x){const k=x instanceof Error?x.message:"Failed to send message";r==null||r.capture("support_ticket_submit_failed",{ticket_type:mw,error:k}),W6e.error("Failed to submit support ticket:",k),Nt.error("Could not send feedback",{description:k})}finally{a(!1)}}},[n,o,i,t,r,l]),p=h.useCallback(b=>{b.key==="Enter"&&(b.metaKey||b.ctrlKey)&&(b.preventDefault(),f())},[f]),m=$R-i.length,g=o||i.trim().length===0;return y.jsx(xy,{open:e,onOpenChange:b=>!b&&u(),children:y.jsxs(wy,{children:[y.jsx(_y,{className:"fixed inset-0 z-max bg-black/40"}),y.jsx(ky,{className:"fixed left-1/2 top-1/2 z-max w-[480px] -translate-x-1/2 -translate-y-1/2 rounded-lg border border-divider bg-main p-6 shadow-xl outline-none",children:y.jsxs("div",{className:"flex flex-col gap-4",children:[y.jsxs("div",{className:"flex items-center justify-between",children:[y.jsx(Op,{className:"text-lg font-semibold text-content",children:"Send feedback"}),y.jsx(Ck,{asChild:!0,children:y.jsx("button",{className:"rounded p-1 text-content-subtle transition-colors hover:text-content",disabled:o,children:y.jsx(ua,{className:"h-4 w-4",weight:"bold"})})})]}),y.jsx("p",{className:"text-sm text-content-subtle",children:"Tell us what happened or what we can improve."}),y.jsxs("div",{className:"space-y-2",children:[y.jsx("label",{htmlFor:"support-ticket-message",className:"text-xs font-medium text-content-muted",children:"Your feedback"}),y.jsx("textarea",{id:"support-ticket-message",value:i,onChange:b=>s(b.target.value),onKeyDown:p,maxLength:$R,rows:7,disabled:o,placeholder:"What happened?",className:"w-full resize-none rounded-md border border-divider bg-main-input px-3 py-2 text-sm text-content outline-none placeholder:text-content-subtle disabled:opacity-50"}),y.jsxs("div",{className:"flex justify-between text-xs text-content-subtle",children:[y.jsx("span",{children:"Context details are included automatically."}),y.jsx("span",{children:m})]})]}),y.jsx("button",{onClick:f,disabled:g,className:"flex w-full items-center justify-center gap-2 rounded-md bg-primary px-3 py-2 text-xs text-white transition-colors hover:bg-primary-hover disabled:opacity-50",children:o?y.jsxs(y.Fragment,{children:[y.jsx(dl,{className:"h-4 w-4 animate-spin",weight:"bold"}),y.jsx("span",{children:"Sending..."})]}):y.jsx("span",{children:"Send feedback"})})]})})]})})},EB="data:image/svg+xml,%3csvg%20width='94'%20height='24'%20viewBox='0%200%2094%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M-0.000156164%2023.832V7.704H5.11184L6.47984%208.424C7.58384%207.704%209.04784%207.344%2010.8718%207.344C12.0718%207.344%2013.1278%207.476%2014.0398%207.74C14.9518%207.98%2015.6838%208.244%2016.2358%208.532C16.8118%208.82%2017.1718%209.024%2017.3158%209.144L15.5158%2013.824C15.2758%2013.656%2014.8198%2013.428%2014.1478%2013.14C13.4998%2012.852%2012.7318%2012.588%2011.8438%2012.348C10.9558%2012.084%2010.0198%2011.952%209.03584%2011.952H8.63984C7.96784%2011.952%207.45184%2012.072%207.09184%2012.312C6.73184%2012.528%206.55184%2013.02%206.55184%2013.788V23.832H-0.000156164ZM23.464%206.156C21.04%206.156%2019.828%205.124%2019.828%203.06C19.828%201.908%2020.128%201.116%2020.728%200.684C21.352%200.227999%2022.264%20-1.43051e-06%2023.464%20-1.43051e-06C24.736%20-1.43051e-06%2025.66%200.227999%2026.236%200.684C26.836%201.116%2027.136%201.908%2027.136%203.06C27.136%205.124%2025.912%206.156%2023.464%206.156ZM20.152%2023.832V7.704H26.704V23.832H20.152ZM37.4767%2023.832L29.6647%207.704H36.9007L40.3207%2016.524L41.2567%2019.116H41.6167L42.5527%2016.524L46.0087%207.704H53.1727L52.5967%209.9L45.4327%2023.832H37.4767ZM61.1953%2023.832C59.6113%2023.832%2058.3873%2023.604%2057.5233%2023.148C56.6833%2022.692%2056.1073%2022.068%2055.7953%2021.276C55.4833%2020.46%2055.3273%2019.524%2055.3273%2018.468V13.032C55.3273%2012.072%2055.4833%2011.196%2055.7953%2010.404C56.1313%209.588%2056.7193%208.94%2057.5593%208.46C58.3993%207.956%2059.6113%207.704%2061.1953%207.704H68.6473C70.5193%207.704%2071.9473%207.932%2072.9313%208.388C73.9393%208.82%2074.6233%209.444%2074.9833%2010.26C75.3673%2011.052%2075.5593%2011.976%2075.5593%2013.032V17.64H69.2593C67.0993%2017.64%2065.4553%2017.592%2064.3273%2017.496C63.2233%2017.4%2062.4433%2017.34%2061.9873%2017.316V17.856C61.9633%2018.816%2062.5393%2019.296%2063.7153%2019.296H64.8313C66.7513%2019.296%2068.5273%2019.26%2070.1593%2019.188C71.7913%2019.092%2073.0033%2019.008%2073.7953%2018.936L75.9553%2022.356C75.9553%2022.596%2075.7513%2022.824%2075.3433%2023.04C74.9353%2023.256%2074.2153%2023.448%2073.1833%2023.616C72.1753%2023.76%2070.7353%2023.832%2068.8633%2023.832H61.1953ZM61.9873%2014.184H68.8993V13.68C68.8993%2013.2%2068.8513%2012.864%2068.7553%2012.672C68.6833%2012.48%2068.4313%2012.36%2067.9993%2012.312C67.5673%2012.264%2066.8353%2012.24%2065.8033%2012.24H63.7153C62.5633%2012.24%2061.9873%2012.72%2061.9873%2013.68V14.184ZM85.8224%2023.832C83.9984%2023.832%2082.7504%2023.448%2082.0784%2022.68C81.4064%2021.912%2081.0704%2020.76%2081.0704%2019.224V12.24H78.1184V7.704H79.6304C80.0384%207.704%2080.3624%207.632%2080.6024%207.488C80.8664%207.32%2081.0344%207.032%2081.1064%206.624L81.7904%202.772H87.6944V7.704H93.7064V12.24H87.6944V17.82C87.6944%2018.42%2087.8384%2018.816%2088.1264%2019.008C88.4144%2019.2%2088.8464%2019.296%2089.4224%2019.296H93.0224L93.7424%2023.472C93.2384%2023.544%2092.4704%2023.628%2091.4384%2023.724C90.4064%2023.796%2089.2784%2023.832%2088.0544%2023.832H85.8224Z'%20fill='%23FF3300'/%3e%3c/svg%3e",SB=({isSigningIn:e,onStartSignIn:t,errorMessage:n=null,isDesktopShell:r=!1,displayMode:i="full"})=>{const s=i==="modal";return y.jsxs("div",{className:s?"glass-panel relative w-full max-w-sm rounded-2xl border border-white/10 px-8 py-14 font-main text-white shadow-2xl":"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:[r&&!s?y.jsx("div",{className:"fixed left-0 right-0 top-0 z-10 h-8",style:{WebkitAppRegion:"drag"}}):null,y.jsxs("div",{className:"flex flex-col items-center gap-10",children:[y.jsx("img",{src:EB,alt:"Rivet",className:"h-8 w-auto object-contain"}),y.jsxs("div",{className:"text-center",children:[y.jsx("h1",{className:"mb-2 text-xl font-medium text-content",children:"Welcome to Rivet"}),y.jsx("p",{className:"text-sm text-content-muted",children:"Sign in to get started"})]}),y.jsx("button",{onClick:t,disabled:e,className:"glass-panel active-push flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium transition-all hover:bg-white/10 disabled:opacity-50",children:e?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"}),y.jsx("span",{children:"Signing in..."})]}):y.jsxs(y.Fragment,{children:[y.jsx("img",{src:"https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/google.svg",alt:"Google",className:"h-5 w-5 brightness-110"}),y.jsx("span",{children:"Sign in with Google"})]})}),n?y.jsx("p",{className:"text-center text-xs text-red-200",children:n}):null]})]})},Y6e=({message:e})=>y.jsx("div",{className:"relative flex min-h-screen flex-col items-center justify-center overflow-hidden bg-[#1c1c20] font-main text-white",children:y.jsxs("div",{className:"flex flex-col items-center gap-10",children:[y.jsx("img",{src:EB,alt:"Rivet",className:"h-8 w-auto object-contain"}),y.jsxs("div",{className:"glass-panel flex items-center gap-3 rounded-xl px-8 py-3.5 text-sm font-medium",children:[y.jsx(dl,{className:"h-5 w-5 shrink-0 animate-spin text-primary",weight:"bold"}),y.jsx("span",{children:e})]})]})}),DR=Vt("useConfig"),X6e=()=>{var e;return typeof window>"u"?null:((e=window.__RIVET_BOOTSTRAP__)==null?void 0:e.queueAccessToken)??null},Q6e=()=>{var e;return typeof window>"u"?null:((e=window.__RIVET_BOOTSTRAP__)==null?void 0:e.agentApplyMode)??null},J6e=()=>{const e=Ee(vo),t=Ge(vo),n=Ge(Jp),r=Ge(B3),i=Ge($v),s=Ge(z3),o=Ge(kD),a=Ge(_D),l=Ge(yD),u=h.useCallback(b=>{o(b.agentModeAvailable),l({name:b.name??null,email:b.email??null}),t(b.featureFlags??vD),a(!0),b.isMCPSession&&n(!0),b.mcpEditor&&r(b.mcpEditor),i(b.agentApplyMode??Q6e()??null),s(b.queueAccessToken??X6e())},[i,o,t,a,n,r,s,l]),f=mZ({queryKey:["rivet-config"],queryFn:async()=>{const b=await fetch("/api/config");if(!b.ok)throw new Error(`Failed to fetch config: ${b.statusText}`);return await b.json()},staleTime:3e4}),{refetch:p}=f;h.useEffect(()=>{f.data&&(u(f.data),DR.info("Config loaded:",f.data))},[f.data,u]),h.useEffect(()=>{f.error&&(a(!0),DR.warn("Failed to load config:",f.error instanceof Error?f.error.message:"Failed to load config"))},[f.error,a]);const m=h.useCallback(async()=>{const b=await p();return b.data?b.data:(a(!0),null)},[p,a]);let g=null;return f.error instanceof Error?g=f.error.message:f.error&&(g="Failed to load config"),{config:f.data??null,featureFlags:e,loading:f.isPending,error:g,refetchConfig:m}};var Ay={};const e8e="https://rivet-proxy.onrender.com";var qR;const gw=(qR=Ay.RIVET_PROXY_URL)==null?void 0:qR.trim(),D8=gw&&gw.length>0?gw:e8e,t8e="https://rivet-core-production.up.railway.app";var KR;const vw=(KR=Ay.RIVET_GATEWAY_URL)==null?void 0:KR.trim();vw&&vw.length>0;const n8e="https://rivet-prototype-host.onrender.com";var YR;const yw=(YR=Ay.RIVET_PROTOTYPE_HOST_URL)==null?void 0:YR.trim();yw&&yw.length>0;const r8e="https://us.i.posthog.com";var XR;const bw=(XR=Ay.RIVET_POSTHOG_HOST)==null?void 0:XR.trim();bw&&bw.length>0;const Hu=Vt("useOAuthCallback"),i8e=()=>{const[e,t]=h.useState({isProcessing:!1,isComplete:!1,error:null});return h.useEffect(()=>{const n=new AbortController;let r=!1;return(async()=>{var a,l,u;const s=window.location.hash,o=window.location.search;if(!(!s||!s.includes("access_token"))&&!r){t({isProcessing:!0,isComplete:!1,error:null});try{Hu.info("Processing OAuth callback...");const f=new URLSearchParams(s.substring(1)),p=f.get("access_token"),m=f.get("refresh_token"),b=new URLSearchParams(o).get("session");if(!p)throw new Error("No access token found in URL");if(!b)throw new Error("No session ID found in URL");Hu.info(`Completing OAuth with session: ${b}`);const x=await fetch(`${D8}/api/auth/google/complete`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:b,accessToken:p,refreshToken:m}),signal:n.signal}),k=await x.json();if(!x.ok||!k.success)throw new Error(k.error||k.message||"Failed to complete authentication");if(Hu.info("OAuth authentication completed successfully"),r)return;if((a=k.user)!=null&&a.id?(St.identify(k.user.id,{...k.user.email?{email:k.user.email}:{}}),k.user.email&&St.alias(k.user.email,k.user.id)):(l=k.user)!=null&&l.email&&St.identify(k.user.email,{email:k.user.email}),(u=k.user)!=null&&u.email&&p)try{const C=await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:k.user.email,token:p,refreshToken:m,userId:k.user.id}),signal:n.signal});C.ok||Hu.warn(`Local auth store returned ${C.status}`)}catch(C){if(r)return;Hu.warn("Failed to store auth locally:",C)}if(r)return;const w=window.location.pathname;window.history.replaceState({},document.title,w),t({isProcessing:!1,isComplete:!0,error:null})}catch(f){if(r)return;const p=f instanceof Error?f.message:"Unknown error occurred";Hu.warn("OAuth callback error:",f),t({isProcessing:!1,isComplete:!1,error:p})}}})(),()=>{r=!0,n.abort()}},[]),e},xw=Vt("useAgentVariantsSession"),s8e=()=>{const e=Ge(Fs),t=Ge($c),n=Ge(Qp),r=Ge(yo),i=Ge(H3),s=Ge(hte),o=da(),a=h.useRef(null);h.useEffect(()=>{const l=new EventSource("/api/variants/events");return l.onmessage=u=>{try{const f=JSON.parse(u.data),p=a.current;f.active?(i(!1),f.sessionId!==a.current&&(a.current=f.sessionId,t(!0),n(!0),r("view"))):(a.current!==null&&t(!1),a.current=null,i(!1)),e(f);const m=!f.active&&p!==null,g=f.active&&f.sessionId!==p;if(g&&fetch(`/api/variants/${f.sessionId}/preview-port`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({variantId:null})}).catch(b=>xw.warn("failed to reset preview-port on session switch",b)),m||g){const b=new Set;if(f.active)for(const k of f.variants)b.add(ra({kind:"variant",sessionId:f.sessionId,variantId:k.workItemId}));const x=o.get(of);for(const k of[x==null?void 0:x.left,x==null?void 0:x.right])k&&b.add(ra({kind:"variant",sessionId:k.sessionId,variantId:k.variantId}));s(b)}}catch(f){xw.warn("failed to parse SSE event payload",f)}},l.onerror=u=>{xw.warn("SSE error (auto-reconnects)",u),i(!1)},()=>{l.close()}},[e,t,n,r,i,s,o])},Bu=Vt("useTokenEditor"),o8e=()=>{const[e,t]=h.useState(null),[n,r]=h.useState(null),[i,s]=h.useState(new Map),[o,a]=h.useState(!0),[l,u]=h.useState(!1),[f,p]=h.useState(null),m=h.useCallback(async()=>{a(!0),p(null);try{const k=await fetch("/api/tokens");if(!k.ok)throw new Error(`Failed to fetch tokens: ${k.statusText}`);const w=await k.json();t(w.registry),r(w.framework),Bu.info(`Loaded ${w.framework} tokens`)}catch(k){const w=k instanceof Error?k.message:"Unknown error";p(w),Bu.warn("Failed to fetch tokens:",k)}finally{a(!1)}},[]);h.useEffect(()=>{m()},[m]);const g=h.useCallback((k,w,C,E)=>{const A=`${k}.${w}`;s(R=>{const P=new Map(R);return E===C?P.delete(A):P.set(A,{category:k,path:w,originalValue:C,newValue:E}),P})},[]),b=h.useCallback(async()=>{if(i.size===0)return!0;u(!0),p(null);const k=Array.from(i.values());let w=!0;for(const C of k)try{Bu.info(`Saving ${C.category}.${C.path} = "${C.newValue}"`);const A=await(await fetch("/api/tokens/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:C.category,path:C.path,value:C.newValue})})).json();if(!A.success)throw new Error(A.error||"Update failed");Bu.info(`Successfully saved ${C.category}.${C.path}`)}catch(E){const A=E instanceof Error?E.message:"Unknown error";p(`Failed to update ${C.category}.${C.path}: ${A}`),Bu.warn(`Failed to save ${C.category}.${C.path}:`,E),w=!1;break}return w&&(s(new Map),await m()),u(!1),w},[i,m]),x=h.useCallback(()=>{s(new Map),Bu.info("Reverted all pending changes")},[]);return{tokens:e,framework:n,pendingChanges:i,isLoading:o,isSaving:l,error:f,updateToken:g,saveChanges:b,revertChanges:x,refetch:m}};var ww="rovingFocusGroup.onEntryFocus",a8e={bubbles:!1,cancelable:!0},f0="RovingFocusGroup",[N8,AB,l8e]=ny(f0),[c8e,TB]=Os(f0,[l8e]),[u8e,d8e]=c8e(f0),PB=h.forwardRef((e,t)=>y.jsx(N8.Provider,{scope:e.__scopeRovingFocusGroup,children:y.jsx(N8.Slot,{scope:e.__scopeRovingFocusGroup,children:y.jsx(f8e,{...e,ref:t})})}));PB.displayName=f0;var f8e=h.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:u,preventScrollOnEntryFocus:f=!1,...p}=e,m=h.useRef(null),g=an(t,m),b=l0(s),[x,k]=Ls({prop:o,defaultProp:a??null,onChange:l,caller:f0}),[w,C]=h.useState(!1),E=ml(u),A=AB(n),R=h.useRef(!1),[P,I]=h.useState(0);return h.useEffect(()=>{const T=m.current;if(T)return T.addEventListener(ww,E),()=>T.removeEventListener(ww,E)},[E]),y.jsx(u8e,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:x,onItemFocus:h.useCallback(T=>k(T),[k]),onItemShiftTab:h.useCallback(()=>C(!0),[]),onFocusableItemAdd:h.useCallback(()=>I(T=>T+1),[]),onFocusableItemRemove:h.useCallback(()=>I(T=>T-1),[]),children:y.jsx(Mt.div,{tabIndex:w||P===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:bt(e.onMouseDown,()=>{R.current=!0}),onFocus:bt(e.onFocus,T=>{const L=!R.current;if(T.target===T.currentTarget&&L&&!w){const M=new CustomEvent(ww,a8e);if(T.currentTarget.dispatchEvent(M),!M.defaultPrevented){const D=A().filter(U=>U.focusable),O=D.find(U=>U.active),F=D.find(U=>U.id===x),V=[O,F,...D].filter(Boolean).map(U=>U.ref.current);MB(V,f)}}R.current=!1}),onBlur:bt(e.onBlur,()=>C(!1))})})}),IB="RovingFocusGroupItem",RB=h.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...a}=e,l=is(),u=s||l,f=d8e(IB,n),p=f.currentTabStopId===u,m=AB(n),{onFocusableItemAdd:g,onFocusableItemRemove:b,currentTabStopId:x}=f;return h.useEffect(()=>{if(r)return g(),()=>b()},[r,g,b]),y.jsx(N8.ItemSlot,{scope:n,id:u,focusable:r,active:i,children:y.jsx(Mt.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...a,ref:t,onMouseDown:bt(e.onMouseDown,k=>{r?f.onItemFocus(u):k.preventDefault()}),onFocus:bt(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:bt(e.onKeyDown,k=>{if(k.key==="Tab"&&k.shiftKey){f.onItemShiftTab();return}if(k.target!==k.currentTarget)return;const w=m8e(k,f.orientation,f.dir);if(w!==void 0){if(k.metaKey||k.ctrlKey||k.altKey||k.shiftKey)return;k.preventDefault();let E=m().filter(A=>A.focusable).map(A=>A.ref.current);if(w==="last")E.reverse();else if(w==="prev"||w==="next"){w==="prev"&&E.reverse();const A=E.indexOf(k.currentTarget);E=f.loop?g8e(E,A+1):E.slice(A+1)}setTimeout(()=>MB(E))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:x!=null}):o})})});RB.displayName=IB;var h8e={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function p8e(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function m8e(e,t,n){const r=p8e(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return h8e[r]}function MB(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function g8e(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var v8e=PB,y8e=RB,Ty="Tabs",[b8e]=Os(Ty,[TB]),$B=TB(),[x8e,$k]=b8e(Ty),DB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:i,defaultValue:s,orientation:o="horizontal",dir:a,activationMode:l="automatic",...u}=e,f=l0(a),[p,m]=Ls({prop:r,onChange:i,defaultProp:s??"",caller:Ty});return y.jsx(x8e,{scope:n,baseId:is(),value:p,onValueChange:m,orientation:o,dir:f,activationMode:l,children:y.jsx(Mt.div,{dir:f,"data-orientation":o,...u,ref:t})})});DB.displayName=Ty;var NB="TabsList",LB=h.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...i}=e,s=$k(NB,n),o=$B(n);return y.jsx(v8e,{asChild:!0,...o,orientation:s.orientation,dir:s.dir,loop:r,children:y.jsx(Mt.div,{role:"tablist","aria-orientation":s.orientation,...i,ref:t})})});LB.displayName=NB;var jB="TabsTrigger",FB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:i=!1,...s}=e,o=$k(jB,n),a=$B(n),l=HB(o.baseId,r),u=BB(o.baseId,r),f=r===o.value;return y.jsx(y8e,{asChild:!0,...a,focusable:!i,active:f,children:y.jsx(Mt.button,{type:"button",role:"tab","aria-selected":f,"aria-controls":u,"data-state":f?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:l,...s,ref:t,onMouseDown:bt(e.onMouseDown,p=>{!i&&p.button===0&&p.ctrlKey===!1?o.onValueChange(r):p.preventDefault()}),onKeyDown:bt(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&o.onValueChange(r)}),onFocus:bt(e.onFocus,()=>{const p=o.activationMode!=="manual";!f&&!i&&p&&o.onValueChange(r)})})})});FB.displayName=jB;var OB="TabsContent",VB=h.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:i,children:s,...o}=e,a=$k(OB,n),l=HB(a.baseId,r),u=BB(a.baseId,r),f=r===a.value,p=h.useRef(f);return h.useEffect(()=>{const m=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(m)},[]),y.jsx(wo,{present:i||f,children:({present:m})=>y.jsx(Mt.div,{"data-state":f?"active":"inactive","data-orientation":a.orientation,role:"tabpanel","aria-labelledby":l,hidden:!m,id:u,tabIndex:0,...o,ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0},children:m&&s})})});VB.displayName=OB;function HB(e,t){return`${e}-trigger-${t}`}function BB(e,t){return`${e}-content-${t}`}var w8e=DB,_8e=LB,k8e=FB,C8e=VB;const E8e=({tokens:e,pendingChanges:t,category:n,onUpdateToken:r,highlightToken:i})=>{const[s,o]=h.useState(null),[a,l]=h.useState(""),u=h.useRef(null);if(h.useEffect(()=>{i&&u.current&&setTimeout(()=>{var x;(x=u.current)==null||x.scrollIntoView({behavior:"smooth",block:"center"})},100)},[i]),!e||Object.keys(e).length===0)return y.jsx("div",{className:"flex items-center justify-center py-12 text-sm text-gray-500",children:"No tokens defined for this category"});const f=(x,k)=>{const w=`${n}.${x}`,C=t.get(w);return C?C.newValue:k},p=x=>{if(x.includes("var(")||x.includes("--"))return{textClass:"text-white",mutedClass:"text-white/70"};let k=0,w=0,C=0,E=!1;if(x.startsWith("#")){const I=x.slice(1);I.length===3?(k=parseInt(I[0]+I[0],16),w=parseInt(I[1]+I[1],16),C=parseInt(I[2]+I[2],16),E=!0):I.length>=6&&(k=parseInt(I.slice(0,2),16),w=parseInt(I.slice(2,4),16),C=parseInt(I.slice(4,6),16),E=!0)}const A=x.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(A&&(k=parseInt(A[1],10),w=parseInt(A[2],10),C=parseInt(A[3],10),E=!0),!E){const I=x.match(/rgba?\(\s*(\d+)\s+(\d+)\s+(\d+)/);I&&(k=parseInt(I[1],10),w=parseInt(I[2],10),C=parseInt(I[3],10),E=!0)}if(!E){const I=x.match(/hsla?\(\s*(\d+)\s*,\s*(\d+)%?\s*,\s*(\d+)%?/);if(I){const T=xT(parseInt(I[1],10),parseInt(I[2],10),parseInt(I[3],10));k=T.r,w=T.g,C=T.b,E=!0}}if(!E){const I=x.match(/hsla?\(\s*(\d+)\s+(\d+)%?\s+(\d+)%?/);if(I){const T=xT(parseInt(I[1],10),parseInt(I[2],10),parseInt(I[3],10));k=T.r,w=T.g,C=T.b,E=!0}}if(!E){const I=x.match(/oklch\(\s*([\d.]+)(%?)/);if(I){const T=parseFloat(I[1]),M=(I[2]==="%"?T/100:T)>.5;return{textClass:M?"text-gray-900":"text-white",mutedClass:M?"text-gray-600":"text-white/70"}}}if(!E)return{textClass:"text-white",mutedClass:"text-white/70"};const P=vie(k,w,C)>.5;return{textClass:P?"text-gray-900":"text-white",mutedClass:P?"text-gray-600":"text-white/70"}},m=(x,k,w,C)=>{const E=f(k,w),A=s===k,R=A&&a?a:E,P=k.replace(/\./g,"-"),I=i===P||i===x,T=R.includes("rgba")||R.startsWith("#")&&R.length===9||/oklch\(/.test(R)&&R.includes("/"),{textClass:L}=p(R),M=Z=>{l(Z)},D=Z=>{r(n,k,w,Z),o(null),l("")},O=Z=>{Z?(o(k),l(E)):(a&&a!==E&&r(n,k,w,a),o(null),l(""))},F=C?"h-44":"h-52";return y.jsxs(oa,{open:A,onOpenChange:O,children:[y.jsx(Tl,{asChild:!0,children:y.jsxs("div",{ref:I?u:null,className:`group relative flex ${F} cursor-pointer flex-col justify-between overflow-hidden rounded-lg border border-white/10 p-4 transition-all ${I?"animate-token-highlight":""}`,children:[y.jsxs("div",{className:"absolute inset-0",children:[T&&y.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`
|
|
612
612
|
linear-gradient(45deg, #e5e5e5 25%, transparent 25%),
|
|
613
613
|
linear-gradient(-45deg, #e5e5e5 25%, transparent 25%),
|
|
614
614
|
linear-gradient(45deg, transparent 75%, #e5e5e5 75%),
|
|
@@ -642,4 +642,4 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
|
|
|
642
642
|
<body>
|
|
643
643
|
<div class="panel">${jR}</div>
|
|
644
644
|
</body>
|
|
645
|
-
</html>`,Z8e="Too many people are trying Rivet right now. Please try again in a few minutes.",UB="Failed to start an isolated demo session.",W8e=async e=>{if(e.status===429)return Z8e;try{const t=await e.json();if(t.error)return t.error;if(t.message)return t.message}catch{}return UB},G8e=({contactEmail:e,projectPath:t,activeDemoSessionId:n=null,showLoginGate:r=!1,onStartLogin:i,isStartingLogin:s=!1,loginError:o=null,fullPageHostedLoginProgressMessage:a=null,holdHostedTryoutPreviewNavigation:l=!1,hostedTryoutPreviewHoldMessage:u=null,deferInspectorUntilPreviewReady:f=!1})=>{const[p,m]=zn(os),g=Ge(sf),b=Ge(F3),x=Ge(j3),[k,w]=zn(ote),C=Ee(yo),[E,A]=zn(Qp),[R,P]=zn($c),I=Ee(Fs),[T,L]=h.useState(!1),[M,D]=zn($r),O=Ee(Dc),F=Ge(ED),Z=Ge(P1),V=Ge(O3),U=Ge(Mc),K=Ge(Dc),W=i8e();s8e();const G=W.isProcessing?"Completing authentication...":a,j=G!==null,H=h.useRef((p==null?void 0:p.xpath)??null),B=h.useRef(!1),N=h.useRef(!1),q=Ge(Mv),X=Pk();h.useEffect(()=>{q(t??null)},[t,q]),h.useEffect(()=>{if(!t||B.current)return;B.current=!0;const J=y4e(t);J.size>0&&(N.current=!0,D(J));const ue=g4e(t);ue&&X(ue)},[t,D,X]),h.useEffect(()=>{if(!(!t||!B.current)){if(N.current){N.current=!1;return}v4e(M,t)}},[M,t]),h.useEffect(()=>{(async()=>{try{const ue=await fetch("/api/tokens");if(ue.ok){const be=await ue.json();g(be),be.framework&&Ii.info(`Loaded ${be.framework} design tokens`)}}catch(ue){Ii.error("Failed to fetch design tokens:",ue)}})()},[g]);const te=()=>{C==="edit"||O||(Z(null),V(null),U(null),K(!1),_w())};h.useEffect(()=>{r&&(x("view"),_w(),m(null),b(null),document.body.style.cursor="auto")},[r,x,b,m]);const ie=h.useMemo(()=>[{key:"Escape",allowInTextField:!0,handler:J=>{const ue=J.target,be=ue.tagName.toLowerCase();if(!((be==="input"||be==="textarea"||be==="select"||ue.getAttribute("contenteditable")==="true")&&C!=="comment")){if(ue.closest("[data-radix-popper-content-wrapper]")){Ii.debug("Escape key pressed inside popover - letting Radix handle it");return}if(O){Ii.debug("Escape key pressed with dirty draft comment - blocking close"),F(_e=>_e+1);return}if(R){Ii.debug("Escape key pressed in variants mode - hiding panel"),P(!1),A(!1);return}Ii.debug("Escape key pressed - switching to view mode"),x("view"),_w(),m(null),b(null)}},description:"Close inspector"},{key:"c",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("C key pressed - switching to comment mode"),x("comment")},description:"Switch to comment mode"},{key:"d",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("D key pressed - switching to design mode"),x("edit")},description:"Switch to design mode"},{key:"v",metaKey:!1,ctrlKey:!1,handler:()=>{R||(Ii.debug("V key pressed - opening variants panel"),P(!0),A(!0),x("view"),St.capture("variants_panel.opened",{source:"keyboard_shortcut",hasActiveSession:I.active}))},description:"Open variants panel"},{key:"p",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("P key pressed - toggling panel"),E?A(!1):(A(!0),C==="view"&&!R&&x("comment"))},description:"Toggle panel"}],[C,O,x,F,R,P,E,A,I]);K3({shortcuts:ie}),h.useEffect(()=>{const J=()=>{CN("window_resize")};return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),h.useEffect(()=>{const J=(p==null?void 0:p.xpath)??null,ue=H.current;J&&J!==ue&&(H.current=J)},[p==null?void 0:p.xpath]);const Y=Array.from(M.values()).some(J=>J.status==="pending");return h.useEffect(()=>{if(Y){A(!0);return}C==="view"&&!R&&A(!1)},[C,A,R,Y]),y.jsxs(mn.div,{className:"relative flex h-screen overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[G!==null?y.jsx("div",{className:"absolute inset-0 z-50",children:y.jsx(Y6e,{message:G})}):null,r&&!j?y.jsx("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/45 backdrop-blur-[2px]",children:y.jsx(SB,{isSigningIn:s,onStartSignIn:()=>{i==null||i()},errorMessage:o,displayMode:"modal"})}):null,y.jsxs("div",{className:`relative flex min-w-0 flex-1 flex-col ${r?"pointer-events-none select-none":""}`,children:[y.jsx(U6e,{holdHostedTryoutPreviewNavigation:l,isInteractionDisabled:r,activeDemoSessionId:n}),l&&u?y.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-main",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main-light p-6 shadow-lg",children:y.jsx(Mk,{message:u})})}):null]}),r?null:y.jsxs(y.Fragment,{children:[f?null:y.jsxs(y.Fragment,{children:[y.jsx(mn.div,{className:"h-full flex-shrink-0",animate:{width:E?"auto":0,opacity:E?1:0},transition:{ease:[.19,1,.22,1],duration:.45},style:{overflow:"hidden",willChange:"width"},onClickCapture:te,children:y.jsx(kxe,{chatMessages:k,setChatMessages:w,onClose:()=>A(!1)})}),y.jsx(Fi,{children:!E&&y.jsx(Ts,{label:"Open chat",side:"left",children:y.jsx(mn.button,{initial:{opacity:0,x:8},animate:{opacity:1,x:0},exit:{opacity:0,x:8},transition:{duration:.15},onClick:()=>A(!0),className:"absolute right-0 top-4 z-50 rounded-l-lg border border-r-0 border-primary/30 bg-main p-2 text-content shadow-lg transition-colors","data-cy":"reopen-panel",children:y.jsx(mp,{className:"h-4 w-4",weight:"bold"})})})})]}),y.jsxs("button",{onClick:()=>L(!0),title:"Support and feedback",className:"absolute bottom-4 left-4 z-50 inline-flex items-center gap-1.5 rounded-md border border-primary/30 bg-main px-3 py-2 text-xs font-medium text-content transition-colors hover:bg-main-hover",children:[y.jsx(s3,{className:"h-3.5 w-3.5",weight:"bold"}),y.jsx("span",{children:"Support"})]}),y.jsx(K6e,{isOpen:T,onClose:()=>L(!1),contactEmail:e})]}),y.jsx(cD,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},q8e=()=>{const[e,t]=h.useState(window.location.hash),[n,r]=h.useState(0),{config:i,refetchConfig:s,loading:o,error:a}=J6e(),l=Ge(Dc),[u,f]=h.useState(!1),[p,m]=h.useState(null),[g,b]=h.useState(!1),[x,k]=h.useState(!1),[w,C]=h.useState(null),[E,A]=h.useState(!1),R=h.useRef(!1),P=h.useRef(!1),I=H8e(window.location.pathname),T=(i==null?void 0:i.activeDemoSessionId)??null,L=I??w??T,M=h.useMemo(()=>j8e(i==null?void 0:i.demoMode,i==null?void 0:i.agentModeAvailable,L),[i==null?void 0:i.demoMode,i==null?void 0:i.agentModeAvailable,L]),D=h.useMemo(()=>L8e({configLoading:o,hasConfig:i!==null,demoMode:i==null?void 0:i.demoMode,agentModeAvailable:i==null?void 0:i.agentModeAvailable,pathnameDemoSessionId:I,activeDemoSessionId:w,configuredDemoSessionId:T}),[i,o,I,w,T]);h.useLayoutEffect(()=>{if(!D){A(!1);return}A(!0)},[D]);const O=E,F=h.useMemo(()=>F8e(O),[O]),Z=(i==null?void 0:i.demoMode)===!0&&O,V=h.useRef(null);V.current=L;const U=h.useCallback(async()=>{if(!R.current)return;C(null);const X=await s();if((X==null?void 0:X.demoMode)===!0&&X.agentModeAvailable!==!0){k(!1);return}(X==null?void 0:X.demoMode)===!0&&k(!0)},[s]);h.useEffect(()=>{if((i==null?void 0:i.demoMode)===!0)return M8e(()=>{U()})},[i==null?void 0:i.demoMode,U]),h.useEffect(()=>{if(R.current=(i==null?void 0:i.demoMode)===!0,(i==null?void 0:i.demoMode)!==!0)return;const X=window.fetch.bind(window);return N8e({nativeFetch:X,pageOrigin:window.location.origin,getShouldIntercept:()=>R.current})},[i==null?void 0:i.demoMode]),h.useEffect(()=>{(i==null?void 0:i.agentModeAvailable)===!0&&k(!1)},[i==null?void 0:i.agentModeAvailable]);const K=h.useCallback(async X=>{const te=V.current;if(!(X!=null&&X.forceRefresh)&&te)return te;if(P.current)return"";P.current=!0;try{const ie=await fetch("/api/demo/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!ie.ok){const J=await W8e(ie);throw new Error(J)}const Y=await ie.json();if(!Y.sessionId)throw new Error("Demo session response missing session id.");return C(Y.sessionId),Y.sessionId}finally{P.current=!1}},[]);h.useEffect(()=>{T&&C(T)},[T]),h.useEffect(()=>{i!=null&&i.userId?(St.identify(i.userId,{...i.email?{email:i.email}:{}}),i.email&&St.alias(i.email,i.userId)):i!=null&&i.email&&St.identify(i.email,{email:i.email})},[i==null?void 0:i.userId,i==null?void 0:i.email]),h.useEffect(()=>{if(!i)return;const X=!!i.demoMode,te=X?L:null;St.register({source:X?"tryout":"core",demo_mode:X,...te?{demo_session_id:te}:{}})},[i,L]);const W=h.useCallback(async()=>{var te;f(!0),m(null);let X=null;try{if(X=window.open("","_blank"),!X)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{X.document.open(),X.document.write(U8e),X.document.close()}catch(J){Ii.warn("Failed to render loading state in auth popup:",J)}const ie=await fetch(`${D8}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"desktop"})}),Y=await ie.json();if(!ie.ok||!Y.success||!Y.authUrl||!Y.sessionId||!Y.pollSecret)throw new Error(Y.error||Y.message||"Failed to start Google login");if(X.closed)throw new Error("Sign-in window was closed before Google login started.");X.location.href=Y.authUrl;for(let J=0;J<z8e;J+=1){if(X.closed)throw new Error("Sign-in window was closed before authentication completed.");const be=await(await fetch(`${D8}/api/auth/google/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:Y.sessionId,pollSecret:Y.pollSecret})})).json();if(be.success&&be.token&&((te=be.user)!=null&&te.email)){if(!(await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:be.user.email,token:be.token,refreshToken:be.refreshToken,userId:be.user.id})})).ok)throw new Error("Signed in, but failed to store session locally.");if(X.close(),(i==null?void 0:i.demoMode)===!0){await K({forceRefresh:!0}),window.location.reload();return}window.location.reload();return}if(be.error&&be.error!=="Pending")throw new Error(be.error||"Google login failed");await new Promise(Me=>setTimeout(Me,B8e))}throw new Error("Authentication timed out. Please try again.")}catch(ie){X&&!X.closed&&X.close();const Y=ie instanceof Error?ie.message:"Failed to start login flow";Ii.warn("Hosted login failed:",Y),m(Y),f(!1)}},[i==null?void 0:i.demoMode,K]),G=(i==null?void 0:i.demoMode)===!0&&((i==null?void 0:i.agentModeAvailable)!==!0||x||u),j=i!=null&&i.demoMode!==!0&&i.agentModeAvailable!==!0,H=h.useCallback(async()=>{b(!0);try{await s()}finally{b(!1)}},[s]);if(h.useEffect(()=>{if(!D)return;let X=!1;return K({forceRefresh:!0}).catch(te=>{const ie=te instanceof Error?te.message:UB;Ii.warn("Hosted session bootstrap failed:",ie),m(ie),Nt.error(ie)}).finally(()=>{X||A(!1)}),()=>{X=!0}},[D,K]),h.useEffect(()=>{const X=()=>{const te=window.location.hash;l(!1),t(ie=>(ie.startsWith("#tokens")&&!te.startsWith("#tokens")&&r(Y=>Y+1),te))};return window.addEventListener("hashchange",X),()=>window.removeEventListener("hashchange",X)},[l]),e.startsWith("#tokens"))return y.jsx(T8e,{});const B={pathname:window.location.pathname,configLoading:o,hasConfig:i!==null,isRetryingConfig:g},N=O8e(B),q=V8e(B);if(N)return y.jsx("div",{className:"flex h-screen items-center justify-center bg-main",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:y.jsx(Mk,{message:"Loading..."})})});if(q){const X=a||"Could not load Rivet configuration.";return y.jsx("div",{className:"flex h-screen items-center justify-center bg-main px-6",children:y.jsxs("div",{className:"w-full max-w-md rounded-lg border border-divider bg-main p-6 text-center shadow-lg",children:[y.jsx("p",{className:"text-sm font-medium text-content",children:"We could not start Rivet yet."}),y.jsx("p",{className:"text-content-dim mt-2 text-xs",children:X}),y.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{H()},children:"Retry"})]})})}return j?y.jsx(SB,{isSigningIn:u,onStartSignIn:()=>{W()},errorMessage:p,displayMode:"full"}):y.jsx(G8e,{contactEmail:i==null?void 0:i.email,projectPath:i==null?void 0:i.projectPath,activeDemoSessionId:M,showLoginGate:G,onStartLogin:W,isStartingLogin:u,loginError:p,fullPageHostedLoginProgressMessage:(i==null?void 0:i.demoMode)===!0&&u?"Completing sign-in...":null,holdHostedTryoutPreviewNavigation:O,hostedTryoutPreviewHoldMessage:F,deferInspectorUntilPreviewReady:Z},n)},K8e="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",Y8e=new tZ,X8e=()=>y.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:y.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})});LG.createRoot(document.getElementById("root")).render(y.jsx(xe.StrictMode,{children:y.jsx(SG,{apiKey:K8e,options:{api_host:"https://us.i.posthog.com",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",session_recording:{maskAllInputs:!1,maskInputOptions:{password:!0},maskTextSelector:null},mask_all_text:!1,mask_all_element_attributes:!1,loaded:e=>{e.register({source:"core",rivet_version:"0.10.2",env:"production"})}},children:y.jsx(IG,{fallback:y.jsx(X8e,{}),children:y.jsx(rZ,{client:Y8e,children:y.jsx(Lve,{defaultShape:"rounded",children:y.jsx($ve,{defaultLibrary:"lucide",children:y.jsx(q8e,{})})})})})})}));
|
|
645
|
+
</html>`,Z8e="Too many people are trying Rivet right now. Please try again in a few minutes.",UB="Failed to start an isolated demo session.",W8e=async e=>{if(e.status===429)return Z8e;try{const t=await e.json();if(t.error)return t.error;if(t.message)return t.message}catch{}return UB},G8e=({contactEmail:e,projectPath:t,activeDemoSessionId:n=null,showLoginGate:r=!1,onStartLogin:i,isStartingLogin:s=!1,loginError:o=null,fullPageHostedLoginProgressMessage:a=null,holdHostedTryoutPreviewNavigation:l=!1,hostedTryoutPreviewHoldMessage:u=null,deferInspectorUntilPreviewReady:f=!1})=>{const[p,m]=zn(os),g=Ge(sf),b=Ge(F3),x=Ge(j3),[k,w]=zn(ote),C=Ee(yo),[E,A]=zn(Qp),[R,P]=zn($c),I=Ee(Fs),[T,L]=h.useState(!1),[M,D]=zn($r),O=Ee(Dc),F=Ge(ED),Z=Ge(P1),V=Ge(O3),U=Ge(Mc),K=Ge(Dc),W=i8e();s8e();const G=W.isProcessing?"Completing authentication...":a,j=G!==null,H=h.useRef((p==null?void 0:p.xpath)??null),B=h.useRef(!1),N=h.useRef(!1),q=Ge(Mv),X=Pk();h.useEffect(()=>{q(t??null)},[t,q]),h.useEffect(()=>{if(!t||B.current)return;B.current=!0;const J=y4e(t);J.size>0&&(N.current=!0,D(J));const ue=g4e(t);ue&&X(ue)},[t,D,X]),h.useEffect(()=>{if(!(!t||!B.current)){if(N.current){N.current=!1;return}v4e(M,t)}},[M,t]),h.useEffect(()=>{(async()=>{try{const ue=await fetch("/api/tokens");if(ue.ok){const be=await ue.json();g(be),be.framework&&Ii.info(`Loaded ${be.framework} design tokens`)}}catch(ue){Ii.error("Failed to fetch design tokens:",ue)}})()},[g]);const te=()=>{C==="edit"||O||(Z(null),V(null),U(null),K(!1),_w())};h.useEffect(()=>{r&&(x("view"),_w(),m(null),b(null),document.body.style.cursor="auto")},[r,x,b,m]);const ie=h.useMemo(()=>[{key:"Escape",allowInTextField:!0,handler:J=>{const ue=J.target,be=ue.tagName.toLowerCase();if(!((be==="input"||be==="textarea"||be==="select"||ue.getAttribute("contenteditable")==="true")&&C!=="comment")){if(ue.closest("[data-radix-popper-content-wrapper]")){Ii.debug("Escape key pressed inside popover - letting Radix handle it");return}if(O){Ii.debug("Escape key pressed with dirty draft comment - blocking close"),F(_e=>_e+1);return}if(R){Ii.debug("Escape key pressed in variants mode - hiding panel"),P(!1),A(!1);return}Ii.debug("Escape key pressed - switching to view mode"),x("view"),_w(),m(null),b(null)}},description:"Close inspector"},{key:"c",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("C key pressed - switching to comment mode"),x("comment")},description:"Switch to comment mode"},{key:"d",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("D key pressed - switching to design mode"),x("edit")},description:"Switch to design mode"},{key:"v",metaKey:!1,ctrlKey:!1,handler:()=>{R||(Ii.debug("V key pressed - opening variants panel"),P(!0),A(!0),x("view"),St.capture("variants_panel.opened",{source:"keyboard_shortcut",hasActiveSession:I.active}))},description:"Open variants panel"},{key:"p",metaKey:!1,ctrlKey:!1,handler:()=>{Ii.debug("P key pressed - toggling panel"),E?A(!1):(A(!0),C==="view"&&!R&&x("comment"))},description:"Toggle panel"}],[C,O,x,F,R,P,E,A,I]);K3({shortcuts:ie}),h.useEffect(()=>{const J=()=>{CN("window_resize")};return window.addEventListener("resize",J),()=>window.removeEventListener("resize",J)},[]),h.useEffect(()=>{const J=(p==null?void 0:p.xpath)??null,ue=H.current;J&&J!==ue&&(H.current=J)},[p==null?void 0:p.xpath]);const Y=Array.from(M.values()).some(J=>J.status==="pending");return h.useEffect(()=>{if(Y){A(!0);return}C==="view"&&!R&&A(!1)},[C,A,R,Y]),y.jsxs(mn.div,{className:"relative flex h-screen overflow-hidden",initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,ease:"easeOut"},"data-cy":"rivet-app",children:[G!==null?y.jsx("div",{className:"absolute inset-0 z-50",children:y.jsx(Y6e,{message:G})}):null,r&&!j?y.jsx("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/45 backdrop-blur-[2px]",children:y.jsx(SB,{isSigningIn:s,onStartSignIn:()=>{i==null||i()},errorMessage:o,displayMode:"modal"})}):null,y.jsxs("div",{className:`relative flex min-w-0 flex-1 flex-col ${r?"pointer-events-none select-none":""}`,children:[y.jsx(U6e,{holdHostedTryoutPreviewNavigation:l,isInteractionDisabled:r,activeDemoSessionId:n}),l&&u?y.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-main",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main-light p-6 shadow-lg",children:y.jsx(Mk,{message:u})})}):null]}),r?null:y.jsxs(y.Fragment,{children:[f?null:y.jsxs(y.Fragment,{children:[y.jsx(mn.div,{className:"h-full flex-shrink-0",animate:{width:E?"auto":0,opacity:E?1:0},transition:{ease:[.19,1,.22,1],duration:.45},style:{overflow:"hidden",willChange:"width"},onClickCapture:te,children:y.jsx(kxe,{chatMessages:k,setChatMessages:w,onClose:()=>A(!1)})}),y.jsx(Fi,{children:!E&&y.jsx(Ts,{label:"Open chat",side:"left",children:y.jsx(mn.button,{initial:{opacity:0,x:8},animate:{opacity:1,x:0},exit:{opacity:0,x:8},transition:{duration:.15},onClick:()=>A(!0),className:"absolute right-0 top-4 z-50 rounded-l-lg border border-r-0 border-primary/30 bg-main p-2 text-content shadow-lg transition-colors","data-cy":"reopen-panel",children:y.jsx(mp,{className:"h-4 w-4",weight:"bold"})})})})]}),y.jsxs("button",{onClick:()=>L(!0),title:"Support and feedback",className:"absolute bottom-4 left-4 z-50 inline-flex items-center gap-1.5 rounded-md border border-primary/30 bg-main px-3 py-2 text-xs font-medium text-content transition-colors hover:bg-main-hover",children:[y.jsx(s3,{className:"h-3.5 w-3.5",weight:"bold"}),y.jsx("span",{children:"Support"})]}),y.jsx(K6e,{isOpen:T,onClose:()=>L(!1),contactEmail:e})]}),y.jsx(cD,{duration:5e3,richColors:!0,toastOptions:{style:{maxHeight:"150px",overflow:"hidden"}}})]})},q8e=()=>{const[e,t]=h.useState(window.location.hash),[n,r]=h.useState(0),{config:i,refetchConfig:s,loading:o,error:a}=J6e(),l=Ge(Dc),[u,f]=h.useState(!1),[p,m]=h.useState(null),[g,b]=h.useState(!1),[x,k]=h.useState(!1),[w,C]=h.useState(null),[E,A]=h.useState(!1),R=h.useRef(!1),P=h.useRef(!1),I=H8e(window.location.pathname),T=(i==null?void 0:i.activeDemoSessionId)??null,L=I??w??T,M=h.useMemo(()=>j8e(i==null?void 0:i.demoMode,i==null?void 0:i.agentModeAvailable,L),[i==null?void 0:i.demoMode,i==null?void 0:i.agentModeAvailable,L]),D=h.useMemo(()=>L8e({configLoading:o,hasConfig:i!==null,demoMode:i==null?void 0:i.demoMode,agentModeAvailable:i==null?void 0:i.agentModeAvailable,pathnameDemoSessionId:I,activeDemoSessionId:w,configuredDemoSessionId:T}),[i,o,I,w,T]);h.useLayoutEffect(()=>{if(!D){A(!1);return}A(!0)},[D]);const O=E,F=h.useMemo(()=>F8e(O),[O]),Z=(i==null?void 0:i.demoMode)===!0&&O,V=h.useRef(null);V.current=L;const U=h.useCallback(async()=>{if(!R.current)return;C(null);const X=await s();if((X==null?void 0:X.demoMode)===!0&&X.agentModeAvailable!==!0){k(!1);return}(X==null?void 0:X.demoMode)===!0&&k(!0)},[s]);h.useEffect(()=>{if((i==null?void 0:i.demoMode)===!0)return M8e(()=>{U()})},[i==null?void 0:i.demoMode,U]),h.useEffect(()=>{if(R.current=(i==null?void 0:i.demoMode)===!0,(i==null?void 0:i.demoMode)!==!0)return;const X=window.fetch.bind(window);return N8e({nativeFetch:X,pageOrigin:window.location.origin,getShouldIntercept:()=>R.current})},[i==null?void 0:i.demoMode]),h.useEffect(()=>{(i==null?void 0:i.agentModeAvailable)===!0&&k(!1)},[i==null?void 0:i.agentModeAvailable]);const K=h.useCallback(async X=>{const te=V.current;if(!(X!=null&&X.forceRefresh)&&te)return te;if(P.current)return"";P.current=!0;try{const ie=await fetch("/api/demo/session",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!ie.ok){const J=await W8e(ie);throw new Error(J)}const Y=await ie.json();if(!Y.sessionId)throw new Error("Demo session response missing session id.");return C(Y.sessionId),Y.sessionId}finally{P.current=!1}},[]);h.useEffect(()=>{T&&C(T)},[T]),h.useEffect(()=>{i!=null&&i.userId?(St.identify(i.userId,{...i.email?{email:i.email}:{}}),i.email&&St.alias(i.email,i.userId)):i!=null&&i.email&&St.identify(i.email,{email:i.email})},[i==null?void 0:i.userId,i==null?void 0:i.email]),h.useEffect(()=>{if(!i)return;const X=!!i.demoMode,te=X?L:null;St.register({source:X?"tryout":"core",demo_mode:X,...te?{demo_session_id:te}:{}})},[i,L]);const W=h.useCallback(async()=>{var te;f(!0),m(null);let X=null;try{if(X=window.open("","_blank"),!X)throw new Error("Pop-up blocked. Please allow pop-ups and try again.");try{X.document.open(),X.document.write(U8e),X.document.close()}catch(J){Ii.warn("Failed to render loading state in auth popup:",J)}const ie=await fetch(`${D8}/api/auth/google/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:"desktop"})}),Y=await ie.json();if(!ie.ok||!Y.success||!Y.authUrl||!Y.sessionId||!Y.pollSecret)throw new Error(Y.error||Y.message||"Failed to start Google login");if(X.closed)throw new Error("Sign-in window was closed before Google login started.");X.location.href=Y.authUrl;for(let J=0;J<z8e;J+=1){if(X.closed)throw new Error("Sign-in window was closed before authentication completed.");const be=await(await fetch(`${D8}/api/auth/google/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session:Y.sessionId,pollSecret:Y.pollSecret})})).json();if(be.success&&be.token&&((te=be.user)!=null&&te.email)){if(!(await fetch("/api/auth/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:be.user.email,token:be.token,refreshToken:be.refreshToken,userId:be.user.id})})).ok)throw new Error("Signed in, but failed to store session locally.");if(X.close(),(i==null?void 0:i.demoMode)===!0){await K({forceRefresh:!0}),window.location.reload();return}window.location.reload();return}if(be.error&&be.error!=="Pending")throw new Error(be.error||"Google login failed");await new Promise(Me=>setTimeout(Me,B8e))}throw new Error("Authentication timed out. Please try again.")}catch(ie){X&&!X.closed&&X.close();const Y=ie instanceof Error?ie.message:"Failed to start login flow";Ii.warn("Hosted login failed:",Y),m(Y),f(!1)}},[i==null?void 0:i.demoMode,K]),G=(i==null?void 0:i.demoMode)===!0&&((i==null?void 0:i.agentModeAvailable)!==!0||x||u),j=i!=null&&i.demoMode!==!0&&i.agentModeAvailable!==!0,H=h.useCallback(async()=>{b(!0);try{await s()}finally{b(!1)}},[s]);if(h.useEffect(()=>{if(!D)return;let X=!1;return K({forceRefresh:!0}).catch(te=>{const ie=te instanceof Error?te.message:UB;Ii.warn("Hosted session bootstrap failed:",ie),m(ie),Nt.error(ie)}).finally(()=>{X||A(!1)}),()=>{X=!0}},[D,K]),h.useEffect(()=>{const X=()=>{const te=window.location.hash;l(!1),t(ie=>(ie.startsWith("#tokens")&&!te.startsWith("#tokens")&&r(Y=>Y+1),te))};return window.addEventListener("hashchange",X),()=>window.removeEventListener("hashchange",X)},[l]),e.startsWith("#tokens"))return y.jsx(T8e,{});const B={pathname:window.location.pathname,configLoading:o,hasConfig:i!==null,isRetryingConfig:g},N=O8e(B),q=V8e(B);if(N)return y.jsx("div",{className:"flex h-screen items-center justify-center bg-main",children:y.jsx("div",{className:"rounded-lg border border-divider bg-main p-6 shadow-lg",children:y.jsx(Mk,{message:"Loading..."})})});if(q){const X=a||"Could not load Rivet configuration.";return y.jsx("div",{className:"flex h-screen items-center justify-center bg-main px-6",children:y.jsxs("div",{className:"w-full max-w-md rounded-lg border border-divider bg-main p-6 text-center shadow-lg",children:[y.jsx("p",{className:"text-sm font-medium text-content",children:"We could not start Rivet yet."}),y.jsx("p",{className:"text-content-dim mt-2 text-xs",children:X}),y.jsx("button",{type:"button",className:"mt-4 rounded-md border border-divider px-3 py-1.5 text-xs text-content hover:bg-main/80",onClick:()=>{H()},children:"Retry"})]})})}return j?y.jsx(SB,{isSigningIn:u,onStartSignIn:()=>{W()},errorMessage:p,displayMode:"full"}):y.jsx(G8e,{contactEmail:i==null?void 0:i.email,projectPath:i==null?void 0:i.projectPath,activeDemoSessionId:M,showLoginGate:G,onStartLogin:W,isStartingLogin:u,loginError:p,fullPageHostedLoginProgressMessage:(i==null?void 0:i.demoMode)===!0&&u?"Completing sign-in...":null,holdHostedTryoutPreviewNavigation:O,hostedTryoutPreviewHoldMessage:F,deferInspectorUntilPreviewReady:Z},n)},K8e="phc_Ntj9tXHbS64XgYxlTfhglRmFivFsfm0AERph4ZlnNH",Y8e=new tZ,X8e=()=>y.jsx("div",{style:{display:"flex",height:"100vh",alignItems:"center",justifyContent:"center"},children:y.jsx("p",{style:{fontSize:"14px",color:"#6b7280"},children:"Something went wrong. Please reload the page."})});LG.createRoot(document.getElementById("root")).render(y.jsx(xe.StrictMode,{children:y.jsx(SG,{apiKey:K8e,options:{api_host:"https://us.i.posthog.com",ui_host:"https://us.posthog.com",person_profiles:"always",capture_exceptions:!0,autocapture:!0,capture_pageview:!0,capture_performance:!0,persistence:"localStorage",session_recording:{maskAllInputs:!1,maskInputOptions:{password:!0},maskTextSelector:null},mask_all_text:!1,mask_all_element_attributes:!1,loaded:e=>{e.register({source:"core",rivet_version:"0.10.3",env:"production"})}},children:y.jsx(IG,{fallback:y.jsx(X8e,{}),children:y.jsx(rZ,{client:Y8e,children:y.jsx(Lve,{defaultShape:"rounded",children:y.jsx($ve,{defaultLibrary:"lucide",children:y.jsx(q8e,{})})})})})})}));
|