@mcpjam/inspector 1.0.14 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"824679d9cb3b6dc5faf362b650bf5365bb047917"}}catch{}})();try{(function(){var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="3362de6d-b023-4f29-8ee6-f66ef70b17ce",t._sentryDebugIdIdentifier="sentry-dbid-3362de6d-b023-4f29-8ee6-f66ef70b17ce")})()}catch{}function aX(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in t)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function Gf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pS={exports:{}},dp={};/**
1
+ (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};t.SENTRY_RELEASE={id:"ce36fef795dafd3e492393926d87e2e282e4f3ee"}}catch{}})();try{(function(){var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="7881c128-808c-4e39-818c-15993df247eb",t._sentryDebugIdIdentifier="sentry-dbid-7881c128-808c-4e39-818c-15993df247eb")})()}catch{}function aX(t,e){for(var n=0;n<e.length;n++){const r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in t)){const i=Object.getOwnPropertyDescriptor(r,s);i&&Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function Gf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var pS={exports:{}},dp={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.js
4
4
  *
@@ -439,7 +439,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/alert-
439
439
  *
440
440
  * This source code is licensed under the ISC license.
441
441
  * See the LICENSE file in the root directory of this source tree.
442
- */const zie=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],uc=Ze("x",zie);function Fie(t){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",e.appendChild(n),n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t))}const Uie=t=>{switch(t){case"success":return Vie;case"info":return Gie;case"warning":return Hie;case"error":return Wie;default:return null}},Bie=Array(12).fill(0),qie=({visible:t,className:e})=>Ee.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Ee.createElement("div",{className:"sonner-spinner"},Bie.map((n,r)=>Ee.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Vie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Hie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Gie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Wie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Yie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Ee.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Ee.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Kie=()=>{const[t,e]=Ee.useState(document.hidden);return Ee.useEffect(()=>{const n=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t};let Nk=1;class Xie{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{const n=this.subscribers.indexOf(e);this.subscribers.splice(n,1)}),this.publish=e=>{this.subscribers.forEach(n=>n(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var n;const{message:r,...s}=e,i=typeof e?.id=="number"||((n=e.id)==null?void 0:n.length)>0?e.id:Nk++,a=this.toasts.find(u=>u.id===i),l=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),a?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...e,id:i,title:r}),{...u,...e,id:i,dismissible:l,title:r}):u):this.addToast({title:r,...s,dismissible:l,id:i}),i},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:e,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),e),this.message=(e,n)=>this.create({...n,message:e}),this.error=(e,n)=>this.create({...n,message:e,type:"error"}),this.success=(e,n)=>this.create({...n,type:"success",message:e}),this.info=(e,n)=>this.create({...n,type:"info",message:e}),this.warning=(e,n)=>this.create({...n,type:"warning",message:e}),this.loading=(e,n)=>this.create({...n,type:"loading",message:e}),this.promise=(e,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:e,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const s=Promise.resolve(e instanceof Function?e():e);let i=r!==void 0,a;const l=s.then(async d=>{if(a=["resolve",d],Ee.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Jie(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"success",description:g,...x})}}).catch(async d=>{if(a=["reject",d],n.error!==void 0){i=!1;const p=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof p=="object"&&!Ee.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,p)=>l.then(()=>a[0]==="reject"?p(a[1]):d(a[1])).catch(p));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(e,n)=>{const r=n?.id||Nk++;return this.create({jsx:e(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Rs=new Xie,Qie=(t,e)=>{const n=e?.id||Nk++;return Rs.addToast({title:t,...e,id:n}),n},Jie=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",Zie=Qie,eae=()=>Rs.toasts,tae=()=>Rs.getActiveToasts(),It=Object.assign(Zie,{success:Rs.success,info:Rs.info,warning:Rs.warning,error:Rs.error,custom:Rs.custom,message:Rs.message,promise:Rs.promise,dismiss:Rs.dismiss,loading:Rs.loading},{getHistory:eae,getToasts:tae});Fie("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function ty(t){return t.label!==void 0}const nae=3,rae="24px",sae="16px",pI=4e3,iae=356,aae=14,oae=45,lae=200;function wa(...t){return t.filter(Boolean).join(" ")}function cae(t){const[e,n]=t.split("-"),r=[];return e&&r.push(e),n&&r.push(n),r}const uae=t=>{var e,n,r,s,i,a,l,u,d;const{invert:p,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:b,heights:E,index:S,toasts:k,expanded:T,removeToast:R,defaultRichColors:j,closeButton:A,style:N,cancelButtonStyle:M,actionButtonStyle:I,className:O="",descriptionClassName:L="",duration:z,position:H,gap:V,expandByDefault:X,classNames:F,icons:W,closeButtonAriaLabel:G="Close toast"}=t,[ee,P]=Ee.useState(null),[ie,ue]=Ee.useState(null),[D,ne]=Ee.useState(!1),[fe,q]=Ee.useState(!1),[K,Y]=Ee.useState(!1),[Z,U]=Ee.useState(!1),[J,oe]=Ee.useState(!1),[pe,ye]=Ee.useState(0),[je,Ne]=Ee.useState(0),Ae=Ee.useRef(h.duration||z||pI),He=Ee.useRef(null),lt=Ee.useRef(null),Fe=S===0,ct=S+1<=b,Ie=h.type,et=h.dismissible!==!1,ot=h.className||"",dr=h.descriptionClassName||"",be=Ee.useMemo(()=>E.findIndex(pt=>pt.toastId===h.id)||0,[E,h.id]),Te=Ee.useMemo(()=>{var pt;return(pt=h.closeButton)!=null?pt:A},[h.closeButton,A]),st=Ee.useMemo(()=>h.duration||z||pI,[h.duration,z]),We=Ee.useRef(0),Tt=Ee.useRef(0),er=Ee.useRef(0),tr=Ee.useRef(null),[jn,Le]=H.split("-"),ht=Ee.useMemo(()=>E.reduce((pt,Fn,Un)=>Un>=be?pt:pt+Fn.height,0),[E,be]),Lt=Kie(),gt=h.invert||p,wn=Ie==="loading";Tt.current=Ee.useMemo(()=>be*V+ht,[be,ht]),Ee.useEffect(()=>{Ae.current=st},[st]),Ee.useEffect(()=>{ne(!0)},[]),Ee.useEffect(()=>{const pt=lt.current;if(pt){const Fn=pt.getBoundingClientRect().height;return Ne(Fn),x(Un=>[{toastId:h.id,height:Fn,position:h.position},...Un]),()=>x(Un=>Un.filter(_r=>_r.toastId!==h.id))}},[x,h.id]),Ee.useLayoutEffect(()=>{if(!D)return;const pt=lt.current,Fn=pt.style.height;pt.style.height="auto";const Un=pt.getBoundingClientRect().height;pt.style.height=Fn,Ne(Un),x(_r=>_r.find(Gn=>Gn.toastId===h.id)?_r.map(Gn=>Gn.toastId===h.id?{...Gn,height:Un}:Gn):[{toastId:h.id,height:Un,position:h.position},..._r])},[D,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Zr=Ee.useCallback(()=>{q(!0),ye(Tt.current),x(pt=>pt.filter(Fn=>Fn.toastId!==h.id)),setTimeout(()=>{R(h)},lae)},[h,R,x,Tt]);Ee.useEffect(()=>{if(h.promise&&Ie==="loading"||h.duration===1/0||h.type==="loading")return;let pt;return T||v||Lt?(()=>{if(er.current<We.current){const _r=new Date().getTime()-We.current;Ae.current=Ae.current-_r}er.current=new Date().getTime()})():(()=>{Ae.current!==1/0&&(We.current=new Date().getTime(),pt=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Zr()},Ae.current))})(),()=>clearTimeout(pt)},[T,v,h,Ie,Lt,Zr]),Ee.useEffect(()=>{h.delete&&(Zr(),h.onDismiss==null||h.onDismiss.call(h,h))},[Zr,h.delete]);function ui(){var pt;if(W?.loading){var Fn;return Ee.createElement("div",{className:wa(F?.loader,h==null||(Fn=h.classNames)==null?void 0:Fn.loader,"sonner-loader"),"data-visible":Ie==="loading"},W.loading)}return Ee.createElement(qie,{className:wa(F?.loader,h==null||(pt=h.classNames)==null?void 0:pt.loader),visible:Ie==="loading"})}const eo=h.icon||W?.[Ie]||Uie(Ie);var ma,zu;return Ee.createElement("li",{tabIndex:0,ref:lt,className:wa(O,ot,F?.toast,h==null||(e=h.classNames)==null?void 0:e.toast,F?.default,F?.[Ie],h==null||(n=h.classNames)==null?void 0:n[Ie]),"data-sonner-toast":"","data-rich-colors":(ma=h.richColors)!=null?ma:j,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":D,"data-promise":!!h.promise,"data-swiped":J,"data-removed":fe,"data-visible":ct,"data-y-position":jn,"data-x-position":Le,"data-index":S,"data-front":Fe,"data-swiping":K,"data-dismissible":et,"data-type":Ie,"data-invert":gt,"data-swipe-out":Z,"data-swipe-direction":ie,"data-expanded":!!(T||X&&D),"data-testid":h.testId,style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${fe?pe:Tt.current}px`,"--initial-height":X?"auto":`${je}px`,...N,...h.style},onDragEnd:()=>{Y(!1),P(null),tr.current=null},onPointerDown:pt=>{pt.button!==2&&(wn||!et||(He.current=new Date,ye(Tt.current),pt.target.setPointerCapture(pt.pointerId),pt.target.tagName!=="BUTTON"&&(Y(!0),tr.current={x:pt.clientX,y:pt.clientY})))},onPointerUp:()=>{var pt,Fn,Un;if(Z||!et)return;tr.current=null;const _r=Number(((pt=lt.current)==null?void 0:pt.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Bi=Number(((Fn=lt.current)==null?void 0:Fn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Gn=new Date().getTime()-((Un=He.current)==null?void 0:Un.getTime()),Bn=ee==="x"?_r:Bi,Mn=Math.abs(Bn)/Gn;if(Math.abs(Bn)>=oae||Mn>.11){ye(Tt.current),h.onDismiss==null||h.onDismiss.call(h,h),ue(ee==="x"?_r>0?"right":"left":Bi>0?"down":"up"),Zr(),U(!0);return}else{var fn,nr;(fn=lt.current)==null||fn.style.setProperty("--swipe-amount-x","0px"),(nr=lt.current)==null||nr.style.setProperty("--swipe-amount-y","0px")}oe(!1),Y(!1),P(null)},onPointerMove:pt=>{var Fn,Un,_r;if(!tr.current||!et||((Fn=window.getSelection())==null?void 0:Fn.toString().length)>0)return;const Gn=pt.clientY-tr.current.y,Bn=pt.clientX-tr.current.x;var Mn;const fn=(Mn=t.swipeDirections)!=null?Mn:cae(H);!ee&&(Math.abs(Bn)>1||Math.abs(Gn)>1)&&P(Math.abs(Bn)>Math.abs(Gn)?"x":"y");let nr={x:0,y:0};const re=Q=>1/(1.5+Math.abs(Q)/20);if(ee==="y"){if(fn.includes("top")||fn.includes("bottom"))if(fn.includes("top")&&Gn<0||fn.includes("bottom")&&Gn>0)nr.y=Gn;else{const Q=Gn*re(Gn);nr.y=Math.abs(Q)<Math.abs(Gn)?Q:Gn}}else if(ee==="x"&&(fn.includes("left")||fn.includes("right")))if(fn.includes("left")&&Bn<0||fn.includes("right")&&Bn>0)nr.x=Bn;else{const Q=Bn*re(Bn);nr.x=Math.abs(Q)<Math.abs(Bn)?Q:Bn}(Math.abs(nr.x)>0||Math.abs(nr.y)>0)&&oe(!0),(Un=lt.current)==null||Un.style.setProperty("--swipe-amount-x",`${nr.x}px`),(_r=lt.current)==null||_r.style.setProperty("--swipe-amount-y",`${nr.y}px`)}},Te&&!h.jsx&&Ie!=="loading"?Ee.createElement("button",{"aria-label":G,"data-disabled":wn,"data-close-button":!0,onClick:wn||!et?()=>{}:()=>{Zr(),h.onDismiss==null||h.onDismiss.call(h,h)},className:wa(F?.closeButton,h==null||(r=h.classNames)==null?void 0:r.closeButton)},(zu=W?.close)!=null?zu:Yie):null,(Ie||h.icon||h.promise)&&h.icon!==null&&(W?.[Ie]!==null||h.icon)?Ee.createElement("div",{"data-icon":"",className:wa(F?.icon,h==null||(s=h.classNames)==null?void 0:s.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||ui():null,h.type!=="loading"?eo:null):null,Ee.createElement("div",{"data-content":"",className:wa(F?.content,h==null||(i=h.classNames)==null?void 0:i.content)},Ee.createElement("div",{"data-title":"",className:wa(F?.title,h==null||(a=h.classNames)==null?void 0:a.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?Ee.createElement("div",{"data-description":"",className:wa(L,dr,F?.description,h==null||(l=h.classNames)==null?void 0:l.description)},typeof h.description=="function"?h.description():h.description):null),Ee.isValidElement(h.cancel)?h.cancel:h.cancel&&ty(h.cancel)?Ee.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||M,onClick:pt=>{ty(h.cancel)&&et&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,pt),Zr())},className:wa(F?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,Ee.isValidElement(h.action)?h.action:h.action&&ty(h.action)?Ee.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||I,onClick:pt=>{ty(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,pt),!pt.defaultPrevented&&Zr())},className:wa(F?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function mI(){if(typeof window>"u"||typeof document>"u")return"ltr";const t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function dae(t,e){const n={};return[t,e].forEach((r,s)=>{const i=s===1,a=i?"--mobile-offset":"--offset",l=i?sae:rae;function u(d){["top","right","bottom","left"].forEach(p=>{n[`${a}-${p}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${a}-${d}`]=l:n[`${a}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):u(l)}),n}const fae=Ee.forwardRef(function(e,n){const{id:r,invert:s,position:i="bottom-right",hotkey:a=["altKey","KeyT"],expand:l,closeButton:u,className:d,offset:p,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:b,visibleToasts:E=nae,toastOptions:S,dir:k=mI(),gap:T=aae,icons:R,containerAriaLabel:j="Notifications"}=e,[A,N]=Ee.useState([]),M=Ee.useMemo(()=>r?A.filter(D=>D.toasterId===r):A.filter(D=>!D.toasterId),[A,r]),I=Ee.useMemo(()=>Array.from(new Set([i].concat(M.filter(D=>D.position).map(D=>D.position)))),[M,i]),[O,L]=Ee.useState([]),[z,H]=Ee.useState(!1),[V,X]=Ee.useState(!1),[F,W]=Ee.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=Ee.useRef(null),ee=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),P=Ee.useRef(null),ie=Ee.useRef(!1),ue=Ee.useCallback(D=>{N(ne=>{var fe;return(fe=ne.find(q=>q.id===D.id))!=null&&fe.delete||Rs.dismiss(D.id),ne.filter(({id:q})=>q!==D.id)})},[]);return Ee.useEffect(()=>Rs.subscribe(D=>{if(D.dismiss){requestAnimationFrame(()=>{N(ne=>ne.map(fe=>fe.id===D.id?{...fe,delete:!0}:fe))});return}setTimeout(()=>{Yz.flushSync(()=>{N(ne=>{const fe=ne.findIndex(q=>q.id===D.id);return fe!==-1?[...ne.slice(0,fe),{...ne[fe],...D},...ne.slice(fe+1)]:[D,...ne]})})})}),[A]),Ee.useEffect(()=>{if(g!=="system"){W(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?W("dark"):W("light")),typeof window>"u")return;const D=window.matchMedia("(prefers-color-scheme: dark)");try{D.addEventListener("change",({matches:ne})=>{W(ne?"dark":"light")})}catch{D.addListener(({matches:fe})=>{try{W(fe?"dark":"light")}catch(q){console.error(q)}})}},[g]),Ee.useEffect(()=>{A.length<=1&&H(!1)},[A]),Ee.useEffect(()=>{const D=ne=>{var fe;if(a.every(Y=>ne[Y]||ne.code===Y)){var K;H(!0),(K=G.current)==null||K.focus()}ne.code==="Escape"&&(document.activeElement===G.current||(fe=G.current)!=null&&fe.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[a]),Ee.useEffect(()=>{if(G.current)return()=>{P.current&&(P.current.focus({preventScroll:!0}),P.current=null,ie.current=!1)}},[G.current]),Ee.createElement("section",{ref:n,"aria-label":`${j} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},I.map((D,ne)=>{var fe;const[q,K]=D.split("-");return M.length?Ee.createElement("ol",{key:D,dir:k==="auto"?mI():k,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":F,"data-y-position":q,"data-x-position":K,style:{"--front-toast-height":`${((fe=O[0])==null?void 0:fe.height)||0}px`,"--width":`${iae}px`,"--gap":`${T}px`,...b,...dae(p,h)},onBlur:Y=>{ie.current&&!Y.currentTarget.contains(Y.relatedTarget)&&(ie.current=!1,P.current&&(P.current.focus({preventScroll:!0}),P.current=null))},onFocus:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||ie.current||(ie.current=!0,P.current=Y.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{V||H(!1)},onDragEnd:()=>H(!1),onPointerDown:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||X(!0)},onPointerUp:()=>X(!1)},M.filter(Y=>!Y.position&&ne===0||Y.position===D).map((Y,Z)=>{var U,J;return Ee.createElement(uae,{key:Y.id,icons:R,index:Z,toast:Y,defaultRichColors:v,duration:(U=S?.duration)!=null?U:x,className:S?.className,descriptionClassName:S?.descriptionClassName,invert:s,visibleToasts:E,closeButton:(J=S?.closeButton)!=null?J:u,interacting:V,position:D,style:S?.style,unstyled:S?.unstyled,classNames:S?.classNames,cancelButtonStyle:S?.cancelButtonStyle,actionButtonStyle:S?.actionButtonStyle,closeButtonAriaLabel:S?.closeButtonAriaLabel,removeToast:ue,toasts:M.filter(oe=>oe.position==Y.position),heights:O.filter(oe=>oe.position==Y.position),setHeights:L,expandByDefault:l,gap:T,expanded:z,swipeDirections:e.swipeDirections})})):null}))});function Rk({className:t,orientation:e="horizontal",decorative:n=!0,...r}){return f.jsx(Qne,{"data-slot":"separator",decorative:n,orientation:e,className:Oe("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function p0({delayDuration:t=0,...e}){return f.jsx($re,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function Ia({...t}){return f.jsx(p0,{children:f.jsx(zre,{"data-slot":"tooltip",...t})})}function Da({...t}){return f.jsx(Fre,{"data-slot":"tooltip-trigger",...t})}function La({className:t,sideOffset:e=0,children:n,...r}){return f.jsx(Ure,{children:f.jsxs(Bre,{"data-slot":"tooltip-content",sideOffset:e,className:Oe("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[n,f.jsx(qre,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function hae({className:t,...e}){return f.jsx(_re,{"data-slot":"switch",className:Oe("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:f.jsx(wre,{"data-slot":"switch-thumb",className:Oe("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function m0({...t}){return f.jsx(Ute,{"data-slot":"dropdown-menu",...t})}function g0({...t}){return f.jsx(Bte,{"data-slot":"dropdown-menu-trigger",...t})}function v0({className:t,sideOffset:e=4,...n}){return f.jsx(qte,{children:f.jsx(Vte,{"data-slot":"dropdown-menu-content",sideOffset:e,className:Oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...n})})}function Ro({className:t,inset:e,variant:n="default",...r}){return f.jsx(Gte,{"data-slot":"dropdown-menu-item","data-inset":e,"data-variant":n,className:Oe("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function pae({className:t,inset:e,...n}){return f.jsx(Hte,{"data-slot":"dropdown-menu-label","data-inset":e,className:Oe("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",t),...n})}function gI({className:t,...e}){return f.jsx(Wte,{"data-slot":"dropdown-menu-separator",className:Oe("bg-border -mx-1 my-1 h-px",t),...e})}function vI({...t}){return f.jsx(Yte,{"data-slot":"dropdown-menu-sub",...t})}function yI({className:t,inset:e,children:n,...r}){return f.jsxs(Kte,{"data-slot":"dropdown-menu-sub-trigger","data-inset":e,className:Oe("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",t),...r,children:[n,f.jsx(la,{className:"ml-auto size-4"})]})}function xI({className:t,...e}){return f.jsx(Xte,{"data-slot":"dropdown-menu-sub-content",className:Oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",t),...e})}async function mae(t){const e=await fetch("/api/mcp/export/server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:t})});if(!e.ok){let n=`Export failed (${e.status})`;try{const r=await e.json();r?.error&&(n=r.error)}catch{}throw new Error(n)}return e.json()}const bI={connected:{label:"Connected",indicatorColor:"#10b981",Icon:Ri,iconClassName:"h-3 w-3 text-green-500"},connecting:{label:"Connecting...",indicatorColor:"#3b82f6",Icon:bu,iconClassName:"h-3 w-3 text-blue-500 animate-spin"},"oauth-flow":{label:"Authorizing...",indicatorColor:"#a855f7",Icon:bu,iconClassName:"h-3 w-3 text-purple-500 animate-spin"},failed:{label:"Failed",indicatorColor:"#ef4444",Icon:uc,iconClassName:"h-3 w-3 text-red-500"},disconnected:{label:"Disconnected",indicatorColor:"#9ca3af",Icon:Lie,iconClassName:"h-3 w-3 text-gray-500"}},TB=t=>bI[t]||bI.disconnected,CB=t=>{if(t.url)return t.url.toString();const e=t.command??"",n=t.args??[];return[e,...n].filter(Boolean).join(" ").trim()},AB=t=>t.url?"HTTP/SSE":"STDIO";var _e=typeof window<"u"?window:void 0,Os=typeof globalThis<"u"?globalThis:_e,NB=Array.prototype,_I=NB.forEach,wI=NB.indexOf,ii=Os?.navigator,Ve=Os?.document,Ms=Os?.location,jk=Os?.fetch,Mk=Os!=null&&Os.XMLHttpRequest&&"withCredentials"in new Os.XMLHttpRequest?Os.XMLHttpRequest:void 0,SI=Os?.AbortController,js=ii?.userAgent,Et=_e??{},wo={DEBUG:!1,LIB_VERSION:"1.277.0"};function EI(t,e,n,r,s,i,a){try{var l=t[i](a),u=l.value}catch(d){return void n(d)}l.done?e(u):Promise.resolve(u).then(r,s)}function kI(t){return function(){var e=this,n=arguments;return new Promise(function(r,s){var i=t.apply(e,n);function a(u){EI(i,r,s,a,l,"next",u)}function l(u){EI(i,r,s,a,l,"throw",u)}a(void 0)})}}function Ye(){return Ye=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ye.apply(null,arguments)}function RB(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var gae=["$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"];function Ht(t,e){return t.indexOf(e)!==-1}var y0=function(t){return t.trim()},Ok=function(t){return t.replace(/^\$/,"")},vae=Array.isArray,jB=Object.prototype,MB=jB.hasOwnProperty,x0=jB.toString,An=vae||function(t){return x0.call(t)==="[object Array]"},ql=t=>typeof t=="function",rs=t=>t===Object(t)&&!An(t),Vd=t=>{if(rs(t)){for(var e in t)if(MB.call(t,e))return!1;return!0}return!1},Be=t=>t===void 0,Cr=t=>x0.call(t)=="[object String]",Pk=t=>Cr(t)&&t.trim().length===0,Xo=t=>t===null,$n=t=>Be(t)||Xo(t),Wa=t=>x0.call(t)=="[object Number]",Vl=t=>x0.call(t)==="[object Boolean]",yae=t=>t instanceof FormData,xae=t=>Ht(gae,t);function Ik(t){return t===null||typeof t!="object"}function Nx(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function OB(t){return!Be(Event)&&function(e,n){try{return e instanceof n}catch{return!1}}(t,Event)}var bae=[!0,"true",1,"1","yes"],IS=t=>Ht(bae,t),_ae=[!1,"false",0,"0","no"];function Na(t,e,n,r,s){return e>n&&(r.warn("min cannot be greater than max."),e=n),Wa(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),Na(s||n,e,n,r))}let wae=class{constructor(e){this.t=e,this.i={},this.o=()=>{Object.keys(this.i).forEach(n=>{var r=this.h(n)+this.m;r>=this.S?delete this.i[n]:this.$(n,r)})},this.h=n=>this.i[String(n)],this.$=(n,r)=>{this.i[String(n)]=r},this.consumeRateLimit=n=>{var r,s,i=(r=this.h(n))!==null&&r!==void 0?r:this.S;if((i=Math.max(i-1,0))===0)return!0;this.$(n,i);var a=i===0;return a&&((s=this.k)==null||s.call(this,n)),a},this.k=this.t.k,this.S=Na(this.t.bucketSize,0,100,this.t.P),this.m=Na(this.t.refillRate,0,this.S,this.t.P),this.T=Na(this.t.refillInterval,0,864e5,this.t.P),this.I=setInterval(()=>{this.o()},this.T)}stop(){this.I&&(clearInterval(this.I),this.I=void 0)}};var ny,TI,DS,Sae=t=>t instanceof Error;function Eae(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return DS&&n.length===TI||(TI=n.length,DS=n.reduce((r,s)=>{ny||(ny={});var i=ny[s];if(i)r[i[0]]=i[1];else for(var a=t(s),l=a.length-1;l>=0;l--){var u=a[l],d=u?.filename,p=e[s];if(d&&p){r[d]=p,ny[s]=[d,p];break}}return r},{})),DS}}var wf="?";function Dk(t,e,n,r){var s={platform:"web:javascript",filename:t,function:e==="<anonymous>"?wf:e,in_app:!0};return Be(n)||(s.lineno=n),Be(r)||(s.colno=r),s}var PB=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:wf,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},kae=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Tae=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Cae=/\((\S*)(?::(\d+))(?::(\d+))\)/,Aae=t=>{var e=kae.exec(t);if(e){var[,n,r,s]=e;return Dk(n,wf,+r,+s)}var i=Tae.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var a=Cae.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}var[l,u]=PB(i[1]||wf,i[2]);return Dk(u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},Nae=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Rae=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,jae=t=>{var e=Nae.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=Rae.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],s=e[1]||wf;return[s,r]=PB(s,r),Dk(r,s,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},CI=/\(error: (.*)\)/,AI=50;function Mae(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return function(r,s){s===void 0&&(s=0);for(var i=[],a=r.split(`
442
+ */const zie=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],uc=Ze("x",zie);function Fie(t){if(typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",e.appendChild(n),n.styleSheet?n.styleSheet.cssText=t:n.appendChild(document.createTextNode(t))}const Uie=t=>{switch(t){case"success":return Vie;case"info":return Gie;case"warning":return Hie;case"error":return Wie;default:return null}},Bie=Array(12).fill(0),qie=({visible:t,className:e})=>Ee.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":t},Ee.createElement("div",{className:"sonner-spinner"},Bie.map((n,r)=>Ee.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Vie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Hie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Gie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Wie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ee.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Yie=Ee.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Ee.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Ee.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Kie=()=>{const[t,e]=Ee.useState(document.hidden);return Ee.useEffect(()=>{const n=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),t};let Nk=1;class Xie{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{const n=this.subscribers.indexOf(e);this.subscribers.splice(n,1)}),this.publish=e=>{this.subscribers.forEach(n=>n(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var n;const{message:r,...s}=e,i=typeof e?.id=="number"||((n=e.id)==null?void 0:n.length)>0?e.id:Nk++,a=this.toasts.find(u=>u.id===i),l=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),a?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...e,id:i,title:r}),{...u,...e,id:i,dismissible:l,title:r}):u):this.addToast({title:r,...s,dismissible:l,id:i}),i},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:e,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),e),this.message=(e,n)=>this.create({...n,message:e}),this.error=(e,n)=>this.create({...n,message:e,type:"error"}),this.success=(e,n)=>this.create({...n,type:"success",message:e}),this.info=(e,n)=>this.create({...n,type:"info",message:e}),this.warning=(e,n)=>this.create({...n,type:"warning",message:e}),this.loading=(e,n)=>this.create({...n,type:"loading",message:e}),this.promise=(e,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:e,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const s=Promise.resolve(e instanceof Function?e():e);let i=r!==void 0,a;const l=s.then(async d=>{if(a=["resolve",d],Ee.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Jie(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!Ee.isValidElement(h)?h:{message:h};this.create({id:r,type:"success",description:g,...x})}}).catch(async d=>{if(a=["reject",d],n.error!==void 0){i=!1;const p=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof p=="object"&&!Ee.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,p)=>l.then(()=>a[0]==="reject"?p(a[1]):d(a[1])).catch(p));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(e,n)=>{const r=n?.id||Nk++;return this.create({jsx:e(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const Rs=new Xie,Qie=(t,e)=>{const n=e?.id||Nk++;return Rs.addToast({title:t,...e,id:n}),n},Jie=t=>t&&typeof t=="object"&&"ok"in t&&typeof t.ok=="boolean"&&"status"in t&&typeof t.status=="number",Zie=Qie,eae=()=>Rs.toasts,tae=()=>Rs.getActiveToasts(),It=Object.assign(Zie,{success:Rs.success,info:Rs.info,warning:Rs.warning,error:Rs.error,custom:Rs.custom,message:Rs.message,promise:Rs.promise,dismiss:Rs.dismiss,loading:Rs.loading},{getHistory:eae,getToasts:tae});Fie("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function ty(t){return t.label!==void 0}const nae=3,rae="24px",sae="16px",pI=4e3,iae=356,aae=14,oae=45,lae=200;function wa(...t){return t.filter(Boolean).join(" ")}function cae(t){const[e,n]=t.split("-"),r=[];return e&&r.push(e),n&&r.push(n),r}const uae=t=>{var e,n,r,s,i,a,l,u,d;const{invert:p,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:b,heights:E,index:S,toasts:k,expanded:T,removeToast:R,defaultRichColors:j,closeButton:A,style:N,cancelButtonStyle:M,actionButtonStyle:I,className:O="",descriptionClassName:L="",duration:z,position:H,gap:V,expandByDefault:X,classNames:F,icons:W,closeButtonAriaLabel:G="Close toast"}=t,[ee,P]=Ee.useState(null),[ie,ue]=Ee.useState(null),[D,ne]=Ee.useState(!1),[fe,q]=Ee.useState(!1),[K,Y]=Ee.useState(!1),[Z,U]=Ee.useState(!1),[J,oe]=Ee.useState(!1),[pe,ye]=Ee.useState(0),[je,Ne]=Ee.useState(0),Ae=Ee.useRef(h.duration||z||pI),He=Ee.useRef(null),lt=Ee.useRef(null),Fe=S===0,ct=S+1<=b,Ie=h.type,et=h.dismissible!==!1,ot=h.className||"",dr=h.descriptionClassName||"",be=Ee.useMemo(()=>E.findIndex(pt=>pt.toastId===h.id)||0,[E,h.id]),Te=Ee.useMemo(()=>{var pt;return(pt=h.closeButton)!=null?pt:A},[h.closeButton,A]),st=Ee.useMemo(()=>h.duration||z||pI,[h.duration,z]),We=Ee.useRef(0),Tt=Ee.useRef(0),er=Ee.useRef(0),tr=Ee.useRef(null),[jn,Le]=H.split("-"),ht=Ee.useMemo(()=>E.reduce((pt,Fn,Un)=>Un>=be?pt:pt+Fn.height,0),[E,be]),Lt=Kie(),gt=h.invert||p,wn=Ie==="loading";Tt.current=Ee.useMemo(()=>be*V+ht,[be,ht]),Ee.useEffect(()=>{Ae.current=st},[st]),Ee.useEffect(()=>{ne(!0)},[]),Ee.useEffect(()=>{const pt=lt.current;if(pt){const Fn=pt.getBoundingClientRect().height;return Ne(Fn),x(Un=>[{toastId:h.id,height:Fn,position:h.position},...Un]),()=>x(Un=>Un.filter(_r=>_r.toastId!==h.id))}},[x,h.id]),Ee.useLayoutEffect(()=>{if(!D)return;const pt=lt.current,Fn=pt.style.height;pt.style.height="auto";const Un=pt.getBoundingClientRect().height;pt.style.height=Fn,Ne(Un),x(_r=>_r.find(Gn=>Gn.toastId===h.id)?_r.map(Gn=>Gn.toastId===h.id?{...Gn,height:Un}:Gn):[{toastId:h.id,height:Un,position:h.position},..._r])},[D,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Zr=Ee.useCallback(()=>{q(!0),ye(Tt.current),x(pt=>pt.filter(Fn=>Fn.toastId!==h.id)),setTimeout(()=>{R(h)},lae)},[h,R,x,Tt]);Ee.useEffect(()=>{if(h.promise&&Ie==="loading"||h.duration===1/0||h.type==="loading")return;let pt;return T||v||Lt?(()=>{if(er.current<We.current){const _r=new Date().getTime()-We.current;Ae.current=Ae.current-_r}er.current=new Date().getTime()})():(()=>{Ae.current!==1/0&&(We.current=new Date().getTime(),pt=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Zr()},Ae.current))})(),()=>clearTimeout(pt)},[T,v,h,Ie,Lt,Zr]),Ee.useEffect(()=>{h.delete&&(Zr(),h.onDismiss==null||h.onDismiss.call(h,h))},[Zr,h.delete]);function ui(){var pt;if(W?.loading){var Fn;return Ee.createElement("div",{className:wa(F?.loader,h==null||(Fn=h.classNames)==null?void 0:Fn.loader,"sonner-loader"),"data-visible":Ie==="loading"},W.loading)}return Ee.createElement(qie,{className:wa(F?.loader,h==null||(pt=h.classNames)==null?void 0:pt.loader),visible:Ie==="loading"})}const eo=h.icon||W?.[Ie]||Uie(Ie);var ma,zu;return Ee.createElement("li",{tabIndex:0,ref:lt,className:wa(O,ot,F?.toast,h==null||(e=h.classNames)==null?void 0:e.toast,F?.default,F?.[Ie],h==null||(n=h.classNames)==null?void 0:n[Ie]),"data-sonner-toast":"","data-rich-colors":(ma=h.richColors)!=null?ma:j,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":D,"data-promise":!!h.promise,"data-swiped":J,"data-removed":fe,"data-visible":ct,"data-y-position":jn,"data-x-position":Le,"data-index":S,"data-front":Fe,"data-swiping":K,"data-dismissible":et,"data-type":Ie,"data-invert":gt,"data-swipe-out":Z,"data-swipe-direction":ie,"data-expanded":!!(T||X&&D),"data-testid":h.testId,style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${fe?pe:Tt.current}px`,"--initial-height":X?"auto":`${je}px`,...N,...h.style},onDragEnd:()=>{Y(!1),P(null),tr.current=null},onPointerDown:pt=>{pt.button!==2&&(wn||!et||(He.current=new Date,ye(Tt.current),pt.target.setPointerCapture(pt.pointerId),pt.target.tagName!=="BUTTON"&&(Y(!0),tr.current={x:pt.clientX,y:pt.clientY})))},onPointerUp:()=>{var pt,Fn,Un;if(Z||!et)return;tr.current=null;const _r=Number(((pt=lt.current)==null?void 0:pt.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Bi=Number(((Fn=lt.current)==null?void 0:Fn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Gn=new Date().getTime()-((Un=He.current)==null?void 0:Un.getTime()),Bn=ee==="x"?_r:Bi,Mn=Math.abs(Bn)/Gn;if(Math.abs(Bn)>=oae||Mn>.11){ye(Tt.current),h.onDismiss==null||h.onDismiss.call(h,h),ue(ee==="x"?_r>0?"right":"left":Bi>0?"down":"up"),Zr(),U(!0);return}else{var fn,nr;(fn=lt.current)==null||fn.style.setProperty("--swipe-amount-x","0px"),(nr=lt.current)==null||nr.style.setProperty("--swipe-amount-y","0px")}oe(!1),Y(!1),P(null)},onPointerMove:pt=>{var Fn,Un,_r;if(!tr.current||!et||((Fn=window.getSelection())==null?void 0:Fn.toString().length)>0)return;const Gn=pt.clientY-tr.current.y,Bn=pt.clientX-tr.current.x;var Mn;const fn=(Mn=t.swipeDirections)!=null?Mn:cae(H);!ee&&(Math.abs(Bn)>1||Math.abs(Gn)>1)&&P(Math.abs(Bn)>Math.abs(Gn)?"x":"y");let nr={x:0,y:0};const re=Q=>1/(1.5+Math.abs(Q)/20);if(ee==="y"){if(fn.includes("top")||fn.includes("bottom"))if(fn.includes("top")&&Gn<0||fn.includes("bottom")&&Gn>0)nr.y=Gn;else{const Q=Gn*re(Gn);nr.y=Math.abs(Q)<Math.abs(Gn)?Q:Gn}}else if(ee==="x"&&(fn.includes("left")||fn.includes("right")))if(fn.includes("left")&&Bn<0||fn.includes("right")&&Bn>0)nr.x=Bn;else{const Q=Bn*re(Bn);nr.x=Math.abs(Q)<Math.abs(Bn)?Q:Bn}(Math.abs(nr.x)>0||Math.abs(nr.y)>0)&&oe(!0),(Un=lt.current)==null||Un.style.setProperty("--swipe-amount-x",`${nr.x}px`),(_r=lt.current)==null||_r.style.setProperty("--swipe-amount-y",`${nr.y}px`)}},Te&&!h.jsx&&Ie!=="loading"?Ee.createElement("button",{"aria-label":G,"data-disabled":wn,"data-close-button":!0,onClick:wn||!et?()=>{}:()=>{Zr(),h.onDismiss==null||h.onDismiss.call(h,h)},className:wa(F?.closeButton,h==null||(r=h.classNames)==null?void 0:r.closeButton)},(zu=W?.close)!=null?zu:Yie):null,(Ie||h.icon||h.promise)&&h.icon!==null&&(W?.[Ie]!==null||h.icon)?Ee.createElement("div",{"data-icon":"",className:wa(F?.icon,h==null||(s=h.classNames)==null?void 0:s.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||ui():null,h.type!=="loading"?eo:null):null,Ee.createElement("div",{"data-content":"",className:wa(F?.content,h==null||(i=h.classNames)==null?void 0:i.content)},Ee.createElement("div",{"data-title":"",className:wa(F?.title,h==null||(a=h.classNames)==null?void 0:a.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?Ee.createElement("div",{"data-description":"",className:wa(L,dr,F?.description,h==null||(l=h.classNames)==null?void 0:l.description)},typeof h.description=="function"?h.description():h.description):null),Ee.isValidElement(h.cancel)?h.cancel:h.cancel&&ty(h.cancel)?Ee.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||M,onClick:pt=>{ty(h.cancel)&&et&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,pt),Zr())},className:wa(F?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,Ee.isValidElement(h.action)?h.action:h.action&&ty(h.action)?Ee.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||I,onClick:pt=>{ty(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,pt),!pt.defaultPrevented&&Zr())},className:wa(F?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function mI(){if(typeof window>"u"||typeof document>"u")return"ltr";const t=document.documentElement.getAttribute("dir");return t==="auto"||!t?window.getComputedStyle(document.documentElement).direction:t}function dae(t,e){const n={};return[t,e].forEach((r,s)=>{const i=s===1,a=i?"--mobile-offset":"--offset",l=i?sae:rae;function u(d){["top","right","bottom","left"].forEach(p=>{n[`${a}-${p}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${a}-${d}`]=l:n[`${a}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):u(l)}),n}const fae=Ee.forwardRef(function(e,n){const{id:r,invert:s,position:i="bottom-right",hotkey:a=["altKey","KeyT"],expand:l,closeButton:u,className:d,offset:p,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:b,visibleToasts:E=nae,toastOptions:S,dir:k=mI(),gap:T=aae,icons:R,containerAriaLabel:j="Notifications"}=e,[A,N]=Ee.useState([]),M=Ee.useMemo(()=>r?A.filter(D=>D.toasterId===r):A.filter(D=>!D.toasterId),[A,r]),I=Ee.useMemo(()=>Array.from(new Set([i].concat(M.filter(D=>D.position).map(D=>D.position)))),[M,i]),[O,L]=Ee.useState([]),[z,H]=Ee.useState(!1),[V,X]=Ee.useState(!1),[F,W]=Ee.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=Ee.useRef(null),ee=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),P=Ee.useRef(null),ie=Ee.useRef(!1),ue=Ee.useCallback(D=>{N(ne=>{var fe;return(fe=ne.find(q=>q.id===D.id))!=null&&fe.delete||Rs.dismiss(D.id),ne.filter(({id:q})=>q!==D.id)})},[]);return Ee.useEffect(()=>Rs.subscribe(D=>{if(D.dismiss){requestAnimationFrame(()=>{N(ne=>ne.map(fe=>fe.id===D.id?{...fe,delete:!0}:fe))});return}setTimeout(()=>{Yz.flushSync(()=>{N(ne=>{const fe=ne.findIndex(q=>q.id===D.id);return fe!==-1?[...ne.slice(0,fe),{...ne[fe],...D},...ne.slice(fe+1)]:[D,...ne]})})})}),[A]),Ee.useEffect(()=>{if(g!=="system"){W(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?W("dark"):W("light")),typeof window>"u")return;const D=window.matchMedia("(prefers-color-scheme: dark)");try{D.addEventListener("change",({matches:ne})=>{W(ne?"dark":"light")})}catch{D.addListener(({matches:fe})=>{try{W(fe?"dark":"light")}catch(q){console.error(q)}})}},[g]),Ee.useEffect(()=>{A.length<=1&&H(!1)},[A]),Ee.useEffect(()=>{const D=ne=>{var fe;if(a.every(Y=>ne[Y]||ne.code===Y)){var K;H(!0),(K=G.current)==null||K.focus()}ne.code==="Escape"&&(document.activeElement===G.current||(fe=G.current)!=null&&fe.contains(document.activeElement))&&H(!1)};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[a]),Ee.useEffect(()=>{if(G.current)return()=>{P.current&&(P.current.focus({preventScroll:!0}),P.current=null,ie.current=!1)}},[G.current]),Ee.createElement("section",{ref:n,"aria-label":`${j} ${ee}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},I.map((D,ne)=>{var fe;const[q,K]=D.split("-");return M.length?Ee.createElement("ol",{key:D,dir:k==="auto"?mI():k,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":F,"data-y-position":q,"data-x-position":K,style:{"--front-toast-height":`${((fe=O[0])==null?void 0:fe.height)||0}px`,"--width":`${iae}px`,"--gap":`${T}px`,...b,...dae(p,h)},onBlur:Y=>{ie.current&&!Y.currentTarget.contains(Y.relatedTarget)&&(ie.current=!1,P.current&&(P.current.focus({preventScroll:!0}),P.current=null))},onFocus:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||ie.current||(ie.current=!0,P.current=Y.relatedTarget)},onMouseEnter:()=>H(!0),onMouseMove:()=>H(!0),onMouseLeave:()=>{V||H(!1)},onDragEnd:()=>H(!1),onPointerDown:Y=>{Y.target instanceof HTMLElement&&Y.target.dataset.dismissible==="false"||X(!0)},onPointerUp:()=>X(!1)},M.filter(Y=>!Y.position&&ne===0||Y.position===D).map((Y,Z)=>{var U,J;return Ee.createElement(uae,{key:Y.id,icons:R,index:Z,toast:Y,defaultRichColors:v,duration:(U=S?.duration)!=null?U:x,className:S?.className,descriptionClassName:S?.descriptionClassName,invert:s,visibleToasts:E,closeButton:(J=S?.closeButton)!=null?J:u,interacting:V,position:D,style:S?.style,unstyled:S?.unstyled,classNames:S?.classNames,cancelButtonStyle:S?.cancelButtonStyle,actionButtonStyle:S?.actionButtonStyle,closeButtonAriaLabel:S?.closeButtonAriaLabel,removeToast:ue,toasts:M.filter(oe=>oe.position==Y.position),heights:O.filter(oe=>oe.position==Y.position),setHeights:L,expandByDefault:l,gap:T,expanded:z,swipeDirections:e.swipeDirections})})):null}))});function Rk({className:t,orientation:e="horizontal",decorative:n=!0,...r}){return f.jsx(Qne,{"data-slot":"separator",decorative:n,orientation:e,className:Oe("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",t),...r})}function p0({delayDuration:t=0,...e}){return f.jsx($re,{"data-slot":"tooltip-provider",delayDuration:t,...e})}function Ia({...t}){return f.jsx(p0,{children:f.jsx(zre,{"data-slot":"tooltip",...t})})}function Da({...t}){return f.jsx(Fre,{"data-slot":"tooltip-trigger",...t})}function La({className:t,sideOffset:e=0,children:n,...r}){return f.jsx(Ure,{children:f.jsxs(Bre,{"data-slot":"tooltip-content",sideOffset:e,className:Oe("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",t),...r,children:[n,f.jsx(qre,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function hae({className:t,...e}){return f.jsx(_re,{"data-slot":"switch",className:Oe("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...e,children:f.jsx(wre,{"data-slot":"switch-thumb",className:Oe("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function m0({...t}){return f.jsx(Ute,{"data-slot":"dropdown-menu",...t})}function g0({...t}){return f.jsx(Bte,{"data-slot":"dropdown-menu-trigger",...t})}function v0({className:t,sideOffset:e=4,...n}){return f.jsx(qte,{children:f.jsx(Vte,{"data-slot":"dropdown-menu-content",sideOffset:e,className:Oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",t),...n})})}function Ro({className:t,inset:e,variant:n="default",...r}){return f.jsx(Gte,{"data-slot":"dropdown-menu-item","data-inset":e,"data-variant":n,className:Oe("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r})}function pae({className:t,inset:e,...n}){return f.jsx(Hte,{"data-slot":"dropdown-menu-label","data-inset":e,className:Oe("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",t),...n})}function gI({className:t,...e}){return f.jsx(Wte,{"data-slot":"dropdown-menu-separator",className:Oe("bg-border -mx-1 my-1 h-px",t),...e})}function vI({...t}){return f.jsx(Yte,{"data-slot":"dropdown-menu-sub",...t})}function yI({className:t,inset:e,children:n,...r}){return f.jsxs(Kte,{"data-slot":"dropdown-menu-sub-trigger","data-inset":e,className:Oe("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",t),...r,children:[n,f.jsx(la,{className:"ml-auto size-4"})]})}function xI({className:t,...e}){return f.jsx(Xte,{"data-slot":"dropdown-menu-sub-content",className:Oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",t),...e})}async function mae(t){const e=await fetch("/api/mcp/export/server",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:t})});if(!e.ok){let n=`Export failed (${e.status})`;try{const r=await e.json();r?.error&&(n=r.error)}catch{}throw new Error(n)}return e.json()}const bI={connected:{label:"Connected",indicatorColor:"#10b981",Icon:Ri,iconClassName:"h-3 w-3 text-green-500"},connecting:{label:"Connecting...",indicatorColor:"#3b82f6",Icon:bu,iconClassName:"h-3 w-3 text-blue-500 animate-spin"},"oauth-flow":{label:"Authorizing...",indicatorColor:"#a855f7",Icon:bu,iconClassName:"h-3 w-3 text-purple-500 animate-spin"},failed:{label:"Failed",indicatorColor:"#ef4444",Icon:uc,iconClassName:"h-3 w-3 text-red-500"},disconnected:{label:"Disconnected",indicatorColor:"#9ca3af",Icon:Lie,iconClassName:"h-3 w-3 text-gray-500"}},TB=t=>bI[t]||bI.disconnected,CB=t=>{if(t.url)return t.url.toString();const e=t.command??"",n=t.args??[];return[e,...n].filter(Boolean).join(" ").trim()},AB=t=>t.url?"HTTP/SSE":"STDIO";var _e=typeof window<"u"?window:void 0,Os=typeof globalThis<"u"?globalThis:_e,NB=Array.prototype,_I=NB.forEach,wI=NB.indexOf,ii=Os?.navigator,Ve=Os?.document,Ms=Os?.location,jk=Os?.fetch,Mk=Os!=null&&Os.XMLHttpRequest&&"withCredentials"in new Os.XMLHttpRequest?Os.XMLHttpRequest:void 0,SI=Os?.AbortController,js=ii?.userAgent,Et=_e??{},wo={DEBUG:!1,LIB_VERSION:"1.278.0"};function EI(t,e,n,r,s,i,a){try{var l=t[i](a),u=l.value}catch(d){return void n(d)}l.done?e(u):Promise.resolve(u).then(r,s)}function kI(t){return function(){var e=this,n=arguments;return new Promise(function(r,s){var i=t.apply(e,n);function a(u){EI(i,r,s,a,l,"next",u)}function l(u){EI(i,r,s,a,l,"throw",u)}a(void 0)})}}function Ye(){return Ye=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ye.apply(null,arguments)}function RB(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var gae=["$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"];function Ht(t,e){return t.indexOf(e)!==-1}var y0=function(t){return t.trim()},Ok=function(t){return t.replace(/^\$/,"")},vae=Array.isArray,jB=Object.prototype,MB=jB.hasOwnProperty,x0=jB.toString,An=vae||function(t){return x0.call(t)==="[object Array]"},ql=t=>typeof t=="function",rs=t=>t===Object(t)&&!An(t),Vd=t=>{if(rs(t)){for(var e in t)if(MB.call(t,e))return!1;return!0}return!1},Be=t=>t===void 0,Cr=t=>x0.call(t)=="[object String]",Pk=t=>Cr(t)&&t.trim().length===0,Xo=t=>t===null,$n=t=>Be(t)||Xo(t),Wa=t=>x0.call(t)=="[object Number]",Vl=t=>x0.call(t)==="[object Boolean]",yae=t=>t instanceof FormData,xae=t=>Ht(gae,t);function Ik(t){return t===null||typeof t!="object"}function Nx(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function OB(t){return!Be(Event)&&function(e,n){try{return e instanceof n}catch{return!1}}(t,Event)}var bae=[!0,"true",1,"1","yes"],IS=t=>Ht(bae,t),_ae=[!1,"false",0,"0","no"];function Na(t,e,n,r,s){return e>n&&(r.warn("min cannot be greater than max."),e=n),Wa(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+s),Na(s||n,e,n,r))}let wae=class{constructor(e){this.t=e,this.i={},this.o=()=>{Object.keys(this.i).forEach(n=>{var r=this.h(n)+this.m;r>=this.S?delete this.i[n]:this.$(n,r)})},this.h=n=>this.i[String(n)],this.$=(n,r)=>{this.i[String(n)]=r},this.consumeRateLimit=n=>{var r,s,i=(r=this.h(n))!==null&&r!==void 0?r:this.S;if((i=Math.max(i-1,0))===0)return!0;this.$(n,i);var a=i===0;return a&&((s=this.k)==null||s.call(this,n)),a},this.k=this.t.k,this.S=Na(this.t.bucketSize,0,100,this.t.P),this.m=Na(this.t.refillRate,0,this.S,this.t.P),this.T=Na(this.t.refillInterval,0,864e5,this.t.P),this.I=setInterval(()=>{this.o()},this.T)}stop(){this.I&&(clearInterval(this.I),this.I=void 0)}};var ny,TI,DS,Sae=t=>t instanceof Error;function Eae(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return DS&&n.length===TI||(TI=n.length,DS=n.reduce((r,s)=>{ny||(ny={});var i=ny[s];if(i)r[i[0]]=i[1];else for(var a=t(s),l=a.length-1;l>=0;l--){var u=a[l],d=u?.filename,p=e[s];if(d&&p){r[d]=p,ny[s]=[d,p];break}}return r},{})),DS}}var wf="?";function Dk(t,e,n,r){var s={platform:"web:javascript",filename:t,function:e==="<anonymous>"?wf:e,in_app:!0};return Be(n)||(s.lineno=n),Be(r)||(s.colno=r),s}var PB=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:wf,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},kae=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Tae=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Cae=/\((\S*)(?::(\d+))(?::(\d+))\)/,Aae=t=>{var e=kae.exec(t);if(e){var[,n,r,s]=e;return Dk(n,wf,+r,+s)}var i=Tae.exec(t);if(i){if(i[2]&&i[2].indexOf("eval")===0){var a=Cae.exec(i[2]);a&&(i[2]=a[1],i[3]=a[2],i[4]=a[3])}var[l,u]=PB(i[1]||wf,i[2]);return Dk(u,l,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},Nae=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Rae=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,jae=t=>{var e=Nae.exec(t);if(e){if(e[3]&&e[3].indexOf(" > eval")>-1){var n=Rae.exec(e[3]);n&&(e[1]=e[1]||"eval",e[3]=n[1],e[4]=n[2],e[5]="")}var r=e[3],s=e[1]||wf;return[s,r]=PB(s,r),Dk(r,s,e[4]?+e[4]:void 0,e[5]?+e[5]:void 0)}},CI=/\(error: (.*)\)/,AI=50;function Mae(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return function(r,s){s===void 0&&(s=0);for(var i=[],a=r.split(`
443
443
  `),l=s;l<a.length;l++){var u=a[l];if(!(u.length>1024)){var d=CI.test(u)?u.replace(CI,"$1"):u;if(!d.match(/\S*Error: /)){for(var p of e){var h=p(d);if(h){i.push(h);break}}if(i.length>=AI)break}}}return function(g){if(!g.length)return[];var v=Array.from(g);return v.reverse(),v.slice(0,AI).map(x=>{return Ye({},x,{filename:x.filename||(b=v,b[b.length-1]||{}).filename,function:x.function||wf});var b})}(i)}}let Oae=class{constructor(e,n,r){e===void 0&&(e=[]),n===void 0&&(n=[]),r===void 0&&(r=[]),this.coercers=e,this.modifiers=r,this.stackParser=Mae(...n)}buildFromUnknown(e,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},s=this.buildCoercingContext(r,n,0).apply(e),i=this.buildParsingContext(),a=this.parseStacktrace(s,i);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}modifyFrames(e){var n=this;return kI(function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&An(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var r,s;return e.cause!=null&&(r=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(s=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),n.chunkIdMap)),Ye({},e,{cause:r,stack:s})}applyChunkIds(e,n){return e.map(r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r))}applyCoercers(e,n){for(var r of this.coercers)if(r.match(e))return r.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return kI(function*(){var r=e;for(var s of n.modifiers)r=yield s(r);return r})()}convertToExceptionList(e,n){var r,s,i,a={type:e.type,value:e.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(s=n.handled)===null||s===void 0||s,synthetic:(i=e.synthetic)!==null&&i!==void 0&&i}};e.stack&&(a.stacktrace={type:"raw",frames:e.stack});var l=[a];return e.cause!=null&&l.push(...this.convertToExceptionList(e.cause,Ye({},n,{handled:!0}))),l}buildParsingContext(){return{chunkIdMap:Eae(this.stackParser)}}buildCoercingContext(e,n,r){r===void 0&&(r=0);var s=(i,a)=>{if(a<=4){var l=this.buildCoercingContext(e,n,a);return this.applyCoercers(i,l)}};return Ye({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:e,apply:i=>s(i,r),next:i=>s(i,r+1)})}},Pae=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var r=Cr(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return Nx(e,"DOMException")}isDOMError(e){return Nx(e,"DOMError")}},Iae=class{match(e){return(n=>n instanceof Error)(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}},Dae=class{constructor(){}match(e){return Nx(e,"ErrorEvent")&&e.error!=null}coerce(e,n){var r,s=n.apply(e.error);return s||{type:"ErrorEvent",value:e.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}};var Lae=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;let $ae=class{match(e){return typeof e=="string"}coerce(e,n){var r,[s,i]=this.getInfos(e);return{type:s??"Error",value:i??e,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var n="Error",r=e,s=e.match(Lae);return s&&(n=s[1],r=s[2]),[n,r]}};var zae=["fatal","error","warning","log","info","debug"];function IB(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var s=n.slice(0,r).join(", ");if(!(s.length>e))return r===n.length||s.length<=e?s:s.slice(0,e)+"..."}return""}let Fae=class{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var r,s=this.getErrorPropertyFromObject(e);return s?n.apply(s):{type:this.getType(e),value:this.getValue(e),stack:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return OB(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+IB(e)}isSeverityLevel(e){return Cr(e)&&!Pk(e)&&zae.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=e[n];if(Sae(r))return r}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch{return}}},Uae=class{match(e){return OB(e)}coerce(e,n){var r,s=e.constructor.name;return{type:s,value:s+" captured as exception with keys: "+IB(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}};class Bae{match(e){return Ik(e)}coerce(e,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}let qae=class{match(e){return Nx(e,"PromiseRejectionEvent")}coerce(e,n){var r,s=this.getUnhandledRejectionReason(e);return Ik(s)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(s),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(s)}getUnhandledRejectionReason(e){if(Ik(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch{}return e}};var DB=t=>{var e={R:function(n){if(_e&&(wo.DEBUG||Et.POSTHOG_DEBUG)&&!Be(_e.console)&&_e.console){for(var r=("__rrweb_original__"in _e.console[n])?_e.console[n].__rrweb_original__:_e.console[n],s=arguments.length,i=new Array(s>1?s-1:0),a=1;a<s;a++)i[a-1]=arguments[a];r(t,...i)}},info:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.R("log",...r)},warn:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.R("warn",...r)},error:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];e.R("error",...r)},critical:function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];console.error(t,...r)},uninitializedWarning:n=>{e.error("You must initialize PostHog before calling "+n)},createLogger:n=>DB(t+" "+n)};return e},qe=DB("[PostHog.js]"),Lr=qe.createLogger,Vae=Lr("[ExternalScriptsLoader]"),NI=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return Vae.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=Ve?.querySelectorAll("script");if(r){for(var s,i=function(){if(r[a].src===e){var u=r[a];return u.__posthog_loading_callback_fired?{v:n()}:(u.addEventListener("load",d=>{u.__posthog_loading_callback_fired=!0,n(void 0,d)}),u.onerror=d=>n(d),{v:void 0})}},a=0;a<r.length;a++)if(s=i())return s.v}var l=()=>{if(!Ve)return n("document not found");var u=Ve.createElement("script");if(u.type="text/javascript",u.crossOrigin="anonymous",u.src=e,u.onload=h=>{u.__posthog_loading_callback_fired=!0,n(void 0,h)},u.onerror=h=>n(h),t.config.prepare_external_dependency_script&&(u=t.config.prepare_external_dependency_script(u)),!u)return n("prepare_external_dependency_script returned null");var d,p=Ve.querySelectorAll("body > script");p.length>0?(d=p[0].parentNode)==null||d.insertBefore(u,p[0]):Ve.body.appendChild(u)};Ve!=null&&Ve.body?l():Ve?.addEventListener("DOMContentLoaded",l)};Et.__PosthogExtensions__=Et.__PosthogExtensions__||{},Et.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{var r="/static/"+e+".js?v="+t.version;if(e==="remote-config"&&(r="/array/"+t.config.token+"/config.js"),e==="toolbar"){var s=3e5;r=r+"&t="+Math.floor(Date.now()/s)*s}var i=t.requestRouter.endpointFor("assets",r);NI(t,i,n)},Et.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var r=t.requestRouter.endpointFor("api",e);NI(t,r,n)};var Rx={};function Hl(t,e,n){if(An(t)){if(_I&&t.forEach===_I)t.forEach(e,n);else if("length"in t&&t.length===+t.length){for(var r=0,s=t.length;r<s;r++)if(r in t&&e.call(n,t[r],r)===Rx)return}}}function Cn(t,e,n){if(!$n(t)){if(An(t))return Hl(t,e,n);if(yae(t)){for(var r of t.entries())if(e.call(n,r[1],r[0])===Rx)return}else for(var s in t)if(MB.call(t,s)&&e.call(n,t[s],s)===Rx)return}}var lr=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Hl(n,function(s){for(var i in s)s[i]!==void 0&&(t[i]=s[i])}),t},eh=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return Hl(n,function(s){Hl(s,function(i){t.push(i)})}),t};function Wy(t){for(var e=Object.keys(t),n=e.length,r=new Array(n);n--;)r[n]=[e[n],t[e[n]]];return r}var RI=function(t){try{return t()}catch{return}},Hae=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.apply(this,n)}catch(s){qe.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),qe.critical(s)}}},sN=function(t){var e={};return Cn(t,function(n,r){(Cr(n)&&n.length>0||Wa(n))&&(e[r]=n)}),e};function Gae(t,e){return n=t,r=i=>Cr(i)&&!Xo(e)?i.slice(0,e):i,s=new Set,function i(a,l){return a!==Object(a)?r?r(a,l):a:s.has(a)?void 0:(s.add(a),An(a)?(u=[],Hl(a,d=>{u.push(i(d))})):(u={},Cn(a,(d,p)=>{s.has(d)||(u[p]=i(d,p))})),u);var u}(n);var n,r,s}var Wae=["herokuapp.com","vercel.app","netlify.app"];function Yae(t){var e=t?.hostname;if(!Cr(e))return!1;var n=e.split(".").slice(-2).join(".");for(var r of Wae)if(n===r)return!1;return!0}function LB(t,e){for(var n=0;n<t.length;n++)if(e(t[n]))return t[n]}function Ar(t,e,n,r){var{capture:s=!1,passive:i=!0}=r??{};t?.addEventListener(e,n,{capture:s,passive:i})}var $B="$people_distinct_id",Op="__alias",Pp="__timers",jI="$autocapture_disabled_server_side",Lk="$heatmaps_enabled_server_side",MI="$exception_capture_enabled_server_side",$k="$error_tracking_suppression_rules",OI="$error_tracking_capture_extension_exceptions",PI="$web_vitals_enabled_server_side",zB="$dead_clicks_enabled_server_side",II="$web_vitals_allowed_metrics",LS="$session_recording_remote_config",jx="$sesid",FB="$session_is_sampled",Hd="$enabled_feature_flags",Ip="$early_access_features",zk="$feature_flag_details",Dp="$stored_person_properties",Gc="$stored_group_properties",Fk="$surveys",ry="$surveys_activated",Mx="$flag_call_reported",So="$user_state",Uk="$client_session_props",Bk="$capture_rate_limit",qk="$initial_campaign_params",Vk="$initial_referrer_info",Ox="$initial_person_info",Px="$epp",UB="__POSTHOG_TOOLBAR__",pp="$posthog_cookieless",Kae=[$B,Op,"__cmpns",Pp,"$session_recording_enabled_server_side",Lk,jx,Hd,$k,So,Ip,zk,Gc,Dp,Fk,Mx,Uk,Bk,qk,Vk,Px,Ox];function DI(t){return t instanceof Element&&(t.id===UB||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function b0(t){return!!t&&t.nodeType===1}function Gl(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function BB(t){return!!t&&t.nodeType===3}function qB(t){return!!t&&t.nodeType===11}function iN(t){return t?y0(t).split(/\s+/):[]}function LI(t){var e=_e?.location.href;return!!(e&&t&&t.some(n=>e.match(n)))}function Ix(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return iN(e)}function VB(t){return $n(t)?null:y0(t).split(/(\s+)/).filter(e=>Nm(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function _0(t){var e="";return Hk(t)&&!KB(t)&&t.childNodes&&t.childNodes.length&&Cn(t.childNodes,function(n){var r;BB(n)&&n.textContent&&(e+=(r=VB(n.textContent))!==null&&r!==void 0?r:"")}),y0(e)}function HB(t){return Be(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var aN=["a","button","form","input","select","textarea","label"];function GB(t,e){if(Be(e))return!0;var n,r=function(i){if(e.some(a=>i.matches(a)))return{v:!0}};for(var s of t)if(n=r(s))return n.v;return!1}function WB(t){var e=t.parentNode;return!(!e||!b0(e))&&e}var $I=[".ph-no-rageclick",".ph-no-capture"],oN=t=>!t||Gl(t,"html")||!b0(t),YB=(t,e)=>{if(!_e||oN(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[t],s=t;s.parentNode&&!Gl(s,"body");)if(qB(s.parentNode))r.push(s.parentNode.host),s=s.parentNode.host;else{var i=WB(s);if(!i)break;if(e||aN.indexOf(i.tagName.toLowerCase())>-1)n=!0;else{var a=_e.getComputedStyle(i);a&&a.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(i),s=i}return{parentIsUsefulElement:n,targetElementList:r}};function Xae(t,e,n,r,s){var i,a,l,u;if(n===void 0&&(n=void 0),!_e||oN(t)||(i=n)!=null&&i.url_allowlist&&!LI(n.url_allowlist)||(a=n)!=null&&a.url_ignorelist&&LI(n.url_ignorelist))return!1;if((l=n)!=null&&l.dom_event_allowlist){var d=n.dom_event_allowlist;if(d&&!d.some(x=>e.type===x))return!1}var{parentIsUsefulElement:p,targetElementList:h}=YB(t,r);if(!function(x,b){var E=b?.element_allowlist;if(Be(E))return!0;var S,k=function(R){if(E.some(j=>R.tagName.toLowerCase()===j))return{v:!0}};for(var T of x)if(S=k(T))return S.v;return!1}(h,n)||!GB(h,(u=n)==null?void 0:u.css_selector_allowlist))return!1;var g=_e.getComputedStyle(t);if(g&&g.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var v=t.tagName.toLowerCase();switch(v){case"html":return!1;case"form":return(s||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(s||["change","click"]).indexOf(e.type)>=0;default:return p?(s||["click"]).indexOf(e.type)>=0:(s||["click"]).indexOf(e.type)>=0&&(aN.indexOf(v)>-1||t.getAttribute("contenteditable")==="true")}}function Hk(t){for(var e=t;e.parentNode&&!Gl(e,"body");e=e.parentNode){var n=Ix(e);if(Ht(n,"ph-sensitive")||Ht(n,"ph-no-capture"))return!1}if(Ht(Ix(t),"ph-include"))return!0;var r=t.type||"";if(Cr(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var s=t.name||t.id||"";return!(Cr(s)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(s.replace(/[^a-zA-Z0-9]/g,"")))}function KB(t){return!!(Gl(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Gl(t,"select")||Gl(t,"textarea")||t.getAttribute("contenteditable")==="true")}var XB="(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})",Qae=new RegExp("^(?:"+XB+")$"),Jae=new RegExp(XB),QB="\\d{3}-?\\d{2}-?\\d{4}",Zae=new RegExp("^("+QB+")$"),eoe=new RegExp("("+QB+")");function Nm(t,e){return e===void 0&&(e=!0),!($n(t)||Cr(t)&&(t=y0(t),(e?Qae:Jae).test((t||"").replace(/[- ]/g,""))||(e?Zae:eoe).test(t)))}function JB(t){var e=_0(t);return Nm(e=(e+" "+ZB(t)).trim())?e:""}function ZB(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Cn(t.childNodes,function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var s=_0(n);e=(e+" "+s).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+ZB(n)).trim())}catch(i){qe.error("[AutoCapture]",i)}}),e}function toe(t){return function(e){var n=e.map(r=>{var s,i,a="";if(r.tag_name&&(a+=r.tag_name),r.attr_class)for(var l of(r.attr_class.sort(),r.attr_class))a+="."+l.replace(/"/g,"");var u=Ye({},r.text?{text:r.text}:{},{"nth-child":(s=r.nth_child)!==null&&s!==void 0?s:0,"nth-of-type":(i=r.nth_of_type)!==null&&i!==void 0?i:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),d={};return Wy(u).sort((p,h)=>{var[g]=p,[v]=h;return g.localeCompare(v)}).forEach(p=>{var[h,g]=p;return d[zI(h.toString())]=zI(g.toString())}),a+=":",a+=Wy(d).map(p=>{var[h,g]=p;return h+'="'+g+'"'}).join("")});return n.join(";")}(function(e){return e.map(n=>{var r,s,i={text:(r=n.$el_text)==null?void 0:r.slice(0,400),tag_name:n.tag_name,href:(s=n.attr__href)==null?void 0:s.slice(0,2048),attr_class:noe(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return Wy(n).filter(a=>{var[l]=a;return l.indexOf("attr__")===0}).forEach(a=>{var[l,u]=a;return i.attributes[l]=u}),i})}(t))}function zI(t){return t.replace(/"|\\"/g,'\\"')}function noe(t){var e=t.attr__class;return e?An(e)?e:iN(e):void 0}class e9{constructor(){this.clicks=[]}isRageClick(e,n,r){var s=this.clicks[this.clicks.length-1];if(s&&Math.abs(e-s.x)+Math.abs(n-s.y)<30&&r-s.timestamp<1e3){if(this.clicks.push({x:e,y:n,timestamp:r}),this.clicks.length===3)return!0}else this.clicks=[{x:e,y:n,timestamp:r}];return!1}}var $S="$copy_autocapture",Ao=function(t){return t.GZipJS="gzip-js",t.Base64="base64",t}({}),Dx=t=>{var e=Ve?.createElement("a");return Be(e)?null:(e.href=t,e)},roe=function(t,e){var n,r;e===void 0&&(e="&");var s=[];return Cn(t,function(i,a){Be(i)||Be(a)||a==="undefined"||(n=encodeURIComponent((l=>l instanceof File)(i)?i.name:i.toString()),r=encodeURIComponent(a),s[s.length]=r+"="+n)}),s.join(e)},Lx=function(t,e){for(var n,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),s=0;s<r.length;s++){var i=r[s].split("=");if(i[0]===e){n=i;break}}if(!An(n)||n.length<2)return"";var a=n[1];try{a=decodeURIComponent(a)}catch{qe.error("Skipping decoding for malformed query param: "+a)}return a.replace(/\+/g," ")},gg=function(t,e,n){if(!t||!e||!e.length)return t;for(var r=t.split("#"),s=r[0]||"",i=r[1],a=s.split("?"),l=a[1],u=a[0],d=(l||"").split("&"),p=[],h=0;h<d.length;h++){var g=d[h].split("=");An(g)&&(e.includes(g[0])?p.push(g[0]+"="+n):p.push(d[h]))}var v=u;return l!=null&&(v+="?"+p.join("&")),i!=null&&(v+="#"+i),v},$x=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},FI=Lr("[AutoCapture]");function zS(t,e){return e.length>t?e.slice(0,t)+"...":e}function soe(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!b0(e));return e}function ioe(t,e,n,r){var s=t.tagName.toLowerCase(),i={tag_name:s};aN.indexOf(s)>-1&&!n&&(s.toLowerCase()==="a"||s.toLowerCase()==="button"?i.$el_text=zS(1024,JB(t)):i.$el_text=zS(1024,_0(t)));var a=Ix(t);a.length>0&&(i.classes=a.filter(function(p){return p!==""})),Cn(t.attributes,function(p){var h;if((!KB(t)||["name","id","class","aria-label"].indexOf(p.name)!==-1)&&(r==null||!r.includes(p.name))&&!e&&Nm(p.value)&&(h=p.name,!Cr(h)||h.substring(0,10)!=="_ngcontent"&&h.substring(0,7)!=="_nghost")){var g=p.value;p.name==="class"&&(g=iN(g).join(" ")),i["attr__"+p.name]=zS(1024,g)}});for(var l=1,u=1,d=t;d=soe(d);)l++,d.tagName===t.tagName&&u++;return i.nth_child=l,i.nth_of_type=u,i}function aoe(t,e){for(var n,r,{e:s,maskAllElementAttributes:i,maskAllText:a,elementAttributeIgnoreList:l,elementsChainAsString:u}=e,d=[t],p=t;p.parentNode&&!Gl(p,"body");)qB(p.parentNode)?(d.push(p.parentNode.host),p=p.parentNode.host):(d.push(p.parentNode),p=p.parentNode);var h,g=[],v={},x=!1,b=!1;if(Cn(d,R=>{var j=Hk(R);R.tagName.toLowerCase()==="a"&&(x=R.getAttribute("href"),x=j&&x&&Nm(x)&&x),Ht(Ix(R),"ph-no-capture")&&(b=!0),g.push(ioe(R,i,a,l));var A=function(N){if(!Hk(N))return{};var M={};return Cn(N.attributes,function(I){if(I.name&&I.name.indexOf("data-ph-capture-attribute")===0){var O=I.name.replace("data-ph-capture-attribute-",""),L=I.value;O&&L&&Nm(L)&&(M[O]=L)}}),M}(R);lr(v,A)}),b)return{props:{},explicitNoCapture:b};if(a||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?g[0].$el_text=JB(t):g[0].$el_text=_0(t)),x){var E,S;g[0].attr__href=x;var k=(E=Dx(x))==null?void 0:E.host,T=_e==null||(S=_e.location)==null?void 0:S.host;k&&T&&k!==T&&(h=x)}return{props:lr({$event_type:s.type,$ce_version:1},u?{}:{$elements:g},{$elements_chain:toe(g)},(n=g[0])!=null&&n.$el_text?{$el_text:(r=g[0])==null?void 0:r.$el_text}:{},h&&s.type==="click"?{$external_click_url:h}:{},v)}}let ooe=class{constructor(e){this.C=!1,this.O=null,this.rageclicks=new e9,this.F=!1,this.instance=e,this.M=null}get A(){var e,n,r=rs(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map(s=>new RegExp(s)),r.url_ignorelist=(n=r.url_ignorelist)==null?void 0:n.map(s=>new RegExp(s)),r}j(){if(this.isBrowserSupported()){if(_e&&Ve){var e=r=>{r=r||_e?.event;try{this.D(r)}catch(s){FI.error("Failed to capture event",s)}};if(Ar(Ve,"submit",e,{capture:!0}),Ar(Ve,"change",e,{capture:!0}),Ar(Ve,"click",e,{capture:!0}),this.A.capture_copied_text){var n=r=>{r=r||_e?.event,this.D(r,$S)};Ar(Ve,"copy",n,{capture:!0}),Ar(Ve,"cut",n,{capture:!0})}}}else FI.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.C&&(this.j(),this.C=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.F=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[jI]:!!e.autocapture_opt_out}),this.O=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.M=e}getElementSelectors(e){var n,r=[];return(n=this.M)==null||n.forEach(s=>{var i=Ve?.querySelectorAll(s);i?.forEach(a=>{e===a&&r.push(s)})}),r}get isEnabled(){var e,n,r=(e=this.instance.persistence)==null?void 0:e.props[jI],s=this.O;if(Xo(s)&&!Vl(r)&&!this.instance.L())return!1;var i=(n=this.O)!==null&&n!==void 0?n:!!r;return!!this.instance.config.autocapture&&!i}D(e,n){if(n===void 0&&(n="$autocapture"),this.isEnabled){var r,s=HB(e);BB(s)&&(s=s.parentNode||null),n==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&function(g,v){if(!_e||oN(g))return!1;var x,b;if((x=Vl(v)?!!v&&$I:(b=v?.css_selector_ignorelist)!==null&&b!==void 0?b:$I)===!1)return!1;var{targetElementList:E}=YB(g,!1);return!GB(E,x)}(s,this.instance.config.rageclick)&&this.D(e,"$rageclick");var i=n===$S;if(s&&Xae(s,e,this.A,i,i?["copy","cut"]:void 0)){var{props:a,explicitNoCapture:l}=aoe(s,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.A.element_attribute_ignorelist,elementsChainAsString:this.F});if(l)return!1;var u=this.getElementSelectors(s);if(u&&u.length>0&&(a.$element_selectors=u),n===$S){var d,p=VB(_e==null||(d=_e.getSelection())==null?void 0:d.toString()),h=e.type||"clipboard";if(!p)return!1;a.$selected_content=p,a.$copy_type=h}return this.instance.capture(n,a),!0}}}isBrowserSupported(){return ql(Ve?.querySelectorAll)}};Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return Wa(t)&&isFinite(t)&&Math.floor(t)===t});var UI="0123456789abcdef";let loe=class Gk{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,r,s){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(s)||e<0||n<0||r<0||s<0||e>0xffffffffffff||n>4095||r>1073741823||s>4294967295)throw new RangeError("invalid field value");var i=new Uint8Array(16);return i[0]=e/Math.pow(2,40),i[1]=e/Math.pow(2,32),i[2]=e/Math.pow(2,24),i[3]=e/Math.pow(2,16),i[4]=e/Math.pow(2,8),i[5]=e,i[6]=112|n>>>8,i[7]=n,i[8]=128|r>>>24,i[9]=r>>>16,i[10]=r>>>8,i[11]=r,i[12]=s>>>24,i[13]=s>>>16,i[14]=s>>>8,i[15]=s,new Gk(i)}toString(){for(var e="",n=0;n<this.bytes.length;n++)e=e+UI.charAt(this.bytes[n]>>>4)+UI.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Gk(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;n<16;n++){var r=this.bytes[n]-e.bytes[n];if(r!==0)return Math.sign(r)}return 0}},coe=class{constructor(){this.N=0,this.U=0,this.H=new uoe}generate(){var e=this.generateOrAbort();if(Be(e)){this.N=0;var n=this.generateOrAbort();if(Be(n))throw new Error("Could not generate UUID after timestamp reset");return n}return e}generateOrAbort(){var e=Date.now();if(e>this.N)this.N=e,this.B();else{if(!(e+1e4>this.N))return;this.U++,this.U>4398046511103&&(this.N++,this.B())}return loe.fromFieldsV7(this.N,Math.trunc(this.U/Math.pow(2,30)),this.U&Math.pow(2,30)-1,this.H.nextUint32())}B(){this.U=1024*this.H.nextUint32()+(1023&this.H.nextUint32())}};var BI,t9=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<t.length;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};_e&&!Be(_e.crypto)&&crypto.getRandomValues&&(t9=t=>crypto.getRandomValues(t));let uoe=class{constructor(){this.q=new Uint32Array(8),this.W=1/0}nextUint32(){return this.W>=this.q.length&&(t9(this.q),this.W=0),this.q[this.W++]}};var Bl=()=>doe().toString(),doe=()=>(BI||(BI=new coe)).generate(),mp="",foe=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function hoe(t,e){if(e){var n=function(s,i){if(i===void 0&&(i=Ve),mp)return mp;if(!i||["localhost","127.0.0.1"].includes(s))return"";for(var a=s.split("."),l=Math.min(a.length,8),u="dmn_chk_"+Bl();!mp&&l--;){var d=a.slice(l).join("."),p=u+"=1;domain=."+d+";path=/";i.cookie=p+";max-age=3",i.cookie.includes(u)&&(i.cookie=p+";max-age=0",mp=d)}return mp}(t);if(!n){var r=(s=>{var i=s.match(foe);return i?i[0]:""})(t);r!==n&&qe.info("Warning: cookie subdomain discovery mismatch",r,n),n=r}return n?"; domain=."+n:""}return""}var $a={G:()=>!!Ve,V:function(t){qe.error("cookieStore error: "+t)},J:function(t){if(Ve){try{for(var e=t+"=",n=Ve.cookie.split(";").filter(i=>i.length),r=0;r<n.length;r++){for(var s=n[r];s.charAt(0)==" ";)s=s.substring(1,s.length);if(s.indexOf(e)===0)return decodeURIComponent(s.substring(e.length,s.length))}}catch{}return null}},K:function(t){var e;try{e=JSON.parse($a.J(t))||{}}catch{}return e},Y:function(t,e,n,r,s){if(Ve)try{var i="",a="",l=hoe(Ve.location.hostname,r);if(n){var u=new Date;u.setTime(u.getTime()+24*n*60*60*1e3),i="; expires="+u.toUTCString()}s&&(a="; secure");var d=t+"="+encodeURIComponent(JSON.stringify(e))+i+"; SameSite=Lax; path=/"+l+a;return d.length>3686.4&&qe.warn("cookieStore warning: large cookie, len="+d.length),Ve.cookie=d,d}catch{return}},X:function(t,e){if(Ve!=null&&Ve.cookie)try{$a.Y(t,"",-1,e)}catch{return}}},FS=null,Vn={G:function(){if(!Xo(FS))return FS;var t=!0;if(Be(_e))t=!1;else try{var e="__mplssupport__";Vn.Y(e,"xyz"),Vn.J(e)!=='"xyz"'&&(t=!1),Vn.X(e)}catch{t=!1}return t||qe.error("localStorage unsupported; falling back to cookie store"),FS=t,t},V:function(t){qe.error("localStorage error: "+t)},J:function(t){try{return _e?.localStorage.getItem(t)}catch(e){Vn.V(e)}return null},K:function(t){try{return JSON.parse(Vn.J(t))||{}}catch{}return null},Y:function(t,e){try{_e?.localStorage.setItem(t,JSON.stringify(e))}catch(n){Vn.V(n)}},X:function(t){try{_e?.localStorage.removeItem(t)}catch(e){Vn.V(e)}}},poe=["distinct_id",jx,FB,Px,Ox],sy=Ye({},Vn,{K:function(t){try{var e={};try{e=$a.K(t)||{}}catch{}var n=lr(e,JSON.parse(Vn.J(t)||"{}"));return Vn.Y(t,n),n}catch{}return null},Y:function(t,e,n,r,s,i){try{Vn.Y(t,e,void 0,void 0,i);var a={};poe.forEach(l=>{e[l]&&(a[l]=e[l])}),Object.keys(a).length&&$a.Y(t,a,n,r,s,i)}catch(l){Vn.V(l)}},X:function(t,e){try{_e?.localStorage.removeItem(t),$a.X(t,e)}catch(n){Vn.V(n)}}}),iy={},moe={G:function(){return!0},V:function(t){qe.error("memoryStorage error: "+t)},J:function(t){return iy[t]||null},K:function(t){return iy[t]||null},Y:function(t,e){iy[t]=e},X:function(t){delete iy[t]}},$c=null,Wr={G:function(){if(!Xo($c))return $c;if($c=!0,Be(_e))$c=!1;else try{var t="__support__";Wr.Y(t,"xyz"),Wr.J(t)!=='"xyz"'&&($c=!1),Wr.X(t)}catch{$c=!1}return $c},V:function(t){qe.error("sessionStorage error: ",t)},J:function(t){try{return _e?.sessionStorage.getItem(t)}catch(e){Wr.V(e)}return null},K:function(t){try{return JSON.parse(Wr.J(t))||null}catch{}return null},Y:function(t,e){try{_e?.sessionStorage.setItem(t,JSON.stringify(e))}catch(n){Wr.V(n)}},X:function(t){try{_e?.sessionStorage.removeItem(t)}catch(e){Wr.V(e)}}},Eo=function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t}({});let goe=class{constructor(e){this._instance=e}get A(){return this._instance.config}get consent(){return this.Z()?Eo.DENIED:this.tt}isOptedOut(){return this.A.cookieless_mode==="always"||this.consent===Eo.DENIED||this.consent===Eo.PENDING&&(this.A.opt_out_capturing_by_default||this.A.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Eo.DENIED}optInOut(e){this.it.Y(this.et,e?1:0,this.A.cookie_expiration,this.A.cross_subdomain_cookie,this.A.secure_cookie)}reset(){this.it.X(this.et,this.A.cross_subdomain_cookie)}get et(){var{token:e,opt_out_capturing_cookie_prefix:n,consent_persistence_name:r}=this._instance.config;return r||(n?n+e:"__ph_opt_in_out_"+e)}get tt(){var e=this.it.J(this.et);return IS(e)?Eo.GRANTED:Ht(_ae,e)?Eo.DENIED:Eo.PENDING}get it(){if(!this.rt){var e=this.A.opt_out_capturing_persistence_type;this.rt=e==="localStorage"?Vn:$a;var n=e==="localStorage"?$a:Vn;n.J(this.et)&&(this.rt.J(this.et)||this.optInOut(IS(n.J(this.et))),n.X(this.et,this.A.cross_subdomain_cookie))}return this.rt}Z(){return!!this.A.respect_dnt&&!!LB([ii?.doNotTrack,ii?.msDoNotTrack,Et.doNotTrack],e=>IS(e))}};var ay=Lr("[Dead Clicks]"),voe=()=>!0,yoe=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(zB)),r=t.instance.config.capture_dead_clicks;return Vl(r)?r:n};class n9{get lazyLoadedDeadClicksAutocapture(){return this.st}constructor(e,n,r){this.instance=e,this.isEnabled=n,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[zB]:e?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.nt(()=>{this.ot()})}nt(e){var n,r;(n=Et.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&e(),(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",s=>{s?ay.error("failed to load script",s):e()})}ot(){var e;if(Ve){if(!this.st&&(e=Et.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=rs(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.st=Et.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.st.start(Ve),ay.info("starting...")}}else ay.error("`document` not found. Cannot start.")}stop(){this.st&&(this.st.stop(),this.st=void 0,ay.info("stopping..."))}}var gp=Lr("[ExceptionAutocapture]");let xoe=class{constructor(e){var n,r,s;this.lt=()=>{var i;if(_e&&this.isEnabled&&(i=Et.__PosthogExtensions__)!=null&&i.errorWrappingFunctions){var a=Et.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,l=Et.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,u=Et.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.ut&&this.A.capture_unhandled_errors&&(this.ut=a(this.captureException.bind(this))),!this.ht&&this.A.capture_unhandled_rejections&&(this.ht=l(this.captureException.bind(this))),!this.dt&&this.A.capture_console_errors&&(this.dt=u(this.captureException.bind(this)))}catch(d){gp.error("failed to start",d),this.vt()}}},this._instance=e,this.ct=!((n=this._instance.persistence)==null||!n.props[MI]),this.A=this.ft(),this.gt=new wae({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(s=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10,refillInterval:1e4,P:gp}),this.startIfEnabled()}ft(){var e=this._instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return rs(e)?n=Ye({},n,e):(Be(e)?this.ct:e)&&(n=Ye({},n,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.A.capture_console_errors||this.A.capture_unhandled_errors||this.A.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(gp.info("enabled"),this.nt(this.lt))}nt(e){var n,r;(n=Et.__PosthogExtensions__)!=null&&n.errorWrappingFunctions&&e(),(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",s=>{if(s)return gp.error("failed to load script",s);e()})}vt(){var e,n,r;(e=this.ut)==null||e.call(this),this.ut=void 0,(n=this.ht)==null||n.call(this),this.ht=void 0,(r=this.dt)==null||r.call(this),this.dt=void 0}onRemoteConfig(e){var n=e.autocaptureExceptions;this.ct=!!n||!1,this.A=this.ft(),this._instance.persistence&&this._instance.persistence.register({[MI]:this.ct}),this.startIfEnabled()}captureException(e){var n,r,s=(n=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&n!==void 0?n:"Exception";this.gt.consumeRateLimit(s)?gp.info("Skipping exception capture because of client rate limiting.",{exception:s}):this._instance.exceptions.sendExceptionEvent(e)}};function qI(t,e,n){try{if(!(e in t))return()=>{};var r=t[e],s=n(r);return ql(s)&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=s,()=>{t[e]=r}}catch{return()=>{}}}let boe=class{constructor(e){var n;this._instance=e,this._t=(_e==null||(n=_e.location)==null?void 0:n.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(qe.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.yt&&this.yt(),this.yt=void 0,qe.info("History API monitoring stopped")}monitorHistoryChanges(){var e,n;if(_e&&_e.history){var r=this;(e=_e.history.pushState)!=null&&e.__posthog_wrapped__||qI(_e.history,"pushState",s=>function(i,a,l){s.call(this,i,a,l),r.bt("pushState")}),(n=_e.history.replaceState)!=null&&n.__posthog_wrapped__||qI(_e.history,"replaceState",s=>function(i,a,l){s.call(this,i,a,l),r.bt("replaceState")}),this.wt()}}bt(e){try{var n,r=_e==null||(n=_e.location)==null?void 0:n.pathname;if(!r)return;r!==this._t&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this._t=r}catch(s){qe.error("Error capturing "+e+" pageview",s)}}wt(){if(!this.yt){var e=()=>{this.bt("popstate")};Ar(_e,"popstate",e),this.yt=()=>{_e&&_e.removeEventListener("popstate",e)}}}};var US=Lr("[SegmentIntegration]");function _oe(t,e){var n=t.config.segment;if(!n)return e();(function(r,s){var i=r.config.segment;if(!i)return s();var a=u=>{var d=()=>u.anonymousId()||Bl();r.config.get_device_id=d,u.id()&&(r.register({distinct_id:u.id(),$device_id:d()}),r.persistence.set_property(So,"identified")),s()},l=i.user();"then"in l&&ql(l.then)?l.then(u=>a(u)):a(l)})(t,()=>{n.register((r=>{Promise&&Promise.resolve||US.warn("This browser does not have Promise support, and can not use the segment integration");var s=(i,a)=>{if(!a)return i;i.event.userId||i.event.anonymousId===r.get_distinct_id()||(US.info("No userId set, resetting PostHog"),r.reset()),i.event.userId&&i.event.userId!==r.get_distinct_id()&&(US.info("UserId set, identifying with PostHog"),r.identify(i.event.userId));var l=r.calculateEventProperties(a,i.event.properties);return i.event.properties=Object.assign({},l,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:i=>s(i,i.event.event),page:i=>s(i,"$pageview"),identify:i=>s(i,"$identify"),screen:i=>s(i,"$screen")}})(t)).then(()=>{e()})})}var r9="posthog-js";function s9(t,e){var{organization:n,projectId:r,prefix:s,severityAllowList:i=["error"],sendExceptionsToPostHog:a=!0}=e===void 0?{}:e;return l=>{var u,d,p,h,g;if(!(i==="*"||i.includes(l.level))||!t.__loaded)return l;l.tags||(l.tags={});var v=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());l.tags["PostHog Person URL"]=v,t.sessionRecordingStarted()&&(l.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var x=((u=l.exception)==null?void 0:u.values)||[],b=x.map(S=>Ye({},S,{stacktrace:S.stacktrace?Ye({},S.stacktrace,{type:"raw",frames:(S.stacktrace.frames||[]).map(k=>Ye({},k,{platform:"web:javascript"}))}):void 0})),E={$exception_message:((d=x[0])==null?void 0:d.value)||l.message,$exception_type:(p=x[0])==null?void 0:p.type,$exception_level:l.level,$exception_list:b,$sentry_event_id:l.event_id,$sentry_exception:l.exception,$sentry_exception_message:((h=x[0])==null?void 0:h.value)||l.message,$sentry_exception_type:(g=x[0])==null?void 0:g.type,$sentry_tags:l.tags};return n&&r&&(E.$sentry_url=(s||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+l.event_id),a&&t.exceptions.sendExceptionEvent(E),l}}class woe{constructor(e,n,r,s,i,a){this.name=r9,this.setupOnce=function(l){l(s9(e,{organization:n,projectId:r,prefix:s,severityAllowList:i,sendExceptionsToPostHog:a==null||a}))}}}var Soe=_e!=null&&_e.location?$x(_e.location.hash,"__posthog")||$x(location.hash,"state"):null,VI="_postHogToolbarParams",HI=Lr("[Toolbar]"),Nl=function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t}(Nl||{});class Eoe{constructor(e){this.instance=e}xt(e){Et.ph_toolbar_state=e}St(){var e;return(e=Et.ph_toolbar_state)!==null&&e!==void 0?e:Nl.UNINITIALIZED}maybeLoadToolbar(e,n,r){if(e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),!_e||!Ve)return!1;e=e??_e.location,r=r??_e.history;try{if(!n){try{_e.localStorage.setItem("test","test"),_e.localStorage.removeItem("test")}catch{return!1}n=_e?.localStorage}var s,i=Soe||$x(e.hash,"__posthog")||$x(e.hash,"state"),a=i?RI(()=>JSON.parse(atob(decodeURIComponent(i))))||RI(()=>JSON.parse(decodeURIComponent(i))):null;return a&&a.action==="ph_authorize"?((s=a).source="url",s&&Object.keys(s).length>0&&(a.desiredHash?e.hash=a.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((s=JSON.parse(n.getItem(VI)||"{}")).source="localstorage",delete s.userIntent),!(!s.token||this.instance.config.token!==s.token)&&(this.loadToolbar(s),!0)}catch{return!1}}Et(e){var n=Et.ph_load_toolbar||Et.ph_load_editor;!$n(n)&&ql(n)?n(e,this.instance):HI.warn("No toolbar load function found")}loadToolbar(e){var n=!(Ve==null||!Ve.getElementById(UB));if(!_e||n)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,s=Ye({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(_e.localStorage.setItem(VI,JSON.stringify(Ye({},s,{source:void 0}))),this.St()===Nl.LOADED)this.Et(s);else if(this.St()===Nl.UNINITIALIZED){var i;this.xt(Nl.LOADING),(i=Et.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",a=>{if(a)return HI.error("[Toolbar] Failed to load",a),void this.xt(Nl.UNINITIALIZED);this.xt(Nl.LOADED),this.Et(s)}),Ar(_e,"turbolinks:load",()=>{this.xt(Nl.UNINITIALIZED),this.loadToolbar(s)})}return!0}$t(e){return this.loadToolbar(e)}maybeLoadEditor(e,n,r){return e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,n,r)}}var koe=Lr("[TracingHeaders]");class Toe{constructor(e){this.kt=void 0,this.Pt=void 0,this.lt=()=>{var n,r;Be(this.kt)&&((n=Et.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),Be(this.Pt)&&((r=Et.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}nt(e){var n,r;(n=Et.__PosthogExtensions__)!=null&&n.tracingHeadersPatchFns&&e(),(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",s=>{if(s)return koe.error("failed to load script",s);e()})}startIfEnabledOrStop(){var e,n;this._instance.config.__add_tracing_headers?this.nt(this.lt):((e=this.kt)==null||e.call(this),(n=this.Pt)==null||n.call(this),this.kt=void 0,this.Pt=void 0)}}var ji="Mobile",zx="iOS",Ra="Android",Rm="Tablet",i9=Ra+" "+Rm,a9="iPad",o9="Apple",l9=o9+" Watch",jm="Safari",Sf="BlackBerry",c9="Samsung",u9=c9+"Browser",d9=c9+" Internet",_u="Chrome",Coe=_u+" OS",f9=_u+" "+zx,lN="Internet Explorer",h9=lN+" "+ji,cN="Opera",Aoe=cN+" Mini",uN="Edge",p9="Microsoft "+uN,uf="Firefox",m9=uf+" "+zx,Mm="Nintendo",Om="PlayStation",df="Xbox",g9=Ra+" "+ji,v9=ji+" "+jm,Lp="Windows",Wk=Lp+" Phone",GI="Nokia",Yk="Ouya",y9="Generic",Noe=y9+" "+ji.toLowerCase(),x9=y9+" "+Rm.toLowerCase(),Kk="Konqueror",ds="(\\d+(\\.\\d+)?)",BS=new RegExp("Version/"+ds),Roe=new RegExp(df,"i"),joe=new RegExp(Om+" \\w+","i"),Moe=new RegExp(Mm+" \\w+","i"),dN=new RegExp(Sf+"|PlayBook|BB10","i"),Ooe={"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"},Poe=(t,e)=>e&&Ht(e,o9)||function(n){return Ht(n,jm)&&!Ht(n,_u)&&!Ht(n,Ra)}(t),b9=function(t,e){return e=e||"",Ht(t," OPR/")&&Ht(t,"Mini")?Aoe:Ht(t," OPR/")?cN:dN.test(t)?Sf:Ht(t,"IE"+ji)||Ht(t,"WPDesktop")?h9:Ht(t,u9)?d9:Ht(t,uN)||Ht(t,"Edg/")?p9:Ht(t,"FBIOS")?"Facebook "+ji:Ht(t,"UCWEB")||Ht(t,"UCBrowser")?"UC Browser":Ht(t,"CriOS")?f9:Ht(t,"CrMo")||Ht(t,_u)?_u:Ht(t,Ra)&&Ht(t,jm)?g9:Ht(t,"FxiOS")?m9:Ht(t.toLowerCase(),Kk.toLowerCase())?Kk:Poe(t,e)?Ht(t,ji)?v9:jm:Ht(t,uf)?uf:Ht(t,"MSIE")||Ht(t,"Trident/")?lN:Ht(t,"Gecko")?uf:""},Ioe={[h9]:[new RegExp("rv:"+ds)],[p9]:[new RegExp(uN+"?\\/"+ds)],[_u]:[new RegExp("("+_u+"|CrMo)\\/"+ds)],[f9]:[new RegExp("CriOS\\/"+ds)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+ds)],[jm]:[BS],[v9]:[BS],[cN]:[new RegExp("(Opera|OPR)\\/"+ds)],[uf]:[new RegExp(uf+"\\/"+ds)],[m9]:[new RegExp("FxiOS\\/"+ds)],[Kk]:[new RegExp("Konqueror[:/]?"+ds,"i")],[Sf]:[new RegExp(Sf+" "+ds),BS],[g9]:[new RegExp("android\\s"+ds,"i")],[d9]:[new RegExp(u9+"\\/"+ds)],[lN]:[new RegExp("(rv:|MSIE )"+ds)],Mozilla:[new RegExp("rv:"+ds)]},Doe=function(t,e){var n=b9(t,e),r=Ioe[n];if(Be(r))return null;for(var s=0;s<r.length;s++){var i=r[s],a=t.match(i);if(a)return parseFloat(a[a.length-2])}return null},WI=[[new RegExp(df+"; "+df+" (.*?)[);]","i"),t=>[df,t&&t[1]||""]],[new RegExp(Mm,"i"),[Mm,""]],[new RegExp(Om,"i"),[Om,""]],[dN,[Sf,""]],[new RegExp(Lp,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Wk,""];if(new RegExp(ji).test(e)&&!/IEMobile\b/.test(e))return[Lp+" "+ji,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var r=n[1],s=Ooe[r]||"";return/arm/i.test(e)&&(s="RT"),[Lp,s]}return[Lp,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[zx,e.join(".")]}return[zx,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=Be(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Ra+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Ra+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[Ra,e.join(".")]}return[Ra,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Coe,""]],[/Linux|debian/i,["Linux",""]]],YI=function(t){return Moe.test(t)?Mm:joe.test(t)?Om:Roe.test(t)?df:new RegExp(Yk,"i").test(t)?Yk:new RegExp("("+Wk+"|WPDesktop)","i").test(t)?Wk:/iPad/.test(t)?a9:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?l9:dN.test(t)?Sf:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(GI,"i").test(t)?GI:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?!new RegExp(ji).test(t)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)?/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Ra:i9:Ra:new RegExp("(pda|"+ji+")","i").test(t)?Noe:new RegExp(Rm,"i").test(t)&&!new RegExp(Rm+" pc","i").test(t)?x9:""},oy="https?://(.*)",th=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Loe=eh(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],th),vg="<masked>",$oe=["li_fat_id"];function _9(t,e,n){if(!Ve)return{};var r,s=e?eh([],th,n||[]):[],i=w9(gg(Ve.URL,s,vg),t),a=(r={},Cn($oe,function(l){var u=$a.J(l);r[l]=u||null}),r);return lr(a,i)}function w9(t,e){var n=Loe.concat(e||[]),r={};return Cn(n,function(s){var i=Lx(t,s);r[s]=i||null}),r}function S9(t){var e=function(i){return i?i.search(oy+"google.([^/?]*)")===0?"google":i.search(oy+"bing.com")===0?"bing":i.search(oy+"yahoo.com")===0?"yahoo":i.search(oy+"duckduckgo.com")===0?"duckduckgo":null:null}(t),n=e!="yahoo"?"q":"p",r={};if(!Xo(e)){r.$search_engine=e;var s=Ve?Lx(Ve.referrer,n):"";s.length&&(r.ph_keyword=s)}return r}function KI(){return navigator.language||navigator.userLanguage}function E9(){return Ve?.referrer||"$direct"}function k9(t,e){var n=t?eh([],th,e||[]):[],r=Ms?.href.substring(0,1e3);return{r:E9().substring(0,1e3),u:r?gg(r,n,vg):void 0}}function T9(t){var e,{r:n,u:r}=t,s={$referrer:n,$referring_domain:n==null?void 0:n=="$direct"?"$direct":(e=Dx(n))==null?void 0:e.host};if(r){s.$current_url=r;var i=Dx(r);s.$host=i?.host,s.$pathname=i?.pathname;var a=w9(r);lr(s,a)}if(n){var l=S9(n);lr(s,l)}return s}function C9(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function zoe(){try{return new Date().getTimezoneOffset()}catch{return}}function Foe(t,e){if(!js)return{};var n,r,s,i=t?eh([],th,e||[]):[],[a,l]=function(u){for(var d=0;d<WI.length;d++){var[p,h]=WI[d],g=p.exec(u),v=g&&(ql(h)?h(g,u):h);if(v)return v}return["",""]}(js);return lr(sN({$os:a,$os_version:l,$browser:b9(js,navigator.vendor),$device:YI(js),$device_type:(r=js,s=YI(r),s===a9||s===i9||s==="Kobo"||s==="Kindle Fire"||s===x9?Rm:s===Mm||s===df||s===Om||s===Yk?"Console":s===l9?"Wearable":s?ji:"Desktop"),$timezone:C9(),$timezone_offset:zoe()}),{$current_url:gg(Ms?.href,i,vg),$host:Ms?.host,$pathname:Ms?.pathname,$raw_user_agent:js.length>1e3?js.substring(0,997)+"...":js,$browser_version:Doe(js,navigator.vendor),$browser_language:KI(),$browser_language_prefix:(n=KI(),typeof n=="string"?n.split("-")[0]:void 0),$screen_height:_e?.screen.height,$screen_width:_e?.screen.width,$viewport_height:_e?.innerHeight,$viewport_width:_e?.innerWidth,$lib:"web",$lib_version:wo.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var wl=Lr("[Web Vitals]"),XI=9e5;class Uoe{constructor(e){var n;this.Tt=!1,this.C=!1,this.q={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.It=()=>{clearTimeout(this.Rt),this.q.metrics.length!==0&&(this._instance.capture("$web_vitals",this.q.metrics.reduce((r,s)=>Ye({},r,{["$web_vitals_"+s.name+"_event"]:Ye({},s),["$web_vitals_"+s.name+"_value"]:s.value}),{})),this.q={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.Ct=r=>{var s,i=(s=this._instance.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0);if(Be(i))wl.error("Could not read session ID. Dropping metrics!");else{this.q=this.q||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var a=this.Ot();Be(a)||($n(r?.name)||$n(r?.value)?wl.error("Invalid metric received",r):this.Ft&&r.value>=this.Ft?wl.error("Ignoring metric with value >= "+this.Ft,r):(this.q.url!==a&&(this.It(),this.Rt=setTimeout(this.It,this.flushToCaptureTimeoutMs)),Be(this.q.url)&&(this.q.url=a),this.q.firstMetricTimestamp=Be(this.q.firstMetricTimestamp)?Date.now():this.q.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.q.metrics.push(Ye({},r,{$current_url:a,$session_id:i.sessionId,$window_id:i.windowId,timestamp:Date.now()})),this.q.metrics.length===this.allowedMetrics.length&&this.It()))}},this.lt=()=>{var r,s,i,a,l=Et.__PosthogExtensions__;Be(l)||Be(l.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:s,onFCP:i,onINP:a}=l.postHogWebVitalsCallbacks),r&&s&&i&&a?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.Ct.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&s(this.Ct.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&i(this.Ct.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&a(this.Ct.bind(this)),this.C=!0):wl.error("web vitals callbacks not loaded - not starting")},this._instance=e,this.Tt=!((n=this._instance.persistence)==null||!n.props[PI]),this.startIfEnabled()}get allowedMetrics(){var e,n,r=rs(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return Be(r)?((n=this._instance.persistence)==null?void 0:n.props[II])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(rs(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get Ft(){var e=rs(this._instance.config.capture_performance)&&Wa(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:XI;return 0<e&&e<=6e4?XI:e}get isEnabled(){var e=Ms?.protocol;if(e!=="http:"&&e!=="https:")return wl.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=rs(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:Vl(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return Vl(n)?n:this.Tt}startIfEnabled(){this.isEnabled&&!this.C&&(wl.info("enabled, starting..."),this.nt(this.lt))}onRemoteConfig(e){var n=rs(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=rs(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[PI]:n}),this._instance.persistence.register({[II]:r})),this.Tt=n,this.startIfEnabled()}nt(e){var n,r;(n=Et.__PosthogExtensions__)!=null&&n.postHogWebVitalsCallbacks&&e(),(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"web-vitals",s=>{s?wl.error("failed to load script",s):e()})}Ot(){var e=_e?_e.location.href:void 0;if(e){var n=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,s=n?eh([],th,r||[]):[];return gg(e,s,vg)}wl.error("Could not determine current URL")}}var Boe=Lr("[Heatmaps]");function QI(t){return rs(t)&&"clientX"in t&&"clientY"in t&&Wa(t.clientX)&&Wa(t.clientY)}class qoe{constructor(e){var n;this.rageclicks=new e9,this.Tt=!1,this.C=!1,this.Mt=null,this.instance=e,this.Tt=!((n=this.instance.persistence)==null||!n.props[Lk])}get flushIntervalMilliseconds(){var e=5e3;return rs(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return Be(this.instance.config.capture_heatmaps)?Be(this.instance.config.enable_heatmaps)?this.Tt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.C)return;Boe.info("starting..."),this.At(),this.Mt=setInterval(this.jt.bind(this),this.flushIntervalMilliseconds)}else{var e,n;clearInterval((e=this.Mt)!==null&&e!==void 0?e:void 0),(n=this.Dt)==null||n.stop(),this.getAndClearBuffer()}}onRemoteConfig(e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Lk]:n}),this.Tt=n,this.startIfEnabled()}getAndClearBuffer(){var e=this.q;return this.q=void 0,e}Lt(e){this.Nt(e.originalEvent,"deadclick")}At(){_e&&Ve&&(Ar(_e,"beforeunload",this.jt.bind(this)),Ar(Ve,"click",e=>this.Nt(e||_e?.event),{capture:!0}),Ar(Ve,"mousemove",e=>this.Ut(e||_e?.event),{capture:!0}),this.Dt=new n9(this.instance,voe,this.Lt.bind(this)),this.Dt.startIfEnabled(),this.C=!0)}zt(e,n){var r=this.instance.scrollManager.scrollY(),s=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),a=function(l,u,d){for(var p=l;p&&b0(p)&&!Gl(p,"body");){if(p===d)return!1;if(Ht(u,_e?.getComputedStyle(p).position))return!0;p=WB(p)}return!1}(HB(e),["fixed","sticky"],i);return{x:e.clientX+(a?0:s),y:e.clientY+(a?0:r),target_fixed:a,type:n}}Nt(e,n){var r;if(n===void 0&&(n="click"),!DI(e.target)&&QI(e)){var s=this.zt(e,n);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Ht(Ye({},s,{type:"rageclick"})),this.Ht(s)}}Ut(e){!DI(e.target)&&QI(e)&&(clearTimeout(this.Bt),this.Bt=setTimeout(()=>{this.Ht(this.zt(e,"mousemove"))},500))}Ht(e){if(_e){var n=_e.location.href,r=this.instance.config.mask_personal_data_properties,s=this.instance.config.custom_personal_data_properties,i=r?eh([],th,s||[]):[],a=gg(n,i,vg);this.q=this.q||{},this.q[a]||(this.q[a]=[]),this.q[a].push(e)}}jt(){this.q&&!Vd(this.q)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class Voe{constructor(e){this._instance=e}doPageView(e,n){var r,s=this.qt(e,n);return this.Wt={pathname:(r=_e?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),s}doPageLeave(e){var n;return this.qt(e,(n=this.Wt)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Wt)==null?void 0:e.pageViewId}}qt(e,n){var r=this.Wt;if(!r)return{$pageview_id:n};var s={$pageview_id:n,$prev_pageview_id:r.pageViewId},i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:a,lastScrollY:l,maxScrollY:u,maxContentHeight:d,lastContentY:p,maxContentY:h}=i;if(!(Be(a)||Be(l)||Be(u)||Be(d)||Be(p)||Be(h))){a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),d=Math.ceil(d),p=Math.ceil(p),h=Math.ceil(h);var g=a<=1?1:Na(l/a,0,1,qe),v=a<=1?1:Na(u/a,0,1,qe),x=d<=1?1:Na(p/d,0,1,qe),b=d<=1?1:Na(h/d,0,1,qe);s=lr(s,{$prev_pageview_last_scroll:l,$prev_pageview_last_scroll_percentage:g,$prev_pageview_max_scroll:u,$prev_pageview_max_scroll_percentage:v,$prev_pageview_last_content:p,$prev_pageview_last_content_percentage:x,$prev_pageview_max_content:h,$prev_pageview_max_content_percentage:b})}}return r.pathname&&(s.$prev_pageview_pathname=r.pathname),r.timestamp&&(s.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),s}}var Mi=Uint8Array,Ps=Uint16Array,Ef=Uint32Array,fN=new Mi([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]),hN=new Mi([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]),JI=new Mi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),A9=function(t,e){for(var n=new Ps(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];var s=new Ef(n[30]);for(r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)s[i]=i-n[r]<<5|r;return[n,s]},N9=A9(fN,2),Hoe=N9[0],Xk=N9[1];Hoe[28]=258,Xk[258]=28;for(var ZI=A9(hN,0)[1],R9=new Ps(32768),Rn=0;Rn<32768;++Rn){var zc=(43690&Rn)>>>1|(21845&Rn)<<1;zc=(61680&(zc=(52428&zc)>>>2|(13107&zc)<<2))>>>4|(3855&zc)<<4,R9[Rn]=((65280&zc)>>>8|(255&zc)<<8)>>>1}var Qp=function(t,e,n){for(var r=t.length,s=0,i=new Ps(e);s<r;++s)++i[t[s]-1];var a,l=new Ps(e);for(s=0;s<e;++s)l[s]=l[s-1]+i[s-1]<<1;for(a=new Ps(r),s=0;s<r;++s)a[s]=R9[l[t[s]-1]++]>>>15-t[s];return a},wu=new Mi(288);for(Rn=0;Rn<144;++Rn)wu[Rn]=8;for(Rn=144;Rn<256;++Rn)wu[Rn]=9;for(Rn=256;Rn<280;++Rn)wu[Rn]=7;for(Rn=280;Rn<288;++Rn)wu[Rn]=8;var Fx=new Mi(32);for(Rn=0;Rn<32;++Rn)Fx[Rn]=5;var Goe=Qp(wu,9),Woe=Qp(Fx,5),j9=function(t){return(t/8>>0)+(7&t&&1)},M9=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var r=new(t instanceof Ps?Ps:t instanceof Ef?Ef:Mi)(n-e);return r.set(t.subarray(e,n)),r},yo=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8},vp=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8,t[r+2]|=n>>>16},qS=function(t,e){for(var n=[],r=0;r<t.length;++r)t[r]&&n.push({s:r,f:t[r]});var s=n.length,i=n.slice();if(!s)return[new Mi(0),0];if(s==1){var a=new Mi(n[0].s+1);return a[n[0].s]=1,[a,1]}n.sort(function(j,A){return j.f-A.f}),n.push({s:-1,f:25001});var l=n[0],u=n[1],d=0,p=1,h=2;for(n[0]={s:-1,f:l.f+u.f,l,r:u};p!=s-1;)l=n[n[d].f<n[h].f?d++:h++],u=n[d!=p&&n[d].f<n[h].f?d++:h++],n[p++]={s:-1,f:l.f+u.f,l,r:u};var g=i[0].s;for(r=1;r<s;++r)i[r].s>g&&(g=i[r].s);var v=new Ps(g+1),x=Qk(n[p-1],v,0);if(x>e){r=0;var b=0,E=x-e,S=1<<E;for(i.sort(function(j,A){return v[A.s]-v[j.s]||j.f-A.f});r<s;++r){var k=i[r].s;if(!(v[k]>e))break;b+=S-(1<<x-v[k]),v[k]=e}for(b>>>=E;b>0;){var T=i[r].s;v[T]<e?b-=1<<e-v[T]++-1:++r}for(;r>=0&&b;--r){var R=i[r].s;v[R]==e&&(--v[R],++b)}x=e}return[new Mi(v),x]},Qk=function(t,e,n){return t.s==-1?Math.max(Qk(t.l,e,n+1),Qk(t.r,e,n+1)):e[t.s]=n},eD=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Ps(++e),r=0,s=t[0],i=1,a=function(u){n[r++]=u},l=1;l<=e;++l)if(t[l]==s&&l!=e)++i;else{if(!s&&i>2){for(;i>138;i-=138)a(32754);i>2&&(a(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(a(s),--i;i>6;i-=6)a(8304);i>2&&(a(i-3<<5|8208),i=0)}for(;i--;)a(s);i=1,s=t[l]}return[n.subarray(0,r),e]},yp=function(t,e){for(var n=0,r=0;r<e.length;++r)n+=t[r]*e[r];return n},Jk=function(t,e,n){var r=n.length,s=j9(e+2);t[s]=255&r,t[s+1]=r>>>8,t[s+2]=255^t[s],t[s+3]=255^t[s+1];for(var i=0;i<r;++i)t[s+i+4]=n[i];return 8*(s+4+r)},tD=function(t,e,n,r,s,i,a,l,u,d,p){yo(e,p++,n),++s[256];for(var h=qS(s,15),g=h[0],v=h[1],x=qS(i,15),b=x[0],E=x[1],S=eD(g),k=S[0],T=S[1],R=eD(b),j=R[0],A=R[1],N=new Ps(19),M=0;M<k.length;++M)N[31&k[M]]++;for(M=0;M<j.length;++M)N[31&j[M]]++;for(var I=qS(N,7),O=I[0],L=I[1],z=19;z>4&&!O[JI[z-1]];--z);var H,V,X,F,W=d+5<<3,G=yp(s,wu)+yp(i,Fx)+a,ee=yp(s,g)+yp(i,b)+a+14+3*z+yp(N,O)+(2*N[16]+3*N[17]+7*N[18]);if(W<=G&&W<=ee)return Jk(e,p,t.subarray(u,u+d));if(yo(e,p,1+(ee<G)),p+=2,ee<G){H=Qp(g,v),V=g,X=Qp(b,E),F=b;var P=Qp(O,L);for(yo(e,p,T-257),yo(e,p+5,A-1),yo(e,p+10,z-4),p+=14,M=0;M<z;++M)yo(e,p+3*M,O[JI[M]]);p+=3*z;for(var ie=[k,j],ue=0;ue<2;++ue){var D=ie[ue];for(M=0;M<D.length;++M){var ne=31&D[M];yo(e,p,P[ne]),p+=O[ne],ne>15&&(yo(e,p,D[M]>>>5&127),p+=D[M]>>>12)}}}else H=Goe,V=wu,X=Woe,F=Fx;for(M=0;M<l;++M)if(r[M]>255){ne=r[M]>>>18&31,vp(e,p,H[ne+257]),p+=V[ne+257],ne>7&&(yo(e,p,r[M]>>>23&31),p+=fN[ne]);var fe=31&r[M];vp(e,p,X[fe]),p+=F[fe],fe>3&&(vp(e,p,r[M]>>>5&8191),p+=hN[fe])}else vp(e,p,H[r[M]]),p+=V[r[M]];return vp(e,p,H[256]),p+V[256]},Yoe=new Ef([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Koe=function(){for(var t=new Ef(256),e=0;e<256;++e){for(var n=e,r=9;--r;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t}(),Xoe=function(t,e,n,r,s){return function(i,a,l,u,d,p){var h=i.length,g=new Mi(u+h+5*(1+Math.floor(h/7e3))+d),v=g.subarray(u,g.length-d),x=0;if(!a||h<8)for(var b=0;b<=h;b+=65535){var E=b+65535;E<h?x=Jk(v,x,i.subarray(b,E)):(v[b]=p,x=Jk(v,x,i.subarray(b,h)))}else{for(var S=Yoe[a-1],k=S>>>13,T=8191&S,R=(1<<l)-1,j=new Ps(32768),A=new Ps(R+1),N=Math.ceil(l/3),M=2*N,I=function(Ae){return(i[Ae]^i[Ae+1]<<N^i[Ae+2]<<M)&R},O=new Ef(25e3),L=new Ps(288),z=new Ps(32),H=0,V=0,X=(b=0,0),F=0,W=0;b<h;++b){var G=I(b),ee=32767&b,P=A[G];if(j[ee]=P,A[G]=ee,F<=b){var ie=h-b;if((H>7e3||X>24576)&&ie>423){x=tD(i,v,0,O,L,z,V,X,W,b-W,x),X=H=V=0,W=b;for(var ue=0;ue<286;++ue)L[ue]=0;for(ue=0;ue<30;++ue)z[ue]=0}var D=2,ne=0,fe=T,q=ee-P&32767;if(ie>2&&G==I(b-q))for(var K=Math.min(k,ie)-1,Y=Math.min(32767,b),Z=Math.min(258,ie);q<=Y&&--fe&&ee!=P;){if(i[b+D]==i[b+D-q]){for(var U=0;U<Z&&i[b+U]==i[b+U-q];++U);if(U>D){if(D=U,ne=q,U>K)break;var J=Math.min(q,U-2),oe=0;for(ue=0;ue<J;++ue){var pe=b-q+ue+32768&32767,ye=pe-j[pe]+32768&32767;ye>oe&&(oe=ye,P=pe)}}}q+=(ee=P)-(P=j[ee])+32768&32767}if(ne){O[X++]=268435456|Xk[D]<<18|ZI[ne];var je=31&Xk[D],Ne=31&ZI[ne];V+=fN[je]+hN[Ne],++L[257+je],++z[Ne],F=b+D,++H}else O[X++]=i[b],++L[i[b]]}}x=tD(i,v,p,O,L,z,V,X,W,b-W,x)}return M9(g,0,u+j9(x)+d)}(t,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,n,r,!0)},VS=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function Qoe(t,e){e===void 0&&(e={});var n=function(){var l=4294967295;return{p:function(u){for(var d=l,p=0;p<u.length;++p)d=Koe[255&d^u[p]]^d>>>8;l=d},d:function(){return 4294967295^l}}}(),r=t.length;n.p(t);var s,i=Xoe(t,e,10+((s=e).filename&&s.filename.length+1||0),8),a=i.length;return function(l,u){var d=u.filename;if(l[0]=31,l[1]=139,l[2]=8,l[8]=u.level<2?4:u.level==9?2:0,l[9]=3,u.mtime!=0&&VS(l,4,Math.floor(new Date(u.mtime||Date.now())/1e3)),d){l[3]=8;for(var p=0;p<=d.length;++p)l[p+10]=d.charCodeAt(p)}}(i,e),VS(i,a-8,n.d()),VS(i,a-4,r),i}var Joe=function(t){var e,n,r,s,i="";for(e=n=0,r=(t=(t+"").replace(/\r\n/g,`
444
444
  `).replace(/\r/g,`
445
445
  `)).length,s=0;s<r;s++){var a=t.charCodeAt(s),l=null;a<128?n++:l=a>127&&a<2048?String.fromCharCode(a>>6|192,63&a|128):String.fromCharCode(a>>12|224,a>>6&63|128,63&a|128),Xo(l)||(n>e&&(i+=t.substring(e,n)),i+=l,e=n=s+1)}return n>e&&(i+=t.substring(e,t.length)),i},Zoe=!!Mk||!!jk,nD="text/plain",Ux=(t,e)=>{var[n,r]=t.split("?"),s=Ye({},e);r?.split("&").forEach(a=>{var[l]=a.split("=");delete s[l]});var i=roe(s);return n+"?"+(i=i?(r?r+"&":"")+i:r)},$p=(t,e)=>JSON.stringify(t,(n,r)=>typeof r=="bigint"?r.toString():r,e),HS=t=>{var{data:e,compression:n}=t;if(e){if(n===Ao.GZipJS){var r=Qoe(function(u,d){var p=u.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(u);for(var h=new Mi(u.length+(u.length>>>1)),g=0,v=function(S){h[g++]=S},x=0;x<p;++x){if(g+5>h.length){var b=new Mi(g+8+(p-x<<1));b.set(h),h=b}var E=u.charCodeAt(x);E<128||d?v(E):E<2048?(v(192|E>>>6),v(128|63&E)):E>55295&&E<57344?(v(240|(E=65536+(1047552&E)|1023&u.charCodeAt(++x))>>>18),v(128|E>>>12&63),v(128|E>>>6&63),v(128|63&E)):(v(224|E>>>12),v(128|E>>>6&63),v(128|63&E))}return M9(h,0,g)}($p(e)),{mtime:0}),s=new Blob([r],{type:nD});return{contentType:nD,body:s,estimatedSize:s.size}}if(n===Ao.Base64){var i=function(u){var d,p,h,g,v,x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,E=0,S="",k=[];if(!u)return u;u=Joe(u);do d=(v=u.charCodeAt(b++)<<16|u.charCodeAt(b++)<<8|u.charCodeAt(b++))>>18&63,p=v>>12&63,h=v>>6&63,g=63&v,k[E++]=x.charAt(d)+x.charAt(p)+x.charAt(h)+x.charAt(g);while(b<u.length);switch(S=k.join(""),u.length%3){case 1:S=S.slice(0,-2)+"==";break;case 2:S=S.slice(0,-1)+"="}return S}($p(e)),a=(u=>"data="+encodeURIComponent(typeof u=="string"?u:$p(u)))(i);return{contentType:"application/x-www-form-urlencoded",body:a,estimatedSize:new Blob([a]).size}}var l=$p(e);return{contentType:"application/json",body:l,estimatedSize:new Blob([l]).size}}},Yy=[];jk&&Yy.push({transport:"fetch",method:t=>{var e,n,{contentType:r,body:s,estimatedSize:i}=(e=HS(t))!==null&&e!==void 0?e:{},a=new Headers;Cn(t.headers,function(p,h){a.append(h,p)}),r&&a.append("Content-Type",r);var l=t.url,u=null;if(SI){var d=new SI;u={signal:d.signal,timeout:setTimeout(()=>d.abort(),t.timeout)}}jk(l,Ye({method:t?.method||"GET",headers:a,keepalive:t.method==="POST"&&(i||0)<52428.8,body:s,signal:(n=u)==null?void 0:n.signal},t.fetchOptions)).then(p=>p.text().then(h=>{var g={statusCode:p.status,text:h};if(p.status===200)try{g.json=JSON.parse(h)}catch(v){qe.error(v)}t.callback==null||t.callback(g)})).catch(p=>{qe.error(p),t.callback==null||t.callback({statusCode:0,text:p})}).finally(()=>u?clearTimeout(u.timeout):null)}}),Mk&&Yy.push({transport:"XHR",method:t=>{var e,n=new Mk;n.open(t.method||"GET",t.url,!0);var{contentType:r,body:s}=(e=HS(t))!==null&&e!==void 0?e:{};Cn(t.headers,function(i,a){n.setRequestHeader(a,i)}),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var i={statusCode:n.status,text:n.responseText};if(n.status===200)try{i.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(i)}},n.send(s)}}),ii!=null&&ii.sendBeacon&&Yy.push({transport:"sendBeacon",method:t=>{var e=Ux(t.url,{beacon:"1"});try{var n,{contentType:r,body:s}=(n=HS(t))!==null&&n!==void 0?n:{},i=typeof s=="string"?new Blob([s],{type:r}):s;ii.sendBeacon(e,i)}catch{}}});var kf=function(t,e){if(!function(n){try{new RegExp(n)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function rD(t,e,n){return $p({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var O9={exact:(t,e)=>e.some(n=>t.some(r=>n===r)),is_not:(t,e)=>e.every(n=>t.every(r=>n!==r)),regex:(t,e)=>e.some(n=>t.some(r=>kf(n,r))),not_regex:(t,e)=>e.every(n=>t.every(r=>!kf(n,r))),icontains:(t,e)=>e.map(ly).some(n=>t.map(ly).some(r=>n.includes(r))),not_icontains:(t,e)=>e.map(ly).every(n=>t.map(ly).every(r=>!n.includes(r)))},ly=t=>t.toLowerCase(),sD=Lr("[Error tracking]");let ele=class{constructor(e){var n,r;this.Gt=[],this.Vt=new Oae([new Pae,new qae,new Dae,new Iae,new Uae,new Fae,new $ae,new Bae],[Aae,jae]),this._instance=e,this.Gt=(n=(r=this._instance.persistence)==null?void 0:r.get_property($k))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,r,s,i=(n=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&n!==void 0?n:[],a=(s=e.errorTracking)==null?void 0:s.captureExtensionExceptions;this.Gt=i,this._instance.persistence&&this._instance.persistence.register({[$k]:this.Gt,[OI]:a})}get Jt(){var e,n=!!this._instance.get_property(OI),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.Vt.buildFromUnknown(e,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(e){if(this.Kt(e))sD.info("Skipping exception capture because a suppression rule matched");else{if(this.Jt||!this.Yt(e))return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"});sD.info("Skipping exception capture because it was thrown by an extension")}}Kt(e){var n=e.$exception_list;if(!n||!An(n)||n.length===0)return!1;var r=n.reduce((s,i)=>{var{type:a,value:l}=i;return Cr(a)&&a.length>0&&s.$exception_types.push(a),Cr(l)&&l.length>0&&s.$exception_values.push(l),s},{$exception_types:[],$exception_values:[]});return this.Gt.some(s=>{var i=s.values.map(a=>{var l,u=O9[a.operator],d=An(a.value)?a.value:[a.value],p=(l=r[a.key])!==null&&l!==void 0?l:[];return d.length>0&&u(d,p)});return s.type==="OR"?i.some(Boolean):i.every(Boolean)})}Yt(e){var n=e.$exception_list;return!(!n||!An(n))&&n.flatMap(r=>{var s,i;return(s=(i=r.stacktrace)==null?void 0:i.frames)!==null&&s!==void 0?s:[]}).some(r=>r.filename&&r.filename.startsWith("chrome-extension://"))}};var Yi=Lr("[FeatureFlags]"),GS="$active_feature_flags",Ed="$override_feature_flags",iD="$feature_flag_payloads",xp="$override_feature_flag_payloads",aD="$feature_flag_request_id",oD=t=>{var e={};for(var[n,r]of Wy(t||{}))r&&(e[n]=r);return e},tle=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map(n=>{var r;return[n,(r=e[n].variant)!==null&&r!==void 0?r:e[n].enabled]})),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter(n=>e[n].enabled).filter(n=>{var r;return(r=e[n].metadata)==null?void 0:r.payload}).map(n=>{var r;return[n,(r=e[n].metadata)==null?void 0:r.payload]}))):Yi.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},nle=function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t}({});class rle{constructor(e){this.Xt=!1,this.Qt=!1,this.Zt=!1,this.ti=!1,this.ii=!1,this.ei=!1,this.ri=!1,this._instance=e,this.featureFlagEventHandlers=[]}si(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter(n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||Yi.error("Invalid evaluation environment found:",n,"Expected non-empty string"),r}):[]}ni(){return this.si().length>0}flags(){if(this._instance.config.__preview_remote_config)this.ei=!0;else{var e=!this.oi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.ai({disableFlags:e})}}get hasLoadedFlags(){return this.Qt}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(zk),n=this._instance.get_property(Ed),r=this._instance.get_property(xp);if(!r&&!n)return e||{};var s=lr({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(n||{})])];for(var a of i){var l,u,d=s[a],p=n?.[a],h=Be(p)?(l=d?.enabled)!==null&&l!==void 0&&l:!!p,g=Be(p)?d.variant:typeof p=="string"?p:void 0,v=r?.[a],x=Ye({},d,{enabled:h,variant:h?g??d?.variant:void 0});h!==d?.enabled&&(x.original_enabled=d?.enabled),g!==d?.variant&&(x.original_variant=d?.variant),v&&(x.metadata=Ye({},d?.metadata,{payload:v,original_payload:d==null||(u=d.metadata)==null?void 0:u.payload})),s[a]=x}return this.Xt||(Yi.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:s}),this.Xt=!0),s}getFlagVariants(){var e=this._instance.get_property(Hd),n=this._instance.get_property(Ed);if(!n)return e||{};for(var r=lr({},e),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.Xt||(Yi.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:r}),this.Xt=!0),r}getFlagPayloads(){var e=this._instance.get_property(iD),n=this._instance.get_property(xp);if(!n)return e||{};for(var r=lr({},e||{}),s=Object.keys(n),i=0;i<s.length;i++)r[s[i]]=n[s[i]];return this.Xt||(Yi.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:r}),this.Xt=!0),r}reloadFeatureFlags(){this.ti||this._instance.config.advanced_disable_feature_flags||this.oi||(this.oi=setTimeout(()=>{this.ai()},5))}li(){clearTimeout(this.oi),this.oi=void 0}ensureFlagsLoaded(){this.Qt||this.Zt||this.oi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.ti=e}ai(e){var n;if(this.li(),!this._instance.L())if(this.Zt)this.ii=!0;else{var r={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:Ye({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(Dp)||{}),group_properties:this._instance.get_property(Gc)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(r.disable_flags=!0),this.ni()&&(r.evaluation_environments=this.si());var s=this._instance.config.__preview_remote_config,i=s?"/flags/?v=2":"/flags/?v=2&config=true",a=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",l=this._instance.requestRouter.endpointFor("api",i+a);s&&(r.timezone=C9()),this.Zt=!0,this._instance.ui({method:"POST",url:l,data:r,compression:this._instance.config.disable_compression?void 0:Ao.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:u=>{var d,p,h=!0;if(u.statusCode===200&&(this.ii||(this.$anon_distinct_id=void 0),h=!1),this.Zt=!1,this.ei||(this.ei=!0,this._instance.hi((p=u.json)!==null&&p!==void 0?p:{})),!r.disable_flags||this.ii)if(this.ri=!h,u.json&&(d=u.json.quotaLimited)!=null&&d.includes(nle.FeatureFlags))Yi.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var g;r.disable_flags||this.receivedFeatureFlags((g=u.json)!==null&&g!==void 0?g:{},h),this.ii&&(this.ii=!1,this.ai())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.Qt||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[e],s=""+r,i=this._instance.get_property(aD)||void 0,a=this._instance.get_property(Mx)||{};if((n.send_event||!("send_event"in n))&&(!(e in a)||!a[e].includes(s))){var l,u,d,p,h,g,v,x,b;An(a[e])?a[e].push(s):a[e]=[s],(l=this._instance.persistence)==null||l.register({[Mx]:a});var E=this.getFeatureFlagDetails(e),S={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:i,$feature_flag_bootstrapped_response:((u=this._instance.config.bootstrap)==null||(u=u.featureFlags)==null?void 0:u[e])||null,$feature_flag_bootstrapped_payload:((d=this._instance.config.bootstrap)==null||(d=d.featureFlagPayloads)==null?void 0:d[e])||null,$used_bootstrap_value:!this.ri};Be(E==null||(p=E.metadata)==null?void 0:p.version)||(S.$feature_flag_version=E.metadata.version);var k,T=(h=E==null||(g=E.reason)==null?void 0:g.description)!==null&&h!==void 0?h:E==null||(v=E.reason)==null?void 0:v.code;T&&(S.$feature_flag_reason=T),E!=null&&(x=E.metadata)!=null&&x.id&&(S.$feature_flag_id=E.metadata.id),Be(E?.original_variant)&&Be(E?.original_enabled)||(S.$feature_flag_original_response=Be(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(b=E.metadata)!=null&&b.original_payload&&(S.$feature_flag_original_payload=E==null||(k=E.metadata)==null?void 0:k.original_payload),this._instance.capture("$feature_flag_called",S)}return r}Yi.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,n){var r=this._instance.config.token,s={distinct_id:this._instance.get_distinct_id(),token:r};this.ni()&&(s.evaluation_environments=this.si()),this._instance.ui({method:"POST",url:this._instance.requestRouter.endpointFor("api","/flags/?v=2&config=true"),data:s,compression:this._instance.config.disable_compression?void 0:Ao.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:i=>{var a,l=(a=i.json)==null?void 0:a.featureFlagPayloads;n(l?.[e]||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.Qt||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,n);return Be(r)?void 0:!!r}Yi.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(n=>n!==e)}receivedFeatureFlags(e,n){if(this._instance.persistence){this.Qt=!0;var r=this.getFlagVariants(),s=this.getFlagPayloads(),i=this.getFlagsWithDetails();(function(a,l,u,d,p){u===void 0&&(u={}),d===void 0&&(d={}),p===void 0&&(p={});var h=tle(a),g=h.flags,v=h.featureFlags,x=h.featureFlagPayloads;if(v){var b=a.requestId;if(An(v)){Yi.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var E={};if(v)for(var S=0;S<v.length;S++)E[v[S]]=!0;l&&l.register({[GS]:v,[Hd]:E})}else{var k=v,T=x,R=g;a.errorsWhileComputingFlags&&(k=Ye({},u,k),T=Ye({},d,T),R=Ye({},p,R)),l&&l.register(Ye({[GS]:Object.keys(oD(k)),[Hd]:k||{},[iD]:T||{},[zk]:R||{}},b?{[aD]:b}:{}))}}})(e,this._instance.persistence,r,s,i),this.di(n)}}override(e,n){n===void 0&&(n=!1),Yi.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Yi.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Ed),this._instance.persistence.unregister(xp),void this.di();if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.Xt=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(Ed);else if(r.flags)if(An(r.flags)){for(var s={},i=0;i<r.flags.length;i++)s[r.flags[i]]=!0;this._instance.persistence.register({[Ed]:s})}else this._instance.persistence.register({[Ed]:r.flags})}return"payloads"in r&&(r.payloads===!1?this._instance.persistence.unregister(xp):r.payloads&&this._instance.persistence.register({[xp]:r.payloads})),void this.di()}this.di()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.Qt){var{flags:n,flagVariants:r}=this.vi();e(n,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,r){var s,i=(this._instance.get_property(Ip)||[]).find(d=>d.flagKey===e),a={["$feature_enrollment/"+e]:n},l={$feature_flag:e,$feature_enrollment:n,$set:a};i&&(l.$early_access_feature_name=i.name),r&&(l.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",l),this.setPersonPropertiesForFlags(a,!1);var u=Ye({},this.getFlagVariants(),{[e]:n});(s=this._instance.persistence)==null||s.register({[GS]:Object.keys(oD(u)),[Hd]:u}),this.di()}getEarlyAccessFeatures(e,n,r){n===void 0&&(n=!1);var s=this._instance.get_property(Ip),i=r?"&"+r.map(a=>"stage="+a).join("&"):"";if(s&&!n)return e(s);this._instance.ui({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+i),method:"GET",callback:a=>{var l,u;if(a.json){var d=a.json.earlyAccessFeatures;return(l=this._instance.persistence)==null||l.unregister(Ip),(u=this._instance.persistence)==null||u.register({[Ip]:d}),e(d)}}})}vi(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter(r=>n[r]),flagVariants:Object.keys(n).filter(r=>n[r]).reduce((r,s)=>(r[s]=n[s],r),{})}}di(e){var{flags:n,flagVariants:r}=this.vi();this.featureFlagEventHandlers.forEach(s=>s(n,r,{errorsLoading:e}))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Dp)||{};this._instance.register({[Dp]:Ye({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Dp)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Gc)||{};Object.keys(r).length!==0&&Object.keys(r).forEach(s=>{r[s]=Ye({},r[s],e[s]),delete e[s]}),this._instance.register({[Gc]:Ye({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Gc)||{};this._instance.register({[Gc]:Ye({},n,{[e]:{}})})}else this._instance.unregister(Gc)}reset(){this.Qt=!1,this.Zt=!1,this.ti=!1,this.ii=!1,this.ei=!1,this.ri=!1,this.$anon_distinct_id=void 0,this.li(),this.Xt=!1}}var sle=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class WS{constructor(e,n){this.A=e,this.props={},this.ci=!1,this.fi=(r=>{var s="";return r.token&&(s=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+s+"_posthog"})(e),this.it=this.pi(e),this.load(),e.debug&&qe.info("Persistence loaded",e.persistence,Ye({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.gi}pi(e){sle.indexOf(e.persistence.toLowerCase())===-1&&(qe.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&Vn.G()?Vn:n==="localstorage+cookie"&&sy.G()?sy:n==="sessionstorage"&&Wr.G()?Wr:n==="memory"?moe:n==="cookie"?$a:sy.G()?sy:$a}properties(){var e={};return Cn(this.props,function(n,r){if(r===Hd&&rs(n))for(var s=Object.keys(n),i=0;i<s.length;i++)e["$feature/"+s[i]]=n[s[i]];else l=r,u=!1,(Xo(a=Kae)?u:wI&&a.indexOf===wI?a.indexOf(l)!=-1:(Cn(a,function(d){if(u||(u=d===l))return Rx}),u))||(e[r]=n);var a,l,u}),e}load(){if(!this.gi){var e=this.it.K(this.fi);e&&(this.props=lr({},e))}}save(){this.gi||this.it.Y(this.fi,this.props,this.mi,this.yi,this.bi,this.A.debug)}remove(){this.it.X(this.fi,!1),this.it.X(this.fi,!0)}clear(){this.remove(),this.props={}}register_once(e,n,r){if(rs(e)){Be(n)&&(n="None"),this.mi=Be(r)?this.wi:r;var s=!1;if(Cn(e,(i,a)=>{this.props.hasOwnProperty(a)&&this.props[a]!==n||(this.props[a]=i,s=!0)}),s)return this.save(),!0}return!1}register(e,n){if(rs(e)){this.mi=Be(n)?this.wi:n;var r=!1;if(Cn(e,(s,i)=>{e.hasOwnProperty(i)&&this.props[i]!==s&&(this.props[i]=s,r=!0)}),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.ci){var e=_9(this.A.custom_campaign_params,this.A.mask_personal_data_properties,this.A.custom_personal_data_properties);Vd(sN(e))||this.register(e),this.ci=!0}}update_search_keyword(){var e;this.register((e=Ve?.referrer)?S9(e):{})}update_referrer_info(){var e;this.register_once({$referrer:E9(),$referring_domain:Ve!=null&&Ve.referrer&&((e=Dx(Ve.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[qk]||this.props[Vk]||this.register_once({[Ox]:k9(this.A.mask_personal_data_properties,this.A.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Cn([Vk,qk],a=>{var l=this.props[a];l&&Cn(l,function(u,d){e["$initial_"+Ok(d)]=u})});var n,r,s=this.props[Ox];if(s){var i=(n=T9(s),r={},Cn(n,function(a,l){r["$initial_"+Ok(l)]=a}),r);lr(e,i)}return e}safe_merge(e){return Cn(this.props,function(n,r){r in e||(e[r]=n)}),e}update_config(e,n,r){if(this.wi=this.mi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var s=this.pi(e),i=this.props;this.clear(),this.it=s,this.props=i,this.save()}}set_disabled(e){this.gi=e,this.gi?this.remove():this.save()}set_cross_subdomain(e){e!==this.yi&&(this.yi=e,this.remove(),this.save())}set_secure(e){e!==this.bi&&(this.bi=e,this.remove(),this.save())}set_event_timer(e,n){var r=this.props[Pp]||{};r[e]=n,this.props[Pp]=r,this.save()}remove_event_timer(e){var n=(this.props[Pp]||{})[e];return Be(n)||(delete this.props[Pp][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}}(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({});(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({});var YS=function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t}({});(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({});(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({});(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({});var Ky=function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t}({}),lD=function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t}({}),P9=function(t){return t.Popover="popover",t.Inline="inline",t}({});class pN{constructor(){this.xi={},this.xi={}}on(e,n){return this.xi[e]||(this.xi[e]=[]),this.xi[e].push(n),()=>{this.xi[e]=this.xi[e].filter(r=>r!==n)}}emit(e,n){for(var r of this.xi[e]||[])r(n);for(var s of this.xi["*"]||[])s(e,n)}}class Kc{constructor(e){this.Si=new pN,this.Ei=(n,r)=>this.$i(n,r)&&this.ki(n,r)&&this.Pi(n,r),this.$i=(n,r)=>r==null||!r.event||n?.event===r?.event,this._instance=e,this.Ti=new Set,this.Ii=new Set}init(){var e;if(!Be((e=this._instance)==null?void 0:e.Ri)){var n;(n=this._instance)==null||n.Ri((r,s)=>{this.on(r,s)})}}register(e){var n,r;if(!Be((n=this._instance)==null?void 0:n.Ri)&&(e.forEach(a=>{var l,u;(l=this.Ii)==null||l.add(a),(u=a.steps)==null||u.forEach(d=>{var p;(p=this.Ti)==null||p.add(d?.event||"")})}),(r=this._instance)!=null&&r.autocapture)){var s,i=new Set;e.forEach(a=>{var l;(l=a.steps)==null||l.forEach(u=>{u!=null&&u.selector&&i.add(u?.selector)})}),(s=this._instance)==null||s.autocapture.setElementSelectors(i)}}on(e,n){var r;n!=null&&e.length!=0&&(this.Ti.has(e)||this.Ti.has(n?.event))&&this.Ii&&((r=this.Ii)==null?void 0:r.size)>0&&this.Ii.forEach(s=>{this.Ci(n,s)&&this.Si.emit("actionCaptured",s.name)})}Oi(e){this.onAction("actionCaptured",n=>e(n))}Ci(e,n){if(n?.steps==null)return!1;for(var r of n.steps)if(this.Ei(e,r))return!0;return!1}onAction(e,n){return this.Si.on(e,n)}ki(e,n){if(n!=null&&n.url){var r,s=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!s||typeof s!="string"||!Kc.Fi(s,n?.url,n?.url_matching||"contains"))return!1}return!0}static Fi(e,n,r){switch(r){case"regex":return!!_e&&kf(e,n);case"exact":return n===e;case"contains":var s=Kc.Mi(n).replace(/_/g,".").replace(/%/g,".*");return kf(e,s);default:return!1}}static Mi(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}Pi(e,n){if((n!=null&&n.href||n!=null&&n.tag_name||n!=null&&n.text)&&!this.Ai(e).some(i=>!(n!=null&&n.href&&!Kc.Fi(i.href||"",n?.href,n?.href_matching||"exact"))&&(n==null||!n.tag_name||i.tag_name===n?.tag_name)&&!(n!=null&&n.text&&!Kc.Fi(i.text||"",n?.text,n?.text_matching||"exact")&&!Kc.Fi(i.$el_text||"",n?.text,n?.text_matching||"exact"))))return!1;if(n!=null&&n.selector){var r,s=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(!s||!s.includes(n?.selector))return!1}return!0}Ai(e){return e?.properties.$elements==null?[]:e?.properties.$elements}}var vn=Lr("[Surveys]"),Zk="seenSurvey_",ile=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},cD=t=>{var e=""+Zk+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+Zk+t.id+"_"+t.current_iteration),e},ale=[YS.Popover,YS.Widget,YS.API],ole={ignoreConditions:!1,ignoreDelay:!1,displayType:P9.Popover};class lle{constructor(e){this._instance=e,this.ji=new Map,this.Di=new Map}register(e){var n;Be((n=this._instance)==null?void 0:n.Ri)||(this.Li(e),this.Ni(e))}Ni(e){var n=e.filter(r=>{var s,i;return((s=r.conditions)==null?void 0:s.actions)&&((i=r.conditions)==null||(i=i.actions)==null||(i=i.values)==null?void 0:i.length)>0});n.length!==0&&(this.Ui==null&&(this.Ui=new Kc(this._instance),this.Ui.init(),this.Ui.Oi(r=>{this.onAction(r)})),n.forEach(r=>{var s,i,a,l,u;r.conditions&&(s=r.conditions)!=null&&s.actions&&(i=r.conditions)!=null&&(i=i.actions)!=null&&i.values&&((a=r.conditions)==null||(a=a.actions)==null||(a=a.values)==null?void 0:a.length)>0&&((l=this.Ui)==null||l.register(r.conditions.actions.values),(u=r.conditions)==null||(u=u.actions)==null||(u=u.values)==null||u.forEach(d=>{if(d&&d.name){var p=this.Di.get(d.name);p&&p.push(r.id),this.Di.set(d.name,p||[r.id])}}))}))}Li(e){var n;e.filter(r=>{var s,i;return((s=r.conditions)==null?void 0:s.events)&&((i=r.conditions)==null||(i=i.events)==null||(i=i.values)==null?void 0:i.length)>0}).length!==0&&((n=this._instance)==null||n.Ri((r,s)=>{this.onEvent(r,s)}),e.forEach(r=>{var s;(s=r.conditions)==null||(s=s.events)==null||(s=s.values)==null||s.forEach(i=>{if(i&&i.name){var a=this.ji.get(i.name);a&&a.push(r.id),this.ji.set(i.name,a||[r.id])}})}))}onEvent(e,n){var r,s,i=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[ry])||[];if(Ky.SHOWN===e&&n&&i.length>0){var a;vn.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:n,existingActivatedSurveys:i});var l=n==null||(a=n.properties)==null?void 0:a.$survey_id;if(l){var u=i.indexOf(l);u>=0&&(i.splice(u,1),this.zi(i))}}else if(this.ji.has(e)){vn.info("survey event name matched",{event:e,eventPayload:n,surveys:this.ji.get(e)});var d=[];(s=this._instance)==null||s.getSurveys(h=>{d=h.filter(g=>{var v;return(v=this.ji.get(e))==null?void 0:v.includes(g.id)})});var p=d.filter(h=>{var g,v=(g=h.conditions)==null||(g=g.events)==null||(g=g.values)==null?void 0:g.find(x=>x.name===e);return!!v&&(!v.propertyFilters||Object.entries(v.propertyFilters).every(x=>{var b,[E,S]=x,k=n==null||(b=n.properties)==null?void 0:b[E];if(Be(k)||Xo(k))return!1;var T=[String(k)],R=O9[S.operator];return R?R(S.values,T):(vn.warn("Unknown property comparison operator: "+S.operator),!1)}))});this.zi(i.concat(p.map(h=>h.id)||[]))}}onAction(e){var n,r=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[ry])||[];this.Di.has(e)&&this.zi(r.concat(this.Di.get(e)||[]))}zi(e){var n;vn.info("updating activated surveys",{activatedSurveys:e}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[ry]:[...new Set(e)]})}getSurveys(){var e,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[ry];return n||[]}getEventToSurveys(){return this.ji}Hi(){return this.Ui}}class cle{constructor(e){this.Bi=void 0,this._surveyManager=null,this.qi=!1,this.Wi=!1,this.Gi=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var n=e.surveys;if($n(n))return vn.warn("Flags not loaded yet. Not loading surveys.");var r=An(n);this.Bi=r?n.length>0:n,vn.info("flags response received, isSurveysEnabled: "+this.Bi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var r=localStorage.key(n);(r!=null&&r.startsWith(Zk)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach(s=>localStorage.removeItem(s))}loadIfEnabled(){if(!this._surveyManager)if(this.Wi)vn.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)vn.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())vn.info("Not loading surveys in cookieless mode without consent.");else{var e=Et?.__PosthogExtensions__;if(e){if(!Be(this.Bi)||this._instance.config.advanced_enable_surveys){var n=this.Bi||this._instance.config.advanced_enable_surveys;this.Wi=!0;try{var r=e.generateSurveys;if(r)return void this.Vi(r,n);var s=e.loadExternalDependency;if(!s)return void this.Ji("PostHog loadExternalDependency extension not found.");s(this._instance,"surveys",i=>{i||!e.generateSurveys?this.Ji("Could not load surveys script",i):this.Vi(e.generateSurveys,n)})}catch(i){throw this.Ji("Error initializing surveys",i),i}finally{this.Wi=!1}}}else vn.error("PostHog Extensions not found.")}}Vi(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new lle(this._instance),vn.info("Surveys loaded successfully"),this.Ki({isLoaded:!0})}Ji(e,n){vn.error(e,n),this.Ki({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.Gi.push(e),this._surveyManager&&this.Ki({isLoaded:!0}),()=>{this.Gi=this.Gi.filter(n=>n!==e)}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return vn.info("Disabled. Not loading surveys."),e([]);var r=this._instance.get_property(Fk);if(r&&!n)return e(r,{isLoaded:!0});if(this.qi)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.qi=!0,this._instance.ui({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:s=>{var i;this.qi=!1;var a=s.statusCode;if(a!==200||!s.json){var l="Surveys API could not be loaded, status: "+a;return vn.error(l),e([],{isLoaded:!1,error:l})}var u,d=s.json.surveys||[],p=d.filter(h=>function(g){return!(!g.start_date||g.end_date)}(h)&&(function(g){var v;return!((v=g.conditions)==null||(v=v.events)==null||(v=v.values)==null||!v.length)}(h)||function(g){var v;return!((v=g.conditions)==null||(v=v.actions)==null||(v=v.values)==null||!v.length)}(h)));return p.length>0&&((u=this._surveyEventReceiver)==null||u.register(p)),(i=this._instance.persistence)==null||i.register({[Fk]:d}),e(d,{isLoaded:!0})}})}catch(s){throw this.qi=!1,s}}Ki(e){for(var n of this.Gi)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(r){vn.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!$n(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);vn.warn("init was not called")}Yi(e){var n=null;return this.getSurveys(r=>{var s;n=(s=r.find(i=>i.id===e))!==null&&s!==void 0?s:null}),n}Xi(e){if($n(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.Yi(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if($n(this._surveyManager))return vn.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.Xi(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return $n(this._surveyManager)?(vn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise(r=>{this.getSurveys(s=>{var i,a=(i=s.find(u=>u.id===e))!==null&&i!==void 0?i:null;if(a){var l=this.Xi(a);r({visible:l.eligible,disabledReason:l.reason})}else r({visible:!1,disabledReason:"Survey not found"})},n)})}renderSurvey(e,n){var r;if($n(this._surveyManager))vn.warn("init was not called");else{var s=typeof e=="string"?this.Yi(e):e;if(s!=null&&s.id)if(ale.includes(s.type)){var i=Ve?.querySelector(n);if(i)return(r=s.appearance)!=null&&r.surveyPopupDelaySeconds?(vn.info("Rendering survey "+s.id+" with delay of "+s.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var a,l;vn.info("Rendering survey "+s.id+" with delay of "+((a=s.appearance)==null?void 0:a.surveyPopupDelaySeconds)+" seconds"),(l=this._surveyManager)==null||l.renderSurvey(s,i),vn.info("Survey "+s.id+" rendered")},1e3*s.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(s,i);vn.warn("Survey element not found")}else vn.warn("Surveys of type "+s.type+" cannot be rendered in the app");else vn.warn("Survey not found")}}displaySurvey(e,n){var r;if($n(this._surveyManager))vn.warn("init was not called");else{var s=this.Yi(e);if(s){var i=s;if((r=s.appearance)!=null&&r.surveyPopupDelaySeconds&&n.ignoreDelay&&(i=Ye({},s,{appearance:Ye({},s.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var a=this.canRenderSurvey(s);if(!a.visible)return void vn.warn("Survey is not eligible to be displayed: ",a.disabledReason)}n.displayType!==P9.Inline?this._surveyManager.handlePopoverSurvey(i):this.renderSurvey(i,n.selector)}else vn.warn("Survey not found")}}}var uD=Lr("[RateLimiter]");class ule{constructor(e){var n,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var i=s.text;if(i&&i.length)try{(JSON.parse(i).quota_limited||[]).forEach(a=>{uD.info((a||"events")+" is quota limited."),this.serverLimits[a]=new Date().getTime()+6e4})}catch(a){return void uD.warn('could not rate limit - continuing. Error: "'+a?.message+'"',{text:i})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=e.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,r,s;e===void 0&&(e=!1);var i=new Date().getTime(),a=(n=(r=this.instance.persistence)==null?void 0:r.get_property(Bk))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:i};a.tokens+=(i-a.last)/1e3*this.captureEventsPerSecond,a.last=i,a.tokens>this.captureEventsBurstLimit&&(a.tokens=this.captureEventsBurstLimit);var l=a.tokens<1;return l||e||(a.tokens=Math.max(0,a.tokens-1)),!l||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=l,(s=this.instance.persistence)==null||s.set_property(Bk,a),{isRateLimited:l,remainingTokens:a.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var Fc=Lr("[RemoteConfig]");class dle{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=Et._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Qi(e){var n,r;(n=Et.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",()=>e(this.remoteConfig)):(Fc.error("PostHog Extensions not found. Cannot load remote config."),e())}Zi(e){this._instance.ui({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Fc.info("Using preloaded remote config",this.remoteConfig),void this.hi(this.remoteConfig);if(this._instance.L())return void Fc.warn("Remote config is disabled. Falling back to local config.");this.Qi(e=>{if(!e)return Fc.info("No config found after loading remote JS config. Falling back to JSON."),void this.Zi(n=>{this.hi(n)});this.hi(e)})}catch(e){Fc.error("Error loading remote config",e)}}hi(e){e?this._instance.config.__preview_remote_config?(this._instance.hi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Fc.info("__preview_remote_config is disabled. Logging config instead",e):Fc.error("Failed to fetch remote config from PostHog.")}}var eT=3e3;class fle{constructor(e,n){this.te=!0,this.ie=[],this.ee=Na(n?.flush_interval_ms||eT,250,5e3,qe.createLogger("flush interval"),eT),this.re=e}enqueue(e){this.ie.push(e),this.se||this.ne()}unload(){this.oe();var e=this.ie.length>0?this.ae():{},n=Object.values(e);[...n.filter(r=>r.url.indexOf("/e")===0),...n.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.re(Ye({},r,{transport:"sendBeacon"}))})}enable(){this.te=!1,this.ne()}ne(){var e=this;this.te||(this.se=setTimeout(()=>{if(this.oe(),this.ie.length>0){var n=this.ae(),r=function(){var i=n[s],a=new Date().getTime();i.data&&An(i.data)&&Cn(i.data,l=>{l.offset=Math.abs(l.timestamp-a),delete l.timestamp}),e.re(i)};for(var s in n)r()}},this.ee))}oe(){clearTimeout(this.se),this.se=void 0}ae(){var e={};return Cn(this.ie,n=>{var r,s=n,i=(s?s.batchKey:null)||s.url;Be(e[i])&&(e[i]=Ye({},s,{data:[]})),(r=e[i].data)==null||r.push(s.data)}),this.ie=[],e}}var hle=["retriesPerformedSoFar"];class ple{constructor(e){this.le=!1,this.ue=3e3,this.ie=[],this._instance=e,this.ie=[],this.he=!0,!Be(_e)&&"onLine"in _e.navigator&&(this.he=_e.navigator.onLine,Ar(_e,"online",()=>{this.he=!0,this.jt()}),Ar(_e,"offline",()=>{this.he=!1}))}get length(){return this.ie.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,r=RB(e,hle);Wa(n)&&n>0&&(r.url=Ux(r.url,{retry_count:n})),this._instance.ui(Ye({},r,{callback:s=>{s.statusCode!==200&&(s.statusCode<400||s.statusCode>=500)&&(n??0)<10?this.de(Ye({retriesPerformedSoFar:n},r)):r.callback==null||r.callback(s)}}))}de(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var r=function(a){var l=3e3*Math.pow(2,a),u=l/2,d=Math.min(18e5,l),p=(Math.random()-.5)*(d-u);return Math.ceil(d+p)}(n),s=Date.now()+r;this.ie.push({retryAt:s,requestOptions:e});var i="Enqueued failed request for retry in "+r;navigator.onLine||(i+=" (Browser is offline)"),qe.warn(i),this.le||(this.le=!0,this.ve())}ve(){this.ce&&clearTimeout(this.ce),this.ce=setTimeout(()=>{this.he&&this.ie.length>0&&this.jt(),this.ve()},this.ue)}jt(){var e=Date.now(),n=[],r=this.ie.filter(i=>i.retryAt<e||(n.push(i),!1));if(this.ie=n,r.length>0)for(var{requestOptions:s}of r)this.retriableRequest(s)}unload(){for(var{requestOptions:e}of(this.ce&&(clearTimeout(this.ce),this.ce=void 0),this.ie))try{this._instance.ui(Ye({},e,{transport:"sendBeacon"}))}catch(n){qe.error(n)}this.ie=[]}}class mle{constructor(e){this.fe=()=>{var n,r,s,i;this.pe||(this.pe={});var a=this.scrollElement(),l=this.scrollY(),u=a?Math.max(0,a.scrollHeight-a.clientHeight):0,d=l+(a?.clientHeight||0),p=a?.scrollHeight||0;this.pe.lastScrollY=Math.ceil(l),this.pe.maxScrollY=Math.max(l,(n=this.pe.maxScrollY)!==null&&n!==void 0?n:0),this.pe.maxScrollHeight=Math.max(u,(r=this.pe.maxScrollHeight)!==null&&r!==void 0?r:0),this.pe.lastContentY=d,this.pe.maxContentY=Math.max(d,(s=this.pe.maxContentY)!==null&&s!==void 0?s:0),this.pe.maxContentHeight=Math.max(p,(i=this.pe.maxContentHeight)!==null&&i!==void 0?i:0)},this._instance=e}getContext(){return this.pe}resetContext(){var e=this.pe;return setTimeout(this.fe,0),e}startMeasuringScrollPosition(){Ar(_e,"scroll",this.fe,{capture:!0}),Ar(_e,"scrollend",this.fe,{capture:!0}),Ar(_e,"resize",this.fe)}scrollElement(){if(!this._instance.config.scroll_root_selector)return _e?.document.documentElement;var e=An(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var r=_e?.document.querySelector(n);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return _e&&(_e.scrollY||_e.pageYOffset||_e.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return _e&&(_e.scrollX||_e.pageXOffset||_e.document.documentElement.scrollLeft)||0}}var gle=t=>k9(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties);class dD{constructor(e,n,r,s){this.ge=i=>{var a=this._e();if(!a||a.sessionId!==i){var l={sessionId:i,props:this.me(this._instance)};this.ye.register({[Uk]:l})}},this._instance=e,this.be=n,this.ye=r,this.me=s||gle,this.be.onSessionId(this.ge)}_e(){return this.ye.props[Uk]}getSetOnceProps(){var e,n=(e=this._e())==null?void 0:e.props;return n?"r"in n?T9(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 e={};return Cn(sN(this.getSetOnceProps()),(n,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Ok(r)]=n}),e}}var KS=Lr("[SessionId]");class fD{on(e,n){return this.we.on(e,n)}constructor(e,n,r){var s;if(this.xe=[],this.Se=void 0,this.we=new pN,this.Ee=(p,h)=>Math.abs(p-h)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.A=e.config,this.ye=e.persistence,this.$e=void 0,this.ke=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Pe=n||Bl,this.Te=r||Bl;var i=this.A.persistence_name||this.A.token,a=this.A.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*Na(a,60,36e3,KS.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Ie(),this.Re="ph_"+i+"_window_id",this.Ce="ph_"+i+"_primary_window_exists",this.Oe()){var l=Wr.K(this.Re),u=Wr.K(this.Ce);l&&!u?this.$e=l:Wr.X(this.Re),Wr.Y(this.Ce,!0)}if((s=this.A.bootstrap)!=null&&s.sessionID)try{var d=(p=>{var h=p.replace(/-/g,"");if(h.length!==32)throw new Error("Not a valid UUID");if(h[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(h.substring(0,12),16)})(this.A.bootstrap.sessionID);this.Fe(this.A.bootstrap.sessionID,new Date().getTime(),d)}catch(p){KS.error("Invalid sessionID in bootstrap",p)}this.Me()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return Be(this.xe)&&(this.xe=[]),this.xe.push(e),this.ke&&e(this.ke,this.$e),()=>{this.xe=this.xe.filter(n=>n!==e)}}Oe(){return this.A.persistence!=="memory"&&!this.ye.gi&&Wr.G()}Ae(e){e!==this.$e&&(this.$e=e,this.Oe()&&Wr.Y(this.Re,e))}je(){return this.$e?this.$e:this.Oe()?Wr.K(this.Re):null}Fe(e,n,r){e===this.ke&&n===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.ke=e,this.ye.register({[jx]:[n,e,r]}))}De(){if(this.ke&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this.ke,this._sessionStartTimestamp];var e=this.ye.props[jx];return An(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Fe(null,null,null)}destroy(){clearTimeout(this.Le),this.Le=void 0,this.Se&&_e&&(_e.removeEventListener("beforeunload",this.Se,{capture:!1}),this.Se=void 0),this.xe=[]}Me(){this.Se=()=>{this.Oe()&&Wr.X(this.Ce)},Ar(_e,"beforeunload",this.Se,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.A.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[s,i,a]=this.De(),l=this.je(),u=Wa(a)&&a>0&&Math.abs(r-a)>864e5,d=!1,p=!i,h=!e&&this.Ee(r,s);p||h||u?(i=this.Pe(),l=this.Te(),KS.info("new session ID generated",{sessionId:i,windowId:l,changeReason:{noSessionId:p,activityTimeout:h,sessionPastMaximumLength:u}}),a=r,d=!0):l||(l=this.Te(),d=!0);var g=s===0||!e||u?r:s,v=a===0?new Date().getTime():a;return this.Ae(l),this.Fe(i,g,v),e||this.Ie(),d&&this.xe.forEach(x=>x(i,l,d?{noSessionId:p,activityTimeout:h,sessionPastMaximumLength:u}:void 0)),{sessionId:i,windowId:l,sessionStartTimestamp:v,changeReason:d?{noSessionId:p,activityTimeout:h,sessionPastMaximumLength:u}:void 0,lastActivityTimestamp:s}}Ie(){clearTimeout(this.Le),this.Le=setTimeout(()=>{var[e]=this.De();if(this.Ee(new Date().getTime(),e)){var n=this.ke;this.resetSessionId(),this.we.emit("forcedIdleReset",{idleSessionId:n})}},1.1*this.sessionTimeoutMs)}}var vle=["$set_once","$set"],Sl=Lr("[SiteApps]");class yle{constructor(e){this._instance=e,this.Ne=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Ue(e,n){if(n){var r=this.globalsForEvent(n);this.Ne.push(r),this.Ne.length>1e3&&(this.Ne=this.Ne.slice(10))}}get siteAppLoaders(){var e;return(e=Et._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ri(this.Ue.bind(this));this.ze=()=>{e(),this.Ne=[],this.ze=void 0}}}globalsForEvent(e){var n,r,s,i,a,l,u;if(!e)throw new Error("Event payload is required");var d={},p=this._instance.get_property("$groups")||[],h=this._instance.get_property("$stored_group_properties")||{};for(var[g,v]of Object.entries(h))d[g]={id:p[g],type:g,properties:v};var{$set_once:x,$set:b}=e;return{event:Ye({},RB(e,vle),{properties:Ye({},e.properties,b?{$set:Ye({},(n=(r=e.properties)==null?void 0:r.$set)!==null&&n!==void 0?n:{},b)}:{},x?{$set_once:Ye({},(s=(i=e.properties)==null?void 0:i.$set_once)!==null&&s!==void 0?s:{},x)}:{}),elements_chain:(a=(l=e.properties)==null?void 0:l.$elements_chain)!==null&&a!==void 0?a:"",distinct_id:(u=e.properties)==null?void 0:u.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:d}}setupSiteApp(e){var n=this.apps[e.id],r=()=>{var l;!n.errored&&this.Ne.length&&(Sl.info("Processing "+this.Ne.length+" events for site app with id "+e.id),this.Ne.forEach(u=>n.processEvent==null?void 0:n.processEvent(u)),n.processedBuffer=!0),Object.values(this.apps).every(u=>u.processedBuffer||u.errored)&&((l=this.ze)==null||l.call(this))},s=!1,i=l=>{n.errored=!l,n.loaded=!0,Sl.info("Site app with id "+e.id+" "+(l?"loaded":"errored")),s&&r()};try{var{processEvent:a}=e.init({posthog:this._instance,callback:l=>{i(l)}});a&&(n.processEvent=a),s=!0}catch(l){Sl.error("Error while initializing PostHog app with config id "+e.id,l),i(!1)}if(s&&n.loaded)try{r()}catch(l){Sl.error("Error while processing buffered events PostHog app with config id "+e.id,l),n.errored=!0}}He(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}Be(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(n)}catch(s){Sl.error("Error while processing event "+e.event+" for site app "+r.id,s)}}}onRemoteConfig(e){var n,r,s,i=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.He(),void this._instance.on("eventCaptured",d=>this.Be(d))):void Sl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.ze)==null||r.call(this),(s=e.siteApps)!=null&&s.length)if(this.isEnabled){var a=function(d){var p;Et["__$$ph_site_app_"+d]=i._instance,(p=Et.__PosthogExtensions__)==null||p.loadSiteApp==null||p.loadSiteApp(i._instance,u,h=>{if(h)return Sl.error("Error while initializing PostHog app with config id "+d,h)})};for(var{id:l,url:u}of e.siteApps)a(l)}else Sl.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var xle=["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"],hD=function(t,e){if(!t)return!1;var n=t.toLowerCase();return xle.concat(e||[]).some(r=>{var s=r.toLowerCase();return n.indexOf(s)!==-1})},I9=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&hD(n,e))return!0;try{var r=t?.userAgentData;if(r!=null&&r.brands&&r.brands.some(s=>hD(s?.brand,e)))return!0}catch{}return!!t.webdriver},zp=function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t}({}),pD="i.posthog.com";class ble{constructor(e){this.qe={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+pD,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.qe[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.qe[this.apiHost]=zp.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.qe[this.apiHost]=zp.EU:this.qe[this.apiHost]=zp.CUSTOM),this.qe[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(this.region===zp.CUSTOM)return this.apiHost+n;var r=pD+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var _le={icontains:(t,e)=>!!_e&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!_e&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!_e&&kf(e.href,t),not_regex:(t,e)=>!!_e&&!kf(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t};let wle=class fs{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments(s=>{fs.We("retrieved web experiments from the server"),n.Ge=new Map,s.forEach(i=>{if(i.feature_flag_key){var a;n.Ge&&(fs.We("setting flag key ",i.feature_flag_key," to web experiment ",i),(a=n.Ge)==null||a.set(i.feature_flag_key,i));var l=n._instance.getFeatureFlag(i.feature_flag_key);Cr(l)&&i.variants[l]&&n.Ve(i.name,l,i.variants[l].transforms)}else if(i.variants)for(var u in i.variants){var d=i.variants[u];fs.Je(d)&&n.Ve(i.name,u,d.transforms)}})},r)},this._instance=e,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}onFeatureFlags(e){if(this._is_bot())fs.We("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if($n(this.Ge))return this.Ge=new Map,this.loadIfEnabled(),void this.previewWebExperiment();fs.We("applying feature flags",e),e.forEach(n=>{var r;if(this.Ge&&(r=this.Ge)!=null&&r.has(n)){var s,i=this._instance.getFeatureFlag(n),a=(s=this.Ge)==null?void 0:s.get(n);i&&a!=null&&a.variants[i]&&this.Ve(a.name,i,a.variants[i].transforms)}})}}previewWebExperiment(){var e=fs.getWindowLocation();if(e!=null&&e.search){var n=Lx(e?.search,"__experiment_id"),r=Lx(e?.search,"__experiment_variant");n&&r&&(fs.We("previewing web experiments "+n+" && "+r),this.getWebExperiments(s=>{this.Ke(parseInt(n),r,s)},!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var s=this._instance.get_property("$web_experiments");if(s&&!n)return e(s);this._instance.ui({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:i=>{if(i.statusCode!==200||!i.json)return e([]);var a=i.json.experiments||[];return e(a)}})}Ke(e,n,r){var s=r.filter(i=>i.id===e);s&&s.length>0&&(fs.We("Previewing web experiment ["+s[0].name+"] with variant ["+n+"]"),this.Ve(s[0].name,n,s[0].variants[n].transforms))}static Je(e){return!$n(e.conditions)&&fs.Ye(e)&&fs.Xe(e)}static Ye(e){var n;if($n(e.conditions)||$n((n=e.conditions)==null?void 0:n.url))return!0;var r,s,i,a=fs.getWindowLocation();return!!a&&((r=e.conditions)==null||!r.url||_le[(s=(i=e.conditions)==null?void 0:i.urlMatchType)!==null&&s!==void 0?s:"icontains"](e.conditions.url,a))}static getWindowLocation(){return _e?.location}static Xe(e){var n;if($n(e.conditions)||$n((n=e.conditions)==null?void 0:n.utm))return!0;var r=_9();if(r.utm_source){var s,i,a,l,u,d,p,h,g=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_campaign||((i=e.conditions)==null||(i=i.utm)==null?void 0:i.utm_campaign)==r.utm_campaign,v=(a=e.conditions)==null||(a=a.utm)==null||!a.utm_source||((l=e.conditions)==null||(l=l.utm)==null?void 0:l.utm_source)==r.utm_source,x=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_medium||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_medium)==r.utm_medium,b=(p=e.conditions)==null||(p=p.utm)==null||!p.utm_term||((h=e.conditions)==null||(h=h.utm)==null?void 0:h.utm_term)==r.utm_term;return g&&x&&b&&v}return!1}static We(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];qe.info("[WebExperiments] "+e,r)}Ve(e,n,r){this._is_bot()?fs.We("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?r.forEach(s=>{if(s.selector){var i;fs.We("applying transform of variant "+n+" for experiment "+e+" ",s);var a=(i=document)==null?void 0:i.querySelectorAll(s.selector);a?.forEach(l=>{var u=l;s.html&&(u.innerHTML=s.html),s.css&&u.setAttribute("style",s.css)})}}):fs.We("Control variants leave the page unmodified.")}_is_bot(){return ii&&this._instance?I9(ii,this._instance.config.custom_blocked_useragents):void 0}};var Sle=Lr("[PostHog ExternalIntegrations]"),Ele={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class kle{constructor(e){this._instance=e}nt(e,n){var r;(r=Et.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,s=>{if(s)return Sle.error("failed to load script",s);n()})}startIfEnabledOrStop(){var e=this,n=function(a){var l,u,d;!s||(l=Et.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[a]||e.nt(Ele[a],()=>{var p;(p=Et.__PosthogExtensions__)==null||(p=p.integrations)==null||(p=p[a])==null||p.start(e._instance)}),!s&&(u=Et.__PosthogExtensions__)!=null&&(u=u.integrations)!=null&&u[a]&&((d=Et.__PosthogExtensions__)==null||(d=d.integrations)==null||(d=d[a])==null||d.stop())};for(var[r,s]of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;n(r)}}}var tT="[SessionRecording]",bp=Lr(tT);class mD{get started(){var e;return!((e=this.Qe)==null||!e.isStarted)}get status(){return this.Qe?this.Qe.status:this.Ze&&!this.tr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ze=!1,this.ir=void 0,this._instance=e,!this._instance.sessionManager)throw bp.error("started without valid sessionManager"),new Error(tT+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(tT+' cannot be used with cookieless_mode="always"')}get tr(){var e,n=!((e=this._instance.get_property(LS))==null||!e.enabled),r=!this._instance.config.disable_session_recording,s=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return _e&&n&&r&&!s}startIfEnabledOrStop(e){var n;if(!this.tr||(n=this.Qe)==null||!n.isStarted){var r=!Be(Object.assign)&&!Be(Array.from);this.tr&&r?(this.er(e),bp.info("starting")):this.stopRecording()}}er(e){var n,r,s;this.tr&&(Et!=null&&(n=Et.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(r=Et.__PosthogExtensions__)!=null&&r.initSessionRecording?this.rr(e):(s=Et.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,this.sr,i=>{if(i)return bp.error("could not load recorder",i);this.rr(e)}))}stopRecording(){var e,n;(e=this.ir)==null||e.call(this),this.ir=void 0,(n=this.Qe)==null||n.stop()}nr(){var e;(e=this._instance.persistence)==null||e.unregister(FB)}ar(e){if(this._instance.persistence){var n,r,s=this._instance.persistence,i=()=>{var a=e.sessionRecording===!1?void 0:e.sessionRecording,l=a?.sampleRate,u=$n(l)?null:parseFloat(l);$n(u)&&this.nr();var d=a?.minimumDurationMilliseconds;s.register({[LS]:Ye({enabled:!!a},a,{networkPayloadCapture:Ye({capturePerformance:e.capturePerformance},a?.networkPayloadCapture),canvasRecording:{enabled:a?.recordCanvas,fps:a?.canvasFps,quality:a?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:Be(d)?null:d,endpoint:a?.endpoint,triggerMatchType:a?.triggerMatchType,masking:a?.masking,urlTriggers:a?.urlTriggers})})};i(),(n=this.ir)==null||n.call(this),this.ir=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(i)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.ar(e),this.Ze=!0,this.startIfEnabledOrStop()):this.Ze=!0:bp.info("skipping remote config with no sessionRecording",e)}log(e,n){var r;n===void 0&&(n="log"),(r=this.Qe)!=null&&r.log?this.Qe.log(e,n):bp.warn("log called before recorder was ready")}get sr(){var e,n,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(LS);return(r==null||(n=r.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}rr(e){var n,r;if((n=Et.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Qe||(this.Qe=(r=Et.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.Qe._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Qe.start(e)}onRRwebEmit(e){var n;(n=this.Qe)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e;(e=this.Qe)==null||e.overrideLinkedFlag()}overrideSampling(){var e;(e=this.Qe)==null||e.overrideSampling()}overrideTrigger(e){var n;(n=this.Qe)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Qe)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var r;return!((r=this.Qe)==null||!r.tryAddCustomEvent(e,n))}}var Jp={},nT=()=>{},Pd="posthog",D9=!Zoe&&js?.indexOf("MSIE")===-1&&js?.indexOf("Mozilla")===-1,gD=t=>{var e;return{api_host:"https://us.i.posthog.com",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:Yae(Ve?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:nT,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:t!=="2025-05-24"||"history_change",capture_pageleave:"if_capture_pageview",defaults:t??"unset",debug:Ms&&Cr(Ms?.search)&&Ms.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(_e==null||(e=_e.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,session_recording:{},mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:n=>{var r="Bad HTTP status: "+n.statusCode+" "+n.text;qe.error(r)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:eT},error_tracking:{},_onCapture:nT,__preview_eager_load_replay:!1}},vD=t=>{var e={};Be(t.process_person)||(e.person_profiles=t.process_person),Be(t.xhr_headers)||(e.request_headers=t.xhr_headers),Be(t.cookie_name)||(e.persistence_name=t.cookie_name),Be(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),Be(t.store_google)||(e.save_campaign_params=t.store_google),Be(t.verbose)||(e.debug=t.verbose);var n=lr({},e,t);return An(t.property_blacklist)&&(Be(t.property_denylist)?n.property_denylist=t.property_blacklist:An(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:qe.error("Invalid value for property_denylist config: "+t.property_denylist)),n};class Tle{constructor(){this.__forceAllowLocalhost=!1}get lr(){return this.__forceAllowLocalhost}set lr(e){qe.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class w0{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new Tle,this.ur=!1,this.version=wo.LIB_VERSION,this.hr=new pN,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=gD(),this.SentryIntegration=woe,this.sentryIntegration=e=>function(n,r){var s=s9(n,r);return{name:r9,processEvent:i=>s(i)}}(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.dr=!1,this.vr=null,this.cr=null,this.pr=null,this.featureFlags=new rle(this),this.toolbar=new Eoe(this),this.scrollManager=new mle(this),this.pageViewManager=new Voe(this),this.surveys=new cle(this),this.experiments=new wle(this),this.exceptions=new ele(this),this.rateLimiter=new ule(this),this.requestRouter=new ble(this),this.consent=new goe(this),this.externalIntegrations=new kle(this),this.people={set:(e,n,r)=>{var s=Cr(e)?{[e]:n}:e;this.setPersonProperties(s),r?.({})},set_once:(e,n,r)=>{var s=Cr(e)?{[e]:n}:e;this.setPersonProperties(void 0,s),r?.({})}},this.on("eventCaptured",e=>qe.info('send "'+e?.event+'"',e))}init(e,n,r){if(r&&r!==Pd){var s,i=(s=Jp[r])!==null&&s!==void 0?s:new w0;return i._init(e,n,r),Jp[r]=i,Jp[Pd][r]=i,i}return this._init(e,n,r)}_init(e,n,r){var s,i;if(n===void 0&&(n={}),Be(e)||Pk(e))return qe.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.gr(n.debug),this._r=n,this.mr=[],n.person_profiles&&(this.cr=n.person_profiles),this.set_config(lr({},gD(n.defaults),vD(n),{name:r,token:e})),this.config.on_xhr_error&&qe.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ao.GZipJS;var a=this.yr();this.persistence=new WS(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new WS(Ye({},this.config,{persistence:"sessionStorage"}),a);var l=Ye({},this.persistence.props),u=Ye({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.br=new fle(T=>this.wr(T),this.config.request_queue_config),this.Sr=new ple(this),this.__request_queue=[];var d=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(d||(this.sessionManager=new fD(this),this.sessionPropsManager=new dD(this,this.sessionManager,this.persistence)),new Toe(this).startIfEnabledOrStop(),this.siteApps=new yle(this),(s=this.siteApps)==null||s.init(),d||(this.sessionRecording=new mD(this),this.sessionRecording.startIfEnabledOrStop()),this.config.disable_scroll_properties||this.scrollManager.startMeasuringScrollPosition(),this.autocapture=new ooe(this),this.autocapture.startIfEnabled(),this.surveys.loadIfEnabled(),this.heatmaps=new qoe(this),this.heatmaps.startIfEnabled(),this.webVitalsAutocapture=new Uoe(this),this.exceptionObserver=new xoe(this),this.exceptionObserver.startIfEnabled(),this.deadClicksAutocapture=new n9(this,yoe),this.deadClicksAutocapture.startIfEnabled(),this.historyAutocapture=new boe(this),this.historyAutocapture.startIfEnabled(),wo.DEBUG=wo.DEBUG||this.config.debug,wo.DEBUG&&qe.info("Starting in debug mode",{this:this,config:n,thisC:Ye({},this.config),p:l,s:u}),((i=n.bootstrap)==null?void 0:i.distinctID)!==void 0){var p,h,g=this.config.get_device_id(Bl()),v=(p=n.bootstrap)!=null&&p.isIdentifiedID?g:n.bootstrap.distinctID;this.persistence.set_property(So,(h=n.bootstrap)!=null&&h.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:v})}if(this.Er()){var x,b,E=Object.keys(((x=n.bootstrap)==null?void 0:x.featureFlags)||{}).filter(T=>{var R;return!((R=n.bootstrap)==null||(R=R.featureFlags)==null||!R[T])}).reduce((T,R)=>{var j;return T[R]=((j=n.bootstrap)==null||(j=j.featureFlags)==null?void 0:j[R])||!1,T},{}),S=Object.keys(((b=n.bootstrap)==null?void 0:b.featureFlagPayloads)||{}).filter(T=>E[T]).reduce((T,R)=>{var j,A;return(j=n.bootstrap)!=null&&(j=j.featureFlagPayloads)!=null&&j[R]&&(T[R]=(A=n.bootstrap)==null||(A=A.featureFlagPayloads)==null?void 0:A[R]),T},{});this.featureFlags.receivedFeatureFlags({featureFlags:E,featureFlagPayloads:S})}if(d)this.register_once({distinct_id:pp,$device_id:null},"");else if(!this.get_distinct_id()){var k=this.config.get_device_id(Bl());this.register_once({distinct_id:k,$device_id:k},""),this.persistence.set_property(So,"anonymous")}return Ar(_e,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?_oe(this,()=>this.$r()):this.$r(),ql(this.config._onCapture)&&this.config._onCapture!==nT&&(qe.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",T=>this.config._onCapture(T.event,T))),this.config.ip&&qe.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}hi(e){var n,r,s,i,a,l,u,d;if(!Ve||!Ve.body)return qe.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.hi(e)},500);this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=Ht(e.supportedCompression,Ao.GZipJS)?Ao.GZipJS:Ht(e.supportedCompression,Ao.Base64)?Ao.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.cr?this.cr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(s=this.sessionRecording)==null||s.onRemoteConfig(e),(i=this.autocapture)==null||i.onRemoteConfig(e),(a=this.heatmaps)==null||a.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(u=this.exceptionObserver)==null||u.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(d=this.deadClicksAutocapture)==null||d.onRemoteConfig(e)}$r(){try{this.config.loaded(this)}catch(e){qe.critical("`loaded` function failed",e)}this.kr(),this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Pr()},1),new dle(this).load(),this.featureFlags.flags()}kr(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.br)==null||e.enable())}_dom_loaded(){this.is_capturing()&&Hl(this.__request_queue,e=>this.wr(e)),this.__request_queue=[],this.kr()}_handle_unload(){var e,n;this.config.request_batching?(this.Tr()&&this.capture("$pageleave"),(e=this.br)==null||e.unload(),(n=this.Sr)==null||n.unload()):this.Tr()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ui(e){this.__loaded&&(D9?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Ux(e.url,{ip:this.config.ip?1:0}),e.headers=Ye({},this.config.request_headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var r,s,i,a=Ye({},n);a.timeout=a.timeout||6e4,a.url=Ux(a.url,{_:new Date().getTime().toString(),ver:wo.LIB_VERSION,compression:a.compression});var l=(r=a.transport)!==null&&r!==void 0?r:"fetch",u=Yy.filter(p=>!a.disableTransport||!p.transport||!a.disableTransport.includes(p.transport)),d=(s=(i=LB(u,p=>p.transport===l))==null?void 0:i.method)!==null&&s!==void 0?s:u[0].method;if(!d)throw new Error("No available transport method");d(a)})(Ye({},e,{callback:n=>{var r,s;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((r=(s=this.config).on_request_error)==null||r.call(s,n)),e.callback==null||e.callback(n)}}))))}wr(e){this.Sr?this.Sr.retriableRequest(e):this.ui(e)}_execute_array(e){var n,r=[],s=[],i=[];Hl(e,l=>{l&&(n=l[0],An(n)?i.push(l):ql(l)?l.call(this):An(l)&&n==="alias"?r.push(l):An(l)&&n.indexOf("capture")!==-1&&ql(this[n])?i.push(l):s.push(l))});var a=function(l,u){Hl(l,function(d){if(An(d[0])){var p=u;Cn(d,function(h){p=p[h[0]].apply(p,h.slice(1))})}else this[d[0]].apply(this,d.slice(1))},u)};a(r,this),a(s,this),a(i,this)}Er(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,r){var s;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.br){if(this.is_capturing())if(!Be(e)&&Cr(e)){if(this.config.opt_out_useragent_filter||!this._is_bot()){var i=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(i==null||!i.isRateLimited){n!=null&&n.$current_url&&!Cr(n?.$current_url)&&(qe.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var a=new Date,l=r?.timestamp||a,u=Bl(),d={uuid:u,event:e,properties:this.calculateEventProperties(e,n||{},l,u)};i&&(d.properties.$lib_rate_limit_remaining_tokens=i.remainingTokens),r?.$set&&(d.$set=r?.$set);var p,h=this.Ir(r?.$set_once);if(h&&(d.$set_once=h),(d=Gae(d,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,Be(r?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=a),e===Ky.DISMISSED||e===Ky.SENT){var g=n?.[lD.SURVEY_ID],v=n?.[lD.SURVEY_ITERATION];p={id:g,current_iteration:v},localStorage.getItem(cD(p))||localStorage.setItem(cD(p),"true"),d.$set=Ye({},d.$set,{[ile({id:g,current_iteration:v},e===Ky.SENT?"responded":"dismissed")]:!0})}var x=Ye({},d.properties.$set,d.$set);if(Vd(x)||this.setPersonPropertiesForFlags(x),!$n(this.config.before_send)){var b=this.Rr(d);if(!b)return;d=b}this.hr.emit("eventCaptured",d);var E={method:"POST",url:(s=r?._url)!==null&&s!==void 0?s:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:d,compression:"best-available",batchKey:r?._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.wr(E):this.br.enqueue(E),d}qe.critical("This capture call is ignored due to client rate limiting.")}}else qe.error("No event name provided to posthog.capture")}else qe.uninitializedWarning("posthog.capture")}Ri(e){return this.on("eventCaptured",n=>e(n.event,n))}calculateEventProperties(e,n,r,s,i){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var a=i?void 0:this.persistence.remove_event_timer(e),l=Ye({},n);if(l.token=this.config.token,l.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(l.$cookieless_mode=!0),e==="$snapshot"){var u=Ye({},this.persistence.properties(),this.sessionPersistence.properties());return l.distinct_id=u.distinct_id,(!Cr(l.distinct_id)&&!Wa(l.distinct_id)||Pk(l.distinct_id))&&qe.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),l}var d,p=Foe(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:h,windowId:g}=this.sessionManager.checkAndGetSessionAndWindowId(i,r.getTime());l.$session_id=h,l.$window_id=g}this.sessionPropsManager&&lr(l,this.sessionPropsManager.getSessionProps());try{var v;this.sessionRecording&&lr(l,this.sessionRecording.sdkDebugProperties),l.$sdk_debug_retry_queue_size=(v=this.Sr)==null?void 0:v.length}catch(S){l.$sdk_debug_error_capturing_properties=String(S)}if(this.requestRouter.region===zp.CUSTOM&&(l.$lib_custom_api_host=this.config.api_host),d=e!=="$pageview"||i?e!=="$pageleave"||i?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,s),l=lr(l,d),e==="$pageview"&&Ve&&(l.title=Ve.title),!Be(a)){var x=r.getTime()-a;l.$duration=parseFloat((x/1e3).toFixed(3))}js&&this.config.opt_out_useragent_filter&&(l.$browser_type=this._is_bot()?"bot":"browser"),(l=lr({},p,this.persistence.properties(),this.sessionPersistence.properties(),l)).$is_identified=this._isIdentified(),An(this.config.property_denylist)?Cn(this.config.property_denylist,function(S){delete l[S]}):qe.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&(qe.error("sanitize_properties is deprecated. Use before_send instead"),l=b(l,e));var E=this.Cr();return l.$process_person_profile=E,E&&!i&&this.Or("_calculate_event_properties"),l}Ir(e){var n;if(!this.persistence||!this.Cr()||this.ur)return e;var r=this.persistence.get_initial_props(),s=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),i=lr({},r,s||{},e||{}),a=this.config.sanitize_properties;return a&&(qe.error("sanitize_properties is deprecated. Use before_send instead"),i=a(i,"$set_once")),this.ur=!0,Vd(i)?void 0:i}register(e,n){var r;(r=this.persistence)==null||r.register(e,n)}register_once(e,n,r){var s;(s=this.persistence)==null||s.register_once(e,n,r)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}Fr(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,r)}getEarlyAccessFeatures(e,n,r){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,r)}on(e,n){return this.hr.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=ole),this.surveys.displaySurvey(e,n)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,r){if(!this.__loaded||!this.persistence)return qe.uninitializedWarning("posthog.identify");if(Wa(e)&&(e=e.toString(),qe.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))qe.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==pp){if(this.Or("posthog.identify")){var s=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var i=s;this.register_once({$had_persisted_distinct_id:!0,$device_id:i},"")}e!==s&&e!==this.get_property(Op)&&(this.unregister(Op),this.register({distinct_id:e}));var a=(this.persistence.get_property(So)||"anonymous")==="anonymous";e!==s&&a?(this.persistence.set_property(So,"identified"),this.setPersonPropertiesForFlags(Ye({},r||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:s},{$set:n||{},$set_once:r||{}}),this.pr=rD(e,n,r),this.featureFlags.setAnonymousDistinctId(s)):(n||r)&&this.setPersonProperties(n,r),e!==s&&(this.reloadFeatureFlags(),this.unregister(Mx))}}else qe.critical('The string "'+pp+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else qe.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,n){if((e||n)&&this.Or("posthog.setPersonProperties")){var r=rD(this.get_distinct_id(),e,n);this.pr!==r?(this.setPersonPropertiesForFlags(Ye({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.pr=r):qe.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,r){if(e&&n){if(this.Or("posthog.group")){var s=this.getGroups();s[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:Ye({},s,{[e]:n})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),s[e]===n||r||this.reloadFeatureFlags()}}else qe.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.Or("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,r,s,i;if(qe.info("reset"),!this.__loaded)return qe.uninitializedWarning("posthog.reset");var a=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(s=this.persistence)==null||s.set_property(So,"anonymous"),(i=this.sessionManager)==null||i.resetSessionId(),this.pr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:pp,$device_id:null},"");else{var l=this.config.get_device_id(Bl());this.register_once({distinct_id:l,$device_id:e?l:a},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),s=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&r){var i,a=(i=e.timestampLookBack)!==null&&i!==void 0?i:10;if(!r)return s;s+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-a,0)}return s}alias(e,n){return e===this.get_property($B)?(qe.critical("Attempting to create alias for existing People user - aborting."),-2):this.Or("posthog.alias")?(Be(n)&&(n=this.get_distinct_id()),e!==n?(this.Fr(Op,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(qe.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=Ye({},this.config);if(rs(e)){var r,s,i,a,l;lr(this.config,vD(e));var u=this.yr();(r=this.persistence)==null||r.update_config(this.config,n,u),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new WS(Ye({},this.config,{persistence:"sessionStorage"}),u);var d=this.gr(this.config.debug);Vl(d)&&(this.config.debug=d),Vl(this.config.debug)&&(this.config.debug?(wo.DEBUG=!0,Vn.G()&&Vn.Y("ph_debug","true"),qe.info("set_config",{config:e,oldConfig:n,newConfig:Ye({},this.config)})):(wo.DEBUG=!1,Vn.G()&&Vn.X("ph_debug"))),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),(i=this.autocapture)==null||i.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),this.surveys.loadIfEnabled(),this.Mr(),(l=this.externalIntegrations)==null||l.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,r={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var s,i,a,l,u;(s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),r.sampling&&((i=this.sessionRecording)==null||i.overrideSampling()),r.linked_flag&&((a=this.sessionRecording)==null||a.overrideLinkedFlag()),r.url_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("url")),r.event_trigger&&((u=this.sessionRecording)==null||u.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){var r=new Error("PostHog syntheticException"),s=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(Ye({},s,n))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Pd;return n!==Pd&&(n=Pd+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(So))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(So))==="identified"}Cr(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&Vd(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Op])&&((n=this.persistence)==null||(n=n.props)==null||!n[Px]))}Tr(){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.Cr()||this.Or("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Or(e){return this.config.person_profiles==="never"?(qe.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Fr(Px,!0),!0)}yr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}Mr(){var e,n,r,s,i=this.yr();return((e=this.persistence)==null?void 0:e.gi)!==i&&((r=this.persistence)==null||r.set_disabled(i)),((n=this.sessionPersistence)==null?void 0:n.gi)!==i&&((s=this.sessionPersistence)==null||s.set_disabled(i)),i}opt_in_capturing(e){if(this.config.cookieless_mode!=="always"){var n,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(n=this.sessionManager)==null||n.destroy(),this.sessionManager=new fD(this),this.persistence&&(this.sessionPropsManager=new dD(this,this.sessionManager,this.persistence)),this.sessionRecording=new mD(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Mr(),this.kr(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(Be(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((r=e?.captureEventName)!==null&&r!==void 0?r:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Pr()}else qe.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Mr(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:pp,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.Pr())):qe.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Eo.GRANTED?"granted":e===Eo.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Mr()}_is_bot(){return ii?I9(ii,this.config.custom_blocked_useragents):void 0}Pr(){Ve&&(Ve.visibilityState==="visible"?this.dr||(this.dr=!0,this.capture("$pageview",{title:Ve.title},{send_instantly:!0}),this.vr&&(Ve.removeEventListener("visibilitychange",this.vr),this.vr=null)):this.vr||(this.vr=this.Pr.bind(this),Ar(Ve,"visibilitychange",this.vr)))}debug(e){e===!1?(_e?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(_e?.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}))}L(){var e,n,r,s,i,a,l,u=this._r||{};return"advanced_disable_flags"in u?!!u.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(qe.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(r="advanced_disable_decide",s=!1,i=qe,a=(n="advanced_disable_flags")in(e=u)&&!Be(e[n]),l=r in e&&!Be(e[r]),a?e[n]:l?(i&&i.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[r]):s)}Rr(e){if($n(this.config.before_send))return e;var n=An(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var s of n){if(r=s(r),$n(r)){var i="Event '"+e.event+"' was rejected in beforeSend function";return xae(e.event)?qe.warn(i+". This can cause unexpected behavior."):qe.info(i),null}r.properties&&!Vd(r.properties)||qe.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Wt)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(r)})}gr(e){var n=Vl(e)&&!e,r=Vn.G()&&Vn.J("ph_debug")==="true";return!n&&(!!r||e)}}(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=Hae(t.prototype[e[n]])})(w0,["identify"]);var yD,Id=(yD=Jp[Pd]=new w0,function(){function t(){t.done||(t.done=!0,D9=!1,Cn(Jp,function(e){e._dom_loaded()}))}Ve!=null&&Ve.addEventListener?Ve.readyState==="complete"?t():Ar(Ve,"DOMContentLoaded",t,{capture:!1}):_e&&qe.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),yD),mN=w.createContext({client:Id});function L9(t,e,n){if(n===void 0&&(n=new WeakMap),t===e)return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;if(n.has(t)&&n.get(t)===e)return!0;n.set(t,e);var r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;for(var i=0,a=r;i<a.length;i++){var l=a[i];if(!s.includes(l)||!L9(t[l],e[l],n))return!1}return!0}function Cle(t){var e=t.children,n=t.client,r=t.apiKey,s=t.options,i=w.useRef(null),a=w.useMemo(function(){return n?(r&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),s&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),n):(r||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."),Id)},[n,r,JSON.stringify(s)]);return w.useEffect(function(){if(!n){var l=i.current;l?(r!==l.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."),s&&!L9(s,l.options)&&Id.set_config(s),i.current={apiKey:r,options:s??{}}):(Id.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Id.init(r,s),i.current={apiKey:r,options:s??{}})}},[n,r,JSON.stringify(s)]),Ee.createElement(mN.Provider,{value:{client:a}},e)}var Qr=function(){var t=w.useContext(mN).client;return t},rT=function(t,e){return rT=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},rT(t,e)};function Ale(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");rT(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var XS=function(t){return typeof t=="function"},Nle={componentStack:null,exceptionEvent:null,error:null},Rle={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(t){Ale(e,t);function e(n){var r=t.call(this,n)||this;return r.state=Nle,r}return e.prototype.componentDidCatch=function(n,r){var s=this.props.additionalProperties,i;XS(s)?i=s(n):typeof s=="object"&&(i=s);var a=this.context.client,l=a.captureException(n,i),u=r.componentStack;this.setState({error:n,componentStack:u,exceptionEvent:l})},e.prototype.render=function(){var n=this.props,r=n.children,s=n.fallback,i=this.state;if(i.componentStack==null)return XS(r)?r():r;var a=XS(s)?Ee.createElement(s,{error:i.error,componentStack:i.componentStack,exceptionEvent:i.exceptionEvent}):s;return Ee.isValidElement(a)?a:(console.warn(Rle.INVALID_FALLBACK),Ee.createElement(Ee.Fragment,null))},e.contextType=mN,e})(Ee.Component);const jle="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",Mle="https://us.i.posthog.com",Ole={api_host:Mle,capture_pageview:!1,person_profiles:"identified_only",loaded:t=>{t.register({environment:"production"})}},Ple=()=>jle,Ile=()=>Ole;function on(){if(window?.isElectron){const e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("darwin")?"mac":e.includes("win")?"win":"electron"}return"npm"}function Dle({server:t,onDisconnect:e,onReconnect:n,onEdit:r,onRemove:s,onViewDetail:i}){const a=Qr(),[l,u]=w.useState(!1),[d,p]=w.useState(!1),[h,g]=w.useState(!1),[v,x]=w.useState(null),{label:b,Icon:E,iconClassName:S,indicatorColor:k}=TB(t.connectionStatus),T=AB(t.config),R=CB(t.config),j=async(O,L)=>{try{await navigator.clipboard.writeText(O),x(L),setTimeout(()=>x(null),2e3)}catch(z){console.error("Failed to copy text:",z)}},A=async()=>{u(!0);try{n(t.name)}catch(O){const L=O instanceof Error?O.message:"Unknown error";It.error(`Failed to reconnect to ${t.name}: ${L}`)}finally{u(!1)}},N=(O,L)=>{const z=new Blob([JSON.stringify(L,null,2)],{type:"application/json;charset=utf-8"}),H=URL.createObjectURL(z),V=document.createElement("a");V.href=H,V.download=O,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(H)},M=async()=>{p(!0);try{const O=It.loading(`Exporting ${t.name}…`),L=await mae(t.name),z=new Date().toISOString().replace(/[:.]/g,"-"),H=`mcp-server-export_${t.name}_${z}.json`;N(H,L),It.success(`Exported ${t.name} info to ${H}`,{id:O})}catch(O){const L=O instanceof Error?O.message:"Unknown error";It.error(`Failed to export ${t.name}: ${L}`)}finally{p(!1)}},I=t.connectionStatus==="connected";return f.jsx(p0,{children:f.jsx(Ha,{className:`border border-border/50 bg-card/50 backdrop-blur-sm hover:border-border transition-colors ${I?"cursor-pointer":"cursor-default"}`,onClick:()=>I&&i?.(t),children:f.jsxs("div",{className:"p-4 space-y-3 py-0",children:[f.jsxs("div",{className:"flex items-baseline justify-between",children:[f.jsxs("div",{className:"flex items-baseline gap-3 flex-1",children:[f.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0 mt-1",style:{backgroundColor:k}}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-sm text-foreground",children:t.name}),f.jsxs("div",{className:"flex items-center gap-1 leading-none",children:[f.jsx(E,{className:S}),f.jsx("p",{className:"text-xs text-muted-foreground leading-none",children:t.connectionStatus==="failed"?`${b} (${t.retryCount} retries)`:b})]})]}),f.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:T})]})]}),f.jsxs("div",{className:"flex items-center gap-2",onClick:O=>O.stopPropagation(),children:[f.jsx("div",{className:"flex items-center gap-2 pr-2 text-xs text-muted-foreground leading-none",children:f.jsx(hae,{checked:t.connectionStatus==="connected",onCheckedChange:O=>{a.capture("connection_switch_toggled",{location:"server_connection_card",platform:on(),environment:void 0}),O?A():e(t.name)},className:"cursor-pointer scale-80"})}),f.jsxs(m0,{children:[f.jsx(g0,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-muted-foreground/50 hover:text-foreground cursor-pointer",children:f.jsx(Nse,{className:"h-3 w-3"})})}),f.jsxs(v0,{align:"end",className:"w-40",children:[f.jsxs(Ro,{onClick:()=>{a.capture("reconnect_server_clicked",{location:"server_connection_card",platform:on(),environment:void 0}),A()},disabled:l||t.connectionStatus==="connecting"||t.connectionStatus==="oauth-flow",className:"text-xs cursor-pointer",children:[l?f.jsx(bu,{className:"h-3 w-3 mr-2 animate-spin"}):f.jsx(or,{className:"h-3 w-3 mr-2"}),l?"Reconnecting...":"Reconnect"]}),f.jsxs(Ro,{onClick:()=>{a.capture("edit_server_clicked",{location:"server_connection_card",platform:on(),environment:void 0}),r(t)},className:"text-xs cursor-pointer",children:[f.jsx(Aie,{className:"h-3 w-3 mr-2"}),"Edit"]}),f.jsxs(Ro,{onClick:()=>{a.capture("export_server_clicked",{location:"server_connection_card",platform:on(),environment:void 0}),M()},disabled:d||t.connectionStatus!=="connected",className:"text-xs cursor-pointer",children:[d?f.jsx(bu,{className:"h-3 w-3 mr-2 animate-spin"}):f.jsx(Cse,{className:"h-3 w-3 mr-2"}),d?"Exporting...":"Export server info"]}),f.jsx(Rk,{}),f.jsxs(Ro,{className:"text-destructive text-xs cursor-pointer",onClick:()=>{a.capture("remove_server_clicked",{location:"server_connection_card",platform:on(),environment:void 0}),e(t.name),s?.(t.name)},children:[f.jsx(Wse,{className:"h-3 w-3 mr-2"}),"Remove server"]})]})]})]})]}),f.jsxs("div",{className:"font-mono text-xs text-muted-foreground bg-muted/30 p-2 rounded border border-border/30 break-all relative group",onClick:O=>O.stopPropagation(),children:[f.jsx("div",{className:"pr-8",children:R}),f.jsx("button",{onClick:O=>{O.stopPropagation(),j(R,"command")},className:"absolute top-1 right-1 p-1 text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer",children:v==="command"?f.jsx(Ri,{className:"h-3 w-3 text-green-500"}):f.jsx(zo,{className:"h-3 w-3"})})]}),t.connectionStatus==="failed"&&t.lastError&&f.jsxs("div",{className:"text-xs text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/30 p-2 rounded border border-red-200 dark:border-red-800/30",children:[f.jsx("div",{className:"break-all",children:h?t.lastError:t.lastError.length>100?`${t.lastError.substring(0,100)}...`:t.lastError}),t.lastError.length>100&&f.jsx("button",{onClick:O=>{O.stopPropagation(),g(!h)},className:"text-red-500/70 hover:text-red-500 mt-1 underline text-xs cursor-pointer",children:h?"Show less":"Show more"}),t.retryCount>0&&f.jsxs("div",{className:"text-red-500/70 mt-1",children:[t.retryCount," retry attempt",t.retryCount!==1?"s":""]})]})]})})})}function Dn({className:t,type:e,...n}){return f.jsx("input",{type:e,"data-slot":"input",className:Oe("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",t),...n})}function ua({...t}){return f.jsx(xA,{"data-slot":"dialog",...t})}function gN({...t}){return f.jsx(AF,{"data-slot":"dialog-trigger",...t})}function Lle({...t}){return f.jsx(bA,{"data-slot":"dialog-portal",...t})}function $le({className:t,...e}){return f.jsx(_A,{"data-slot":"dialog-overlay",className:Oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function da({className:t,children:e,showCloseButton:n=!0,...r}){return f.jsxs(Lle,{"data-slot":"dialog-portal",children:[f.jsx($le,{}),f.jsxs(wA,{"data-slot":"dialog-content",className:Oe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...r,children:[e,n&&f.jsxs(Xb,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[f.jsx(uc,{}),f.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function fa({className:t,...e}){return f.jsx("div",{"data-slot":"dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",t),...e})}function S0({className:t,...e}){return f.jsx("div",{"data-slot":"dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...e})}function ha({className:t,...e}){return f.jsx(SA,{"data-slot":"dialog-title",className:Oe("text-lg leading-none font-semibold pb-1",t),...e})}function nh({className:t,...e}){return f.jsx(EA,{"data-slot":"dialog-description",className:Oe("text-muted-foreground text-sm",t),...e})}function nu({...t}){return f.jsx(Dne,{"data-slot":"select",...t})}function ru({...t}){return f.jsx($ne,{"data-slot":"select-value",...t})}function su({className:t,size:e="default",children:n,...r}){return f.jsxs(Lne,{"data-slot":"select-trigger","data-size":e,className:Oe("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",t),...r,children:[n,f.jsx(zne,{asChild:!0,children:f.jsx(cc,{className:"size-4 opacity-50"})})]})}function iu({className:t,children:e,position:n="popper",...r}){return f.jsx(Fne,{children:f.jsxs(Une,{"data-slot":"select-content",className:Oe("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",t),position:n,...r,children:[f.jsx(zle,{}),f.jsx(Bne,{className:Oe("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:e}),f.jsx(Fle,{})]})})}function ei({className:t,children:e,...n}){return f.jsxs(qne,{"data-slot":"select-item",className:Oe("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",t),...n,children:[f.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:f.jsx(Hne,{children:f.jsx(Ri,{className:"size-4"})})}),f.jsx(Vne,{children:e})]})}function zle({className:t,...e}){return f.jsx(Gne,{"data-slot":"select-scroll-up-button",className:Oe("flex cursor-default items-center justify-center py-1",t),...e,children:f.jsx(_B,{className:"size-4"})})}function Fle({className:t,...e}){return f.jsx(Wne,{"data-slot":"select-scroll-down-button",className:Oe("flex cursor-default items-center justify-center py-1",t),...e,children:f.jsx(cc,{className:"size-4"})})}let vN;vN=globalThis.crypto;async function Ule(t){return(await vN).getRandomValues(new Uint8Array(t))}async function Ble(t){const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";let n="";const r=await Ule(t);for(let s=0;s<t;s++){const i=r[s]%e.length;n+=e[i]}return n}async function qle(t){return await Ble(t)}async function Vle(t){const e=await(await vN).subtle.digest("SHA-256",new TextEncoder().encode(t));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Hle(t){if(t||(t=43),t<43||t>128)throw`Expected a length between 43 and 128. Received ${t}.`;const e=await qle(t),n=await Vle(e);return{code_verifier:e,code_challenge:n}}var en;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const a of s)i[a]=a;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(l=>typeof s[s[l]]!="number"),a={};for(const l of i)a[l]=s[l];return t.objectValues(a)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&i.push(a);return i},t.find=(s,i)=>{for(const a of s)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(en||(en={}));var xD;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(xD||(xD={}));const Ge=en.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ol=t=>{switch(typeof t){case"undefined":return Ge.undefined;case"string":return Ge.string;case"number":return Number.isNaN(t)?Ge.nan:Ge.number;case"boolean":return Ge.boolean;case"function":return Ge.function;case"bigint":return Ge.bigint;case"symbol":return Ge.symbol;case"object":return Array.isArray(t)?Ge.array:t===null?Ge.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ge.promise:typeof Map<"u"&&t instanceof Map?Ge.map:typeof Set<"u"&&t instanceof Set?Ge.set:typeof Date<"u"&&t instanceof Date?Ge.date:Ge.object;default:return Ge.unknown}},Re=en.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 Fo extends Error{get errors(){return this.issues}constructor(e){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=e}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let l=r,u=0;for(;u<a.path.length;){const d=a.path[u];u===a.path.length-1?(l[d]=l[d]||{_errors:[]},l[d]._errors.push(n(a))):l[d]=l[d]||{_errors:[]},l=l[d],u++}}};return s(this),r}static assert(e){if(!(e instanceof Fo))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,en.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)if(s.path.length>0){const i=s.path[0];n[i]=n[i]||[],n[i].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Fo.create=t=>new Fo(t);const sT=(t,e)=>{let n;switch(t.code){case Re.invalid_type:t.received===Ge.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case Re.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,en.jsonStringifyReplacer)}`;break;case Re.unrecognized_keys:n=`Unrecognized key(s) in object: ${en.joinValues(t.keys,", ")}`;break;case Re.invalid_union:n="Invalid input";break;case Re.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${en.joinValues(t.options)}`;break;case Re.invalid_enum_value:n=`Invalid enum value. Expected ${en.joinValues(t.options)}, received '${t.received}'`;break;case Re.invalid_arguments:n="Invalid function arguments";break;case Re.invalid_return_type:n="Invalid function return type";break;case Re.invalid_date:n="Invalid date";break;case Re.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:en.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case Re.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case Re.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case Re.custom:n="Invalid input";break;case Re.invalid_intersection_types:n="Intersection results could not be merged";break;case Re.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case Re.not_finite:n="Number must be finite";break;default:n=e.defaultError,en.assertNever(t)}return{message:n}};let Gle=sT;function Wle(){return Gle}const Yle=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],a={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(a,{data:e,defaultError:l}).message;return{...s,path:i,message:l}};function Ue(t,e){const n=Wle(),r=Yle({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===sT?void 0:sT].filter(s=>!!s)});t.common.issues.push(r)}class xs{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return wt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,a=await s.value;r.push({key:i,value:a})}return xs.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:a}=s;if(i.status==="aborted"||a.status==="aborted")return wt;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const wt=Object.freeze({status:"aborted"}),Fp=t=>({status:"dirty",value:t}),Li=t=>({status:"valid",value:t}),bD=t=>t.status==="aborted",_D=t=>t.status==="dirty",Tf=t=>t.status==="valid",Bx=t=>typeof Promise<"u"&&t instanceof Promise;var rt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(rt||(rt={}));class Ya{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const wD=(t,e)=>{if(Tf(e))return{success:!0,data:e.value};if(!t.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 Fo(t.common.issues);return this._error=n,this._error}}};function Dt(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,l)=>{const{message:u}=t;return a.code==="invalid_enum_value"?{message:u??l.defaultError}:typeof l.data>"u"?{message:u??r??l.defaultError}:a.code!=="invalid_type"?{message:l.defaultError}:{message:u??n??l.defaultError}},description:s}}class Yt{get description(){return this._def.description}_getType(e){return Ol(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ol(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xs,ctx:{common:e.parent.common,data:e.data,parsedType:Ol(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Bx(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ol(e)},s=this._parseSync({data:e,path:r.path,parent:r});return wD(r,s)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ol(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return Tf(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Tf(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ol(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(Bx(s)?s:Promise.resolve(s));return wD(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const a=e(s),l=()=>i.addIssue({code:Re.custom,...r(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(l(),!1)):a?!0:(l(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ku({schema:this,typeName:kt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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 Oo.create(this,this._def)}nullable(){return Tu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return za.create(this)}promise(){return Yx.create(this,this._def)}or(e){return Vx.create([this,e],this._def)}and(e){return Hx.create(this,e,this._def)}transform(e){return new ku({...Dt(this._def),schema:this,typeName:kt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Kx({...Dt(this._def),innerType:this,defaultValue:n,typeName:kt.ZodDefault})}brand(){return new U9({typeName:kt.ZodBranded,type:this,...Dt(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Xx({...Dt(this._def),innerType:this,catchValue:n,typeName:kt.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return xN.create(this,e)}readonly(){return Qx.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Kle=/^c[^\s-]{8,}$/i,Xle=/^[0-9a-z]+$/,Qle=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jle=/^[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,Zle=/^[a-z0-9_-]{21}$/i,ece=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tce=/^[-+]?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)?)??$/,nce=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rce="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let QS;const sce=/^(?:(?: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])$/,ice=/^(?:(?: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])$/,ace=/^(([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]))$/,oce=/^(([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])$/,lce=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cce=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$9="((\\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])))",uce=new RegExp(`^${$9}$`);function z9(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function dce(t){return new RegExp(`^${z9(t)}$`)}function fce(t){let e=`${$9}T${z9(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function hce(t,e){return!!((e==="v4"||!e)&&sce.test(t)||(e==="v6"||!e)&&ace.test(t))}function pce(t,e){if(!ece.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function mce(t,e){return!!((e==="v4"||!e)&&ice.test(t)||(e==="v6"||!e)&&oce.test(t))}class jo extends Yt{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ge.string){const i=this._getOrReturnCtx(e);return Ue(i,{code:Re.invalid_type,expected:Ge.string,received:i.parsedType}),wt}const r=new xs;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,l=e.data.length<i.value;(a||l)&&(s=this._getOrReturnCtx(e,s),a?Ue(s,{code:Re.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):l&&Ue(s,{code:Re.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")nce.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"email",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")QS||(QS=new RegExp(rce,"u")),QS.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"emoji",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Jle.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"uuid",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Zle.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"nanoid",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Kle.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"cuid",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Xle.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"cuid2",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Qle.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"ulid",code:Re.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),Ue(s,{validation:"url",code:Re.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"regex",code:Re.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?fce(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?uce.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?dce(i).test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?tce.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"duration",code:Re.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?hce(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"ip",code:Re.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?pce(e.data,i.alg)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"jwt",code:Re.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?mce(e.data,i.version)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"cidr",code:Re.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?lce.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"base64",code:Re.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?cce.test(e.data)||(s=this._getOrReturnCtx(e,s),Ue(s,{validation:"base64url",code:Re.invalid_string,message:i.message}),r.dirty()):en.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:Re.invalid_string,...rt.errToObj(r)})}_addCheck(e){return new jo({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...rt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...rt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...rt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...rt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...rt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...rt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...rt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...rt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...rt.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...rt.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...rt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...rt.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...rt.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...rt.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...rt.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...rt.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...rt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...rt.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...rt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...rt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...rt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...rt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...rt.errToObj(n)})}nonempty(e){return this.min(1,rt.errToObj(e))}trim(){return new jo({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new jo({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new jo({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}jo.create=t=>new jo({checks:[],typeName:kt.ZodString,coerce:t?.coerce??!1,...Dt(t)});function gce(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=Number.parseInt(t.toFixed(s).replace(".","")),a=Number.parseInt(e.toFixed(s).replace(".",""));return i%a/10**s}class Cf extends Yt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Ge.number){const i=this._getOrReturnCtx(e);return Ue(i,{code:Re.invalid_type,expected:Ge.number,received:i.parsedType}),wt}let r;const s=new xs;for(const i of this._def.checks)i.kind==="int"?en.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?gce(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.not_finite,message:i.message}),s.dirty()):en.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,rt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,rt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,rt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,rt.toString(n))}setLimit(e,n,r,s){return new Cf({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:rt.toString(s)}]})}_addCheck(e){return new Cf({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:rt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:rt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:rt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:rt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:rt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:rt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:rt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:rt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:rt.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&en.isInteger(e.value))}get isFinite(){let e=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"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}}Cf.create=t=>new Cf({checks:[],typeName:kt.ZodNumber,coerce:t?.coerce||!1,...Dt(t)});class Pm extends Yt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ge.bigint)return this._getInvalidInput(e);let r;const s=new xs;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Ue(r,{code:Re.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):en.assertNever(i);return{status:s.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return Ue(n,{code:Re.invalid_type,expected:Ge.bigint,received:n.parsedType}),wt}gte(e,n){return this.setLimit("min",e,!0,rt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,rt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,rt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,rt.toString(n))}setLimit(e,n,r,s){return new Pm({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:rt.toString(s)}]})}_addCheck(e){return new Pm({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:rt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:rt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:rt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:rt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:rt.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Pm.create=t=>new Pm({checks:[],typeName:kt.ZodBigInt,coerce:t?.coerce??!1,...Dt(t)});class iT extends Yt{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ge.boolean){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.boolean,received:r.parsedType}),wt}return Li(e.data)}}iT.create=t=>new iT({typeName:kt.ZodBoolean,coerce:t?.coerce||!1,...Dt(t)});class qx extends Yt{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ge.date){const i=this._getOrReturnCtx(e);return Ue(i,{code:Re.invalid_type,expected:Ge.date,received:i.parsedType}),wt}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return Ue(i,{code:Re.invalid_date}),wt}const r=new xs;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),Ue(s,{code:Re.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):en.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new qx({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:rt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:rt.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}qx.create=t=>new qx({checks:[],coerce:t?.coerce||!1,typeName:kt.ZodDate,...Dt(t)});class SD extends Yt{_parse(e){if(this._getType(e)!==Ge.symbol){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.symbol,received:r.parsedType}),wt}return Li(e.data)}}SD.create=t=>new SD({typeName:kt.ZodSymbol,...Dt(t)});class aT extends Yt{_parse(e){if(this._getType(e)!==Ge.undefined){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.undefined,received:r.parsedType}),wt}return Li(e.data)}}aT.create=t=>new aT({typeName:kt.ZodUndefined,...Dt(t)});class oT extends Yt{_parse(e){if(this._getType(e)!==Ge.null){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.null,received:r.parsedType}),wt}return Li(e.data)}}oT.create=t=>new oT({typeName:kt.ZodNull,...Dt(t)});class lT extends Yt{constructor(){super(...arguments),this._any=!0}_parse(e){return Li(e.data)}}lT.create=t=>new lT({typeName:kt.ZodAny,...Dt(t)});class cT extends Yt{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Li(e.data)}}cT.create=t=>new cT({typeName:kt.ZodUnknown,...Dt(t)});class Ql extends Yt{_parse(e){const n=this._getOrReturnCtx(e);return Ue(n,{code:Re.invalid_type,expected:Ge.never,received:n.parsedType}),wt}}Ql.create=t=>new Ql({typeName:kt.ZodNever,...Dt(t)});class ED extends Yt{_parse(e){if(this._getType(e)!==Ge.undefined){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.void,received:r.parsedType}),wt}return Li(e.data)}}ED.create=t=>new ED({typeName:kt.ZodVoid,...Dt(t)});class za extends Yt{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==Ge.array)return Ue(n,{code:Re.invalid_type,expected:Ge.array,received:n.parsedType}),wt;if(s.exactLength!==null){const a=n.data.length>s.exactLength.value,l=n.data.length<s.exactLength.value;(a||l)&&(Ue(n,{code:a?Re.too_big:Re.too_small,minimum:l?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(Ue(n,{code:Re.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(Ue(n,{code:Re.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,l)=>s.type._parseAsync(new Ya(n,a,n.path,l)))).then(a=>xs.mergeArray(r,a));const i=[...n.data].map((a,l)=>s.type._parseSync(new Ya(n,a,n.path,l)));return xs.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new za({...this._def,minLength:{value:e,message:rt.toString(n)}})}max(e,n){return new za({...this._def,maxLength:{value:e,message:rt.toString(n)}})}length(e,n){return new za({...this._def,exactLength:{value:e,message:rt.toString(n)}})}nonempty(e){return this.min(1,e)}}za.create=(t,e)=>new za({type:t,minLength:null,maxLength:null,exactLength:null,typeName:kt.ZodArray,...Dt(e)});function Dd(t){if(t instanceof gr){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Oo.create(Dd(r))}return new gr({...t._def,shape:()=>e})}else return t instanceof za?new za({...t._def,type:Dd(t.element)}):t instanceof Oo?Oo.create(Dd(t.unwrap())):t instanceof Tu?Tu.create(Dd(t.unwrap())):t instanceof Su?Su.create(t.items.map(e=>Dd(e))):t}class gr extends Yt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=en.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ge.object){const d=this._getOrReturnCtx(e);return Ue(d,{code:Re.invalid_type,expected:Ge.object,received:d.parsedType}),wt}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ql&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||l.push(d);const u=[];for(const d of a){const p=i[d],h=s.data[d];u.push({key:{status:"valid",value:d},value:p._parse(new Ya(s,h,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof Ql){const d=this._def.unknownKeys;if(d==="passthrough")for(const p of l)u.push({key:{status:"valid",value:p},value:{status:"valid",value:s.data[p]}});else if(d==="strict")l.length>0&&(Ue(s,{code:Re.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const p of l){const h=s.data[p];u.push({key:{status:"valid",value:p},value:d._parse(new Ya(s,h,s.path,p)),alwaysSet:p in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const p of u){const h=await p.key,g=await p.value;d.push({key:h,value:g,alwaysSet:p.alwaysSet})}return d}).then(d=>xs.mergeObjectSync(r,d)):xs.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return rt.errToObj,new gr({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{const s=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:rt.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new gr({...this._def,unknownKeys:"strip"})}passthrough(){return new gr({...this._def,unknownKeys:"passthrough"})}extend(e){return new gr({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new gr({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:kt.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new gr({...this._def,catchall:e})}pick(e){const n={};for(const r of en.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new gr({...this._def,shape:()=>n})}omit(e){const n={};for(const r of en.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new gr({...this._def,shape:()=>n})}deepPartial(){return Dd(this)}partial(e){const n={};for(const r of en.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}return new gr({...this._def,shape:()=>n})}required(e){const n={};for(const r of en.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Oo;)i=i._def.innerType;n[r]=i}return new gr({...this._def,shape:()=>n})}keyof(){return F9(en.objectKeys(this.shape))}}gr.create=(t,e)=>new gr({shape:()=>t,unknownKeys:"strip",catchall:Ql.create(),typeName:kt.ZodObject,...Dt(e)});gr.strictCreate=(t,e)=>new gr({shape:()=>t,unknownKeys:"strict",catchall:Ql.create(),typeName:kt.ZodObject,...Dt(e)});gr.lazycreate=(t,e)=>new gr({shape:t,unknownKeys:"strip",catchall:Ql.create(),typeName:kt.ZodObject,...Dt(e)});class Vx extends Yt{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const a=i.map(l=>new Fo(l.ctx.common.issues));return Ue(n,{code:Re.invalid_union,unionErrors:a}),wt}if(n.common.async)return Promise.all(r.map(async i=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(s);{let i;const a=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:d});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=a.map(u=>new Fo(u));return Ue(n,{code:Re.invalid_union,unionErrors:l}),wt}}get options(){return this._def.options}}Vx.create=(t,e)=>new Vx({options:t,typeName:kt.ZodUnion,...Dt(e)});const bo=t=>t instanceof dT?bo(t.schema):t instanceof ku?bo(t.innerType()):t instanceof Wx?[t.value]:t instanceof Eu?t.options:t instanceof fT?en.objectValues(t.enum):t instanceof Kx?bo(t._def.innerType):t instanceof aT?[void 0]:t instanceof oT?[null]:t instanceof Oo?[void 0,...bo(t.unwrap())]:t instanceof Tu?[null,...bo(t.unwrap())]:t instanceof U9||t instanceof Qx?bo(t.unwrap()):t instanceof Xx?bo(t._def.innerType):[];class yN extends Yt{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ge.object)return Ue(n,{code:Re.invalid_type,expected:Ge.object,received:n.parsedType}),wt;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(Ue(n,{code:Re.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),wt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const a=bo(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const l of a){if(s.has(l))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(l)}`);s.set(l,i)}}return new yN({typeName:kt.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Dt(r)})}}function uT(t,e){const n=Ol(t),r=Ol(e);if(t===e)return{valid:!0,data:t};if(n===Ge.object&&r===Ge.object){const s=en.objectKeys(e),i=en.objectKeys(t).filter(l=>s.indexOf(l)!==-1),a={...t,...e};for(const l of i){const u=uT(t[l],e[l]);if(!u.valid)return{valid:!1};a[l]=u.data}return{valid:!0,data:a}}else if(n===Ge.array&&r===Ge.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const a=t[i],l=e[i],u=uT(a,l);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return n===Ge.date&&r===Ge.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class Hx extends Yt{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,a)=>{if(bD(i)||bD(a))return wt;const l=uT(i.value,a.value);return l.valid?((_D(i)||_D(a))&&n.dirty(),{status:n.value,value:l.data}):(Ue(r,{code:Re.invalid_intersection_types}),wt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>s(i,a)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Hx.create=(t,e,n)=>new Hx({left:t,right:e,typeName:kt.ZodIntersection,...Dt(n)});class Su extends Yt{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ge.array)return Ue(r,{code:Re.invalid_type,expected:Ge.array,received:r.parsedType}),wt;if(r.data.length<this._def.items.length)return Ue(r,{code:Re.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),wt;!this._def.rest&&r.data.length>this._def.items.length&&(Ue(r,{code:Re.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((a,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ya(r,a,r.path,l)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>xs.mergeArray(n,a)):xs.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new Su({...this._def,rest:e})}}Su.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Su({items:t,typeName:kt.ZodTuple,rest:null,...Dt(e)})};class Gx extends Yt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ge.object)return Ue(r,{code:Re.invalid_type,expected:Ge.object,received:r.parsedType}),wt;const s=[],i=this._def.keyType,a=this._def.valueType;for(const l in r.data)s.push({key:i._parse(new Ya(r,l,r.path,l)),value:a._parse(new Ya(r,r.data[l],r.path,l)),alwaysSet:l in r.data});return r.common.async?xs.mergeObjectAsync(n,s):xs.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Yt?new Gx({keyType:e,valueType:n,typeName:kt.ZodRecord,...Dt(r)}):new Gx({keyType:jo.create(),valueType:e,typeName:kt.ZodRecord,...Dt(n)})}}class kD extends Yt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ge.map)return Ue(r,{code:Re.invalid_type,expected:Ge.map,received:r.parsedType}),wt;const s=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([l,u],d)=>({key:s._parse(new Ya(r,l,r.path,[d,"key"])),value:i._parse(new Ya(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of a){const d=await u.key,p=await u.value;if(d.status==="aborted"||p.status==="aborted")return wt;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of a){const d=u.key,p=u.value;if(d.status==="aborted"||p.status==="aborted")return wt;(d.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(d.value,p.value)}return{status:n.value,value:l}}}}kD.create=(t,e,n)=>new kD({valueType:e,keyType:t,typeName:kt.ZodMap,...Dt(n)});class Im extends Yt{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ge.set)return Ue(r,{code:Re.invalid_type,expected:Ge.set,received:r.parsedType}),wt;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(Ue(r,{code:Re.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(Ue(r,{code:Re.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function a(u){const d=new Set;for(const p of u){if(p.status==="aborted")return wt;p.status==="dirty"&&n.dirty(),d.add(p.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ya(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>a(u)):a(l)}min(e,n){return new Im({...this._def,minSize:{value:e,message:rt.toString(n)}})}max(e,n){return new Im({...this._def,maxSize:{value:e,message:rt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Im.create=(t,e)=>new Im({valueType:t,minSize:null,maxSize:null,typeName:kt.ZodSet,...Dt(e)});class dT extends Yt{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}dT.create=(t,e)=>new dT({getter:t,typeName:kt.ZodLazy,...Dt(e)});class Wx extends Yt{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return Ue(n,{received:n.data,code:Re.invalid_literal,expected:this._def.value}),wt}return{status:"valid",value:e.data}}get value(){return this._def.value}}Wx.create=(t,e)=>new Wx({value:t,typeName:kt.ZodLiteral,...Dt(e)});function F9(t,e){return new Eu({values:t,typeName:kt.ZodEnum,...Dt(e)})}class Eu extends Yt{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return Ue(n,{expected:en.joinValues(r),received:n.parsedType,code:Re.invalid_type}),wt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return Ue(n,{received:n.data,code:Re.invalid_enum_value,options:r}),wt}return Li(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Eu.create(e,{...this._def,...n})}exclude(e,n=this._def){return Eu.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}}Eu.create=F9;class fT extends Yt{_parse(e){const n=en.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ge.string&&r.parsedType!==Ge.number){const s=en.objectValues(n);return Ue(r,{expected:en.joinValues(s),received:r.parsedType,code:Re.invalid_type}),wt}if(this._cache||(this._cache=new Set(en.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=en.objectValues(n);return Ue(r,{received:r.data,code:Re.invalid_enum_value,options:s}),wt}return Li(e.data)}get enum(){return this._def.values}}fT.create=(t,e)=>new fT({values:t,typeName:kt.ZodNativeEnum,...Dt(e)});class Yx extends Yt{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ge.promise&&n.common.async===!1)return Ue(n,{code:Re.invalid_type,expected:Ge.promise,received:n.parsedType}),wt;const r=n.parsedType===Ge.promise?n.data:Promise.resolve(n.data);return Li(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Yx.create=(t,e)=>new Yx({type:t,typeName:kt.ZodPromise,...Dt(e)});class ku extends Yt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===kt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:a=>{Ue(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const a=s.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async l=>{if(n.value==="aborted")return wt;const u=await this._def.schema._parseAsync({data:l,path:r.path,parent:r});return u.status==="aborted"?wt:u.status==="dirty"||n.value==="dirty"?Fp(u.value):u});{if(n.value==="aborted")return wt;const l=this._def.schema._parseSync({data:a,path:r.path,parent:r});return l.status==="aborted"?wt:l.status==="dirty"||n.value==="dirty"?Fp(l.value):l}}if(s.type==="refinement"){const a=l=>{const u=s.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?wt:(l.status==="dirty"&&n.dirty(),a(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?wt:(l.status==="dirty"&&n.dirty(),a(l.value).then(()=>({status:n.value,value:l.value}))))}if(s.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Tf(a))return wt;const l=s.transform(a.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Tf(a)?Promise.resolve(s.transform(a.value,i)).then(l=>({status:n.value,value:l})):wt);en.assertNever(s)}}ku.create=(t,e,n)=>new ku({schema:t,typeName:kt.ZodEffects,effect:e,...Dt(n)});ku.createWithPreprocess=(t,e,n)=>new ku({schema:e,effect:{type:"preprocess",transform:t},typeName:kt.ZodEffects,...Dt(n)});class Oo extends Yt{_parse(e){return this._getType(e)===Ge.undefined?Li(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Oo.create=(t,e)=>new Oo({innerType:t,typeName:kt.ZodOptional,...Dt(e)});class Tu extends Yt{_parse(e){return this._getType(e)===Ge.null?Li(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Tu.create=(t,e)=>new Tu({innerType:t,typeName:kt.ZodNullable,...Dt(e)});class Kx extends Yt{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===Ge.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Kx.create=(t,e)=>new Kx({innerType:t,typeName:kt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Dt(e)});class Xx extends Yt{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Bx(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Fo(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Fo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Xx.create=(t,e)=>new Xx({innerType:t,typeName:kt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Dt(e)});class TD extends Yt{_parse(e){if(this._getType(e)!==Ge.nan){const r=this._getOrReturnCtx(e);return Ue(r,{code:Re.invalid_type,expected:Ge.nan,received:r.parsedType}),wt}return{status:"valid",value:e.data}}}TD.create=t=>new TD({typeName:kt.ZodNaN,...Dt(t)});class U9 extends Yt{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class xN extends Yt{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?wt:i.status==="dirty"?(n.dirty(),Fp(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?wt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new xN({in:e,out:n,typeName:kt.ZodPipeline})}}class Qx extends Yt{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Tf(s)&&(s.value=Object.freeze(s.value)),s);return Bx(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}}Qx.create=(t,e)=>new Qx({innerType:t,typeName:kt.ZodReadonly,...Dt(e)});var kt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(kt||(kt={}));const ve=jo.create,Ir=Cf.create,Nr=iT.create,vce=lT.create,yg=cT.create;Ql.create;const Je=za.create,$e=gr.create,_s=Vx.create,yce=yN.create;Hx.create;Su.create;const xg=Gx.create,Rt=Wx.create,Uo=Eu.create;Yx.create;const Ce=Oo.create;Tu.create;const xce=wt,bN="2025-06-18",E0="2.0",B9=_s([ve(),Ir().int()]),q9=ve(),bce=$e({progressToken:Ce(B9)}).passthrough(),$i=$e({_meta:Ce(bce)}).passthrough(),Fs=$e({method:ve(),params:Ce($i)}),bg=$e({_meta:Ce($e({}).passthrough())}).passthrough(),Ja=$e({method:ve(),params:Ce(bg)}),zi=$e({_meta:Ce($e({}).passthrough())}).passthrough(),k0=_s([ve(),Ir().int()]),_ce=$e({jsonrpc:Rt(E0),id:k0}).merge(Fs).strict(),wce=$e({jsonrpc:Rt(E0)}).merge(Ja).strict(),Sce=$e({jsonrpc:Rt(E0),id:k0,result:zi}).strict();var CD;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError"})(CD||(CD={}));const Ece=$e({jsonrpc:Rt(E0),id:k0,error:$e({code:Ir().int(),message:ve(),data:Ce(yg())})}).strict();_s([_ce,wce,Sce,Ece]);const V9=zi.strict(),H9=Ja.extend({method:Rt("notifications/cancelled"),params:bg.extend({requestId:k0,reason:ve().optional()})}),kce=$e({src:ve(),mimeType:Ce(ve()),sizes:Ce(Je(ve()))}).passthrough(),_g=$e({icons:Je(kce).optional()}).passthrough(),wg=$e({name:ve(),title:Ce(ve())}).passthrough(),G9=wg.extend({version:ve(),websiteUrl:Ce(ve())}).merge(_g),Tce=$e({experimental:Ce($e({}).passthrough()),sampling:Ce($e({}).passthrough()),elicitation:Ce($e({}).passthrough()),roots:Ce($e({listChanged:Ce(Nr())}).passthrough())}).passthrough(),Cce=Fs.extend({method:Rt("initialize"),params:$i.extend({protocolVersion:ve(),capabilities:Tce,clientInfo:G9})}),Ace=$e({experimental:Ce($e({}).passthrough()),logging:Ce($e({}).passthrough()),completions:Ce($e({}).passthrough()),prompts:Ce($e({listChanged:Ce(Nr())}).passthrough()),resources:Ce($e({subscribe:Ce(Nr()),listChanged:Ce(Nr())}).passthrough()),tools:Ce($e({listChanged:Ce(Nr())}).passthrough())}).passthrough(),Nce=zi.extend({protocolVersion:ve(),capabilities:Ace,serverInfo:G9,instructions:Ce(ve())}),Rce=Ja.extend({method:Rt("notifications/initialized")}),W9=Fs.extend({method:Rt("ping")}),jce=$e({progress:Ir(),total:Ce(Ir()),message:Ce(ve())}).passthrough(),Y9=Ja.extend({method:Rt("notifications/progress"),params:bg.merge(jce).extend({progressToken:B9})}),T0=Fs.extend({params:$i.extend({cursor:Ce(q9)}).optional()}),C0=zi.extend({nextCursor:Ce(q9)}),K9=$e({uri:ve(),mimeType:Ce(ve()),_meta:Ce($e({}).passthrough())}).passthrough(),X9=K9.extend({text:ve()}),_N=ve().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Q9=K9.extend({blob:_N}),J9=wg.extend({uri:ve(),description:Ce(ve()),mimeType:Ce(ve()),_meta:Ce($e({}).passthrough())}).merge(_g),Mce=wg.extend({uriTemplate:ve(),description:Ce(ve()),mimeType:Ce(ve()),_meta:Ce($e({}).passthrough())}).merge(_g),Oce=T0.extend({method:Rt("resources/list")}),Pce=C0.extend({resources:Je(J9)}),Ice=T0.extend({method:Rt("resources/templates/list")}),Dce=C0.extend({resourceTemplates:Je(Mce)}),Lce=Fs.extend({method:Rt("resources/read"),params:$i.extend({uri:ve()})}),$ce=zi.extend({contents:Je(_s([X9,Q9]))}),zce=Ja.extend({method:Rt("notifications/resources/list_changed")}),Fce=Fs.extend({method:Rt("resources/subscribe"),params:$i.extend({uri:ve()})}),Uce=Fs.extend({method:Rt("resources/unsubscribe"),params:$i.extend({uri:ve()})}),Bce=Ja.extend({method:Rt("notifications/resources/updated"),params:bg.extend({uri:ve()})}),qce=$e({name:ve(),description:Ce(ve()),required:Ce(Nr())}).passthrough(),Vce=wg.extend({description:Ce(ve()),arguments:Ce(Je(qce)),_meta:Ce($e({}).passthrough())}).merge(_g),Hce=T0.extend({method:Rt("prompts/list")}),Gce=C0.extend({prompts:Je(Vce)}),Wce=Fs.extend({method:Rt("prompts/get"),params:$i.extend({name:ve(),arguments:Ce(xg(ve()))})}),wN=$e({type:Rt("text"),text:ve(),_meta:Ce($e({}).passthrough())}).passthrough(),SN=$e({type:Rt("image"),data:_N,mimeType:ve(),_meta:Ce($e({}).passthrough())}).passthrough(),EN=$e({type:Rt("audio"),data:_N,mimeType:ve(),_meta:Ce($e({}).passthrough())}).passthrough(),Yce=$e({type:Rt("resource"),resource:_s([X9,Q9]),_meta:Ce($e({}).passthrough())}).passthrough(),Kce=J9.extend({type:Rt("resource_link")}),Z9=_s([wN,SN,EN,Kce,Yce]),Xce=$e({role:Uo(["user","assistant"]),content:Z9}).passthrough(),Qce=zi.extend({description:Ce(ve()),messages:Je(Xce)}),Jce=Ja.extend({method:Rt("notifications/prompts/list_changed")}),Zce=$e({title:Ce(ve()),readOnlyHint:Ce(Nr()),destructiveHint:Ce(Nr()),idempotentHint:Ce(Nr()),openWorldHint:Ce(Nr())}).passthrough(),eue=wg.extend({description:Ce(ve()),inputSchema:$e({type:Rt("object"),properties:Ce($e({}).passthrough()),required:Ce(Je(ve()))}).passthrough(),outputSchema:Ce($e({type:Rt("object"),properties:Ce($e({}).passthrough()),required:Ce(Je(ve()))}).passthrough()),annotations:Ce(Zce),_meta:Ce($e({}).passthrough())}).merge(_g),tue=T0.extend({method:Rt("tools/list")}),nue=C0.extend({tools:Je(eue)}),eq=zi.extend({content:Je(Z9).default([]),structuredContent:$e({}).passthrough().optional(),isError:Ce(Nr())});eq.or(zi.extend({toolResult:yg()}));const rue=Fs.extend({method:Rt("tools/call"),params:$i.extend({name:ve(),arguments:Ce(xg(yg()))})}),sue=Ja.extend({method:Rt("notifications/tools/list_changed")}),tq=Uo(["debug","info","notice","warning","error","critical","alert","emergency"]),iue=Fs.extend({method:Rt("logging/setLevel"),params:$i.extend({level:tq})}),aue=Ja.extend({method:Rt("notifications/message"),params:bg.extend({level:tq,logger:Ce(ve()),data:yg()})}),oue=$e({name:ve().optional()}).passthrough(),lue=$e({hints:Ce(Je(oue)),costPriority:Ce(Ir().min(0).max(1)),speedPriority:Ce(Ir().min(0).max(1)),intelligencePriority:Ce(Ir().min(0).max(1))}).passthrough(),cue=$e({role:Uo(["user","assistant"]),content:_s([wN,SN,EN])}).passthrough(),uue=Fs.extend({method:Rt("sampling/createMessage"),params:$i.extend({messages:Je(cue),systemPrompt:Ce(ve()),includeContext:Ce(Uo(["none","thisServer","allServers"])),temperature:Ce(Ir()),maxTokens:Ir().int(),stopSequences:Ce(Je(ve())),metadata:Ce($e({}).passthrough()),modelPreferences:Ce(lue)})}),due=zi.extend({model:ve(),stopReason:Ce(Uo(["endTurn","stopSequence","maxTokens"]).or(ve())),role:Uo(["user","assistant"]),content:yce("type",[wN,SN,EN])}),fue=$e({type:Rt("boolean"),title:Ce(ve()),description:Ce(ve()),default:Ce(Nr())}).passthrough(),hue=$e({type:Rt("string"),title:Ce(ve()),description:Ce(ve()),minLength:Ce(Ir()),maxLength:Ce(Ir()),format:Ce(Uo(["email","uri","date","date-time"]))}).passthrough(),pue=$e({type:Uo(["number","integer"]),title:Ce(ve()),description:Ce(ve()),minimum:Ce(Ir()),maximum:Ce(Ir())}).passthrough(),mue=$e({type:Rt("string"),title:Ce(ve()),description:Ce(ve()),enum:Je(ve()),enumNames:Ce(Je(ve()))}).passthrough(),gue=_s([fue,hue,pue,mue]),vue=Fs.extend({method:Rt("elicitation/create"),params:$i.extend({message:ve(),requestedSchema:$e({type:Rt("object"),properties:xg(ve(),gue),required:Ce(Je(ve()))}).passthrough()})}),yue=zi.extend({action:Uo(["accept","decline","cancel"]),content:Ce(xg(ve(),yg()))}),xue=$e({type:Rt("ref/resource"),uri:ve()}).passthrough(),bue=$e({type:Rt("ref/prompt"),name:ve()}).passthrough(),_ue=Fs.extend({method:Rt("completion/complete"),params:$i.extend({ref:_s([bue,xue]),argument:$e({name:ve(),value:ve()}).passthrough(),context:Ce($e({arguments:Ce(xg(ve(),ve()))}))})}),wue=zi.extend({completion:$e({values:Je(ve()).max(100),total:Ce(Ir().int()),hasMore:Ce(Nr())}).passthrough()}),Sue=$e({uri:ve().startsWith("file://"),name:Ce(ve()),_meta:Ce($e({}).passthrough())}).passthrough(),Eue=Fs.extend({method:Rt("roots/list")}),kue=zi.extend({roots:Je(Sue)}),Tue=Ja.extend({method:Rt("notifications/roots/list_changed")});_s([W9,Cce,_ue,iue,Wce,Hce,Oce,Ice,Lce,Fce,Uce,rue,tue]);_s([H9,Y9,Rce,Tue]);_s([V9,due,yue,kue]);_s([W9,uue,vue,Eue]);_s([H9,Y9,aue,Bce,zce,sue,Jce]);_s([V9,Nce,wue,Qce,Gce,Pce,Dce,$ce,eq,nue]);const Kr=ve().url().superRefine((t,e)=>{if(!URL.canParse(t))return e.addIssue({code:Re.custom,message:"URL must be parseable",fatal:!0}),xce}).refine(t=>{const e=new URL(t);return e.protocol!=="javascript:"&&e.protocol!=="data:"&&e.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),Cue=$e({resource:ve().url(),authorization_servers:Je(Kr).optional(),jwks_uri:ve().url().optional(),scopes_supported:Je(ve()).optional(),bearer_methods_supported:Je(ve()).optional(),resource_signing_alg_values_supported:Je(ve()).optional(),resource_name:ve().optional(),resource_documentation:ve().optional(),resource_policy_uri:ve().url().optional(),resource_tos_uri:ve().url().optional(),tls_client_certificate_bound_access_tokens:Nr().optional(),authorization_details_types_supported:Je(ve()).optional(),dpop_signing_alg_values_supported:Je(ve()).optional(),dpop_bound_access_tokens_required:Nr().optional()}).passthrough(),kN=$e({issuer:ve(),authorization_endpoint:Kr,token_endpoint:Kr,registration_endpoint:Kr.optional(),scopes_supported:Je(ve()).optional(),response_types_supported:Je(ve()),response_modes_supported:Je(ve()).optional(),grant_types_supported:Je(ve()).optional(),token_endpoint_auth_methods_supported:Je(ve()).optional(),token_endpoint_auth_signing_alg_values_supported:Je(ve()).optional(),service_documentation:Kr.optional(),revocation_endpoint:Kr.optional(),revocation_endpoint_auth_methods_supported:Je(ve()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Je(ve()).optional(),introspection_endpoint:ve().optional(),introspection_endpoint_auth_methods_supported:Je(ve()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Je(ve()).optional(),code_challenge_methods_supported:Je(ve()).optional()}).passthrough(),Aue=$e({issuer:ve(),authorization_endpoint:Kr,token_endpoint:Kr,userinfo_endpoint:Kr.optional(),jwks_uri:Kr,registration_endpoint:Kr.optional(),scopes_supported:Je(ve()).optional(),response_types_supported:Je(ve()),response_modes_supported:Je(ve()).optional(),grant_types_supported:Je(ve()).optional(),acr_values_supported:Je(ve()).optional(),subject_types_supported:Je(ve()),id_token_signing_alg_values_supported:Je(ve()),id_token_encryption_alg_values_supported:Je(ve()).optional(),id_token_encryption_enc_values_supported:Je(ve()).optional(),userinfo_signing_alg_values_supported:Je(ve()).optional(),userinfo_encryption_alg_values_supported:Je(ve()).optional(),userinfo_encryption_enc_values_supported:Je(ve()).optional(),request_object_signing_alg_values_supported:Je(ve()).optional(),request_object_encryption_alg_values_supported:Je(ve()).optional(),request_object_encryption_enc_values_supported:Je(ve()).optional(),token_endpoint_auth_methods_supported:Je(ve()).optional(),token_endpoint_auth_signing_alg_values_supported:Je(ve()).optional(),display_values_supported:Je(ve()).optional(),claim_types_supported:Je(ve()).optional(),claims_supported:Je(ve()).optional(),service_documentation:ve().optional(),claims_locales_supported:Je(ve()).optional(),ui_locales_supported:Je(ve()).optional(),claims_parameter_supported:Nr().optional(),request_parameter_supported:Nr().optional(),request_uri_parameter_supported:Nr().optional(),require_request_uri_registration:Nr().optional(),op_policy_uri:Kr.optional(),op_tos_uri:Kr.optional()}).passthrough(),Nue=Aue.merge(kN.pick({code_challenge_methods_supported:!0})),nq=$e({access_token:ve(),id_token:ve().optional(),token_type:ve(),expires_in:Ir().optional(),scope:ve().optional(),refresh_token:ve().optional()}).strip(),Rue=$e({error:ve(),error_description:ve().optional(),error_uri:ve().optional()}),AD=Kr.optional().or(Rt("").transform(()=>{})),jue=$e({redirect_uris:Je(Kr),token_endpoint_auth_method:ve().optional(),grant_types:Je(ve()).optional(),response_types:Je(ve()).optional(),client_name:ve().optional(),client_uri:Kr.optional(),logo_uri:AD,scope:ve().optional(),contacts:Je(ve()).optional(),tos_uri:AD,policy_uri:ve().optional(),jwks_uri:Kr.optional(),jwks:vce().optional(),software_id:ve().optional(),software_version:ve().optional(),software_statement:ve().optional()}).strip(),Mue=$e({client_id:ve(),client_secret:ve().optional(),client_id_issued_at:Ir().optional(),client_secret_expires_at:Ir().optional()}).strip(),Oue=jue.merge(Mue);$e({error:ve(),error_description:ve().optional()}).strip();$e({token:ve(),token_type_hint:ve().optional()}).strip();function Pue(t){const e=typeof t=="string"?new URL(t):new URL(t.href);return e.hash="",e}function Iue({requestedResource:t,configuredResource:e}){const n=typeof t=="string"?new URL(t):new URL(t.href),r=typeof e=="string"?new URL(e):new URL(e.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;const s=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/";return s.startsWith(i)}class Jr extends Error{constructor(e,n){super(e),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class hT extends Jr{}hT.errorCode="invalid_request";class Jx extends Jr{}Jx.errorCode="invalid_client";class Zx extends Jr{}Zx.errorCode="invalid_grant";class eb extends Jr{}eb.errorCode="unauthorized_client";class pT extends Jr{}pT.errorCode="unsupported_grant_type";class mT extends Jr{}mT.errorCode="invalid_scope";class gT extends Jr{}gT.errorCode="access_denied";class Af extends Jr{}Af.errorCode="server_error";class vT extends Jr{}vT.errorCode="temporarily_unavailable";class yT extends Jr{}yT.errorCode="unsupported_response_type";class xT extends Jr{}xT.errorCode="unsupported_token_type";let bT=class extends Jr{};bT.errorCode="invalid_token";class _T extends Jr{}_T.errorCode="method_not_allowed";class wT extends Jr{}wT.errorCode="too_many_requests";class ST extends Jr{}ST.errorCode="invalid_client_metadata";class ET extends Jr{}ET.errorCode="insufficient_scope";const Due={[hT.errorCode]:hT,[Jx.errorCode]:Jx,[Zx.errorCode]:Zx,[eb.errorCode]:eb,[pT.errorCode]:pT,[mT.errorCode]:mT,[gT.errorCode]:gT,[Af.errorCode]:Af,[vT.errorCode]:vT,[yT.errorCode]:yT,[xT.errorCode]:xT,[bT.errorCode]:bT,[_T.errorCode]:_T,[wT.errorCode]:wT,[ST.errorCode]:ST,[ET.errorCode]:ET},JS="code",ZS="S256";function rq(t,e){const n=t.client_secret!==void 0;return e.length===0?n?"client_secret_post":"none":n&&e.includes("client_secret_basic")?"client_secret_basic":n&&e.includes("client_secret_post")?"client_secret_post":e.includes("none")?"none":n?"client_secret_post":"none"}function sq(t,e,n,r){const{client_id:s,client_secret:i}=e;switch(t){case"client_secret_basic":Lue(s,i,n);return;case"client_secret_post":$ue(s,i,r);return;case"none":zue(s,r);return;default:throw new Error(`Unsupported client authentication method: ${t}`)}}function Lue(t,e,n){if(!e)throw new Error("client_secret_basic authentication requires a client_secret");const r=btoa(`${t}:${e}`);n.set("Authorization",`Basic ${r}`)}function $ue(t,e,n){n.set("client_id",t),e&&n.set("client_secret",e)}function zue(t,e){e.set("client_id",t)}async function TN(t){const e=t instanceof Response?t.status:void 0,n=t instanceof Response?await t.text():t;try{const r=Rue.parse(JSON.parse(n)),{error:s,error_description:i,error_uri:a}=r,l=Due[s]||Af;return new l(i||"",a)}catch(r){const s=`${e?`HTTP ${e}: `:""}Invalid OAuth error response: ${r}. Raw body: ${n}`;return new Af(s)}}async function CN(t,e){var n,r;try{return await eE(t,e)}catch(s){if(s instanceof Jx||s instanceof eb)return await((n=t.invalidateCredentials)===null||n===void 0?void 0:n.call(t,"all")),await eE(t,e);if(s instanceof Zx)return await((r=t.invalidateCredentials)===null||r===void 0?void 0:r.call(t,"tokens")),await eE(t,e);throw s}}async function eE(t,{serverUrl:e,authorizationCode:n,scope:r,resourceMetadataUrl:s,fetchFn:i}){let a,l;try{a=await aq(e,{resourceMetadataUrl:s},i),a.authorization_servers&&a.authorization_servers.length>0&&(l=a.authorization_servers[0])}catch{}l||(l=e);const u=await iq(e,t,a),d=await Vue(l,{fetchFn:i});let p=await Promise.resolve(t.clientInformation());if(!p){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");if(!t.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");const b=await uq(l,{metadata:d,clientMetadata:t.clientMetadata,fetchFn:i});await t.saveClientInformation(b),p=b}if(n!==void 0){const b=await t.codeVerifier(),E=await cq(l,{metadata:d,clientInformation:p,authorizationCode:n,codeVerifier:b,redirectUri:t.redirectUrl,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(E),"AUTHORIZED"}const h=await t.tokens();if(h?.refresh_token)try{const b=await Hue(l,{metadata:d,clientInformation:p,refreshToken:h.refresh_token,resource:u,addClientAuthentication:t.addClientAuthentication,fetchFn:i});return await t.saveTokens(b),"AUTHORIZED"}catch(b){if(!(!(b instanceof Jr)||b instanceof Af))throw b}const g=t.state?await t.state():void 0,{authorizationUrl:v,codeVerifier:x}=await lq(l,{metadata:d,clientInformation:p,state:g,redirectUrl:t.redirectUrl,scope:r||t.clientMetadata.scope,resource:u});return await t.saveCodeVerifier(x),await t.redirectToAuthorization(v),"REDIRECT"}async function iq(t,e,n){const r=Pue(t);if(e.validateResourceURL)return await e.validateResourceURL(r,n?.resource);if(n){if(!Iue({requestedResource:r,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}async function aq(t,e,n=fetch){const r=await oq(t,"oauth-protected-resource",n,{protocolVersion:e?.protocolVersion,metadataUrl:e?.resourceMetadataUrl});if(!r||r.status===404)throw new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!r.ok)throw new Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Cue.parse(await r.json())}async function AN(t,e,n=fetch){try{return await n(t,{headers:e})}catch(r){if(r instanceof TypeError)return e?AN(t,void 0,n):void 0;throw r}}function Fue(t,e="",n={}){return e.endsWith("/")&&(e=e.slice(0,-1)),n.prependPathname?`${e}/.well-known/${t}`:`/.well-known/${t}${e}`}async function ND(t,e,n=fetch){return await AN(t,{"MCP-Protocol-Version":e},n)}function Uue(t,e){return!t||t.status>=400&&t.status<500&&e!=="/"}async function oq(t,e,n,r){var s,i;const a=new URL(t),l=(s=r?.protocolVersion)!==null&&s!==void 0?s:bN;let u;if(r?.metadataUrl)u=new URL(r.metadataUrl);else{const p=Fue(e,a.pathname);u=new URL(p,(i=r?.metadataServerUrl)!==null&&i!==void 0?i:a),u.search=a.search}let d=await ND(u,l,n);if(!r?.metadataUrl&&Uue(d,a.pathname)){const p=new URL(`/.well-known/${e}`,a);d=await ND(p,l,n)}return d}async function Bue(t,{authorizationServerUrl:e,protocolVersion:n}={},r=fetch){typeof t=="string"&&(t=new URL(t)),e||(e=t),typeof e=="string"&&(e=new URL(e)),n??(n=bN);const s=await oq(e,"oauth-authorization-server",r,{protocolVersion:n,metadataServerUrl:e});if(!(!s||s.status===404)){if(!s.ok)throw new Error(`HTTP ${s.status} trying to load well-known OAuth metadata`);return kN.parse(await s.json())}}function que(t){const e=typeof t=="string"?new URL(t):t,n=e.pathname!=="/",r=[];if(!n)return r.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",e.origin),type:"oidc"}),r;let s=e.pathname;return s.endsWith("/")&&(s=s.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${s}`,e.origin),type:"oauth"}),r.push({url:new URL("/.well-known/oauth-authorization-server",e.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${s}`,e.origin),type:"oidc"}),r.push({url:new URL(`${s}/.well-known/openid-configuration`,e.origin),type:"oidc"}),r}async function Vue(t,{fetchFn:e=fetch,protocolVersion:n=bN}={}){const r={"MCP-Protocol-Version":n,Accept:"application/json"},s=que(t);for(const{url:i,type:a}of s){const l=await AN(i,r,e);if(l){if(!l.ok){if(l.status>=400&&l.status<500)continue;throw new Error(`HTTP ${l.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?kN.parse(await l.json()):Nue.parse(await l.json())}}}async function lq(t,{metadata:e,clientInformation:n,redirectUrl:r,scope:s,state:i,resource:a}){let l;if(e){if(l=new URL(e.authorization_endpoint),!e.response_types_supported.includes(JS))throw new Error(`Incompatible auth server: does not support response type ${JS}`);if(e.code_challenge_methods_supported&&!e.code_challenge_methods_supported.includes(ZS))throw new Error(`Incompatible auth server: does not support code challenge method ${ZS}`)}else l=new URL("/authorize",t);const u=await Hle(),d=u.code_verifier,p=u.code_challenge;return l.searchParams.set("response_type",JS),l.searchParams.set("client_id",n.client_id),l.searchParams.set("code_challenge",p),l.searchParams.set("code_challenge_method",ZS),l.searchParams.set("redirect_uri",String(r)),i&&l.searchParams.set("state",i),s&&l.searchParams.set("scope",s),s?.includes("offline_access")&&l.searchParams.append("prompt","consent"),a&&l.searchParams.set("resource",a.href),{authorizationUrl:l,codeVerifier:d}}async function cq(t,{metadata:e,clientInformation:n,authorizationCode:r,codeVerifier:s,redirectUri:i,resource:a,addClientAuthentication:l,fetchFn:u}){var d;const p="authorization_code",h=e?.token_endpoint?new URL(e.token_endpoint):new URL("/token",t);if(e?.grant_types_supported&&!e.grant_types_supported.includes(p))throw new Error(`Incompatible auth server: does not support grant type ${p}`);const g=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),v=new URLSearchParams({grant_type:p,code:r,code_verifier:s,redirect_uri:String(i)});if(l)l(g,v,t,e);else{const b=(d=e?.token_endpoint_auth_methods_supported)!==null&&d!==void 0?d:[],E=rq(n,b);sq(E,n,g,v)}a&&v.set("resource",a.href);const x=await(u??fetch)(h,{method:"POST",headers:g,body:v});if(!x.ok)throw await TN(x);return nq.parse(await x.json())}async function Hue(t,{metadata:e,clientInformation:n,refreshToken:r,resource:s,addClientAuthentication:i,fetchFn:a}){var l;const u="refresh_token";let d;if(e){if(d=new URL(e.token_endpoint),e.grant_types_supported&&!e.grant_types_supported.includes(u))throw new Error(`Incompatible auth server: does not support grant type ${u}`)}else d=new URL("/token",t);const p=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),h=new URLSearchParams({grant_type:u,refresh_token:r});if(i)i(p,h,t,e);else{const v=(l=e?.token_endpoint_auth_methods_supported)!==null&&l!==void 0?l:[],x=rq(n,v);sq(x,n,p,h)}s&&h.set("resource",s.href);const g=await(a??fetch)(d,{method:"POST",headers:p,body:h});if(!g.ok)throw await TN(g);return nq.parse({refresh_token:r,...await g.json()})}async function uq(t,{metadata:e,clientMetadata:n,fetchFn:r}){let s;if(e){if(!e.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");s=new URL(e.registration_endpoint)}else s=new URL("/register",t);const i=await(r??fetch)(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw await TN(i);return Oue.parse(await i.json())}const ff=window.fetch;function NN(){return async function(e,n){const r=typeof e=="string"?e:e instanceof URL?e.toString():e.url;if(r.includes("/.well-known/oauth-authorization-server"))try{const s=`/api/mcp/oauth/metadata?url=${encodeURIComponent(r)}`;return await ff(s,{...n,method:"GET"})}catch(s){return console.error("OAuth metadata proxy failed, falling back to direct fetch:",s),await ff(e,n)}return await ff(e,n)}}class A0{serverName;redirectUri;customClientId;customClientSecret;constructor(e,n,r){this.serverName=e,this.redirectUri=`${window.location.origin}/oauth/callback`,this.customClientId=n,this.customClientSecret=r}get redirectUrl(){return this.redirectUri}get clientMetadata(){return{client_name:`MCPJam - ${this.serverName}`,client_uri:"https://github.com/mcpjam/inspector",redirect_uris:[this.redirectUri],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){const e=localStorage.getItem(`mcp-client-${this.serverName}`),n=e?JSON.parse(e):void 0;if(this.customClientId)if(n){const r={...n,client_id:this.customClientId};return this.customClientSecret&&(r.client_secret=this.customClientSecret),r}else{const r={client_id:this.customClientId};return this.customClientSecret&&(r.client_secret=this.customClientSecret),r}return n}async saveClientInformation(e){localStorage.setItem(`mcp-client-${this.serverName}`,JSON.stringify(e))}tokens(){const e=localStorage.getItem(`mcp-tokens-${this.serverName}`);return e?JSON.parse(e):void 0}async saveTokens(e){localStorage.setItem(`mcp-tokens-${this.serverName}`,JSON.stringify(e))}async redirectToAuthorization(e){localStorage.setItem("mcp-oauth-pending",this.serverName),window.location.href=e.toString()}async saveCodeVerifier(e){localStorage.setItem(`mcp-verifier-${this.serverName}`,e)}codeVerifier(){const e=localStorage.getItem(`mcp-verifier-${this.serverName}`);if(!e)throw new Error("Code verifier not found");return e}async invalidateCredentials(e){switch(e){case"all":localStorage.removeItem(`mcp-tokens-${this.serverName}`),localStorage.removeItem(`mcp-client-${this.serverName}`),localStorage.removeItem(`mcp-verifier-${this.serverName}`);break;case"client":localStorage.removeItem(`mcp-client-${this.serverName}`);break;case"tokens":localStorage.removeItem(`mcp-tokens-${this.serverName}`);break;case"verifier":localStorage.removeItem(`mcp-verifier-${this.serverName}`);break}}}async function tb(t){const e=NN();window.fetch=e;try{const n=new A0(t.serverName,t.clientId,t.clientSecret);localStorage.setItem(`mcp-serverUrl-${t.serverName}`,t.serverUrl),localStorage.setItem("mcp-oauth-pending",t.serverName);const r={};if(t.scopes&&t.scopes.length>0&&(r.scopes=t.scopes),localStorage.setItem(`mcp-oauth-config-${t.serverName}`,JSON.stringify(r)),t.clientId||t.clientSecret){const a=localStorage.getItem(`mcp-client-${t.serverName}`),u={...a?JSON.parse(a):{}};t.clientId&&(u.client_id=t.clientId),t.clientSecret&&(u.client_secret=t.clientSecret),localStorage.setItem(`mcp-client-${t.serverName}`,JSON.stringify(u))}const s={serverUrl:t.serverUrl};t.scopes&&t.scopes.length>0&&(s.scope=t.scopes.join(" "));const i=await CN(n,s);if(i==="REDIRECT")return{success:!0};if(i==="AUTHORIZED"){const a=n.tokens();if(a)return{success:!0,serverConfig:MN(t.serverUrl,a)}}return{success:!1,error:"OAuth flow failed"}}catch(n){let r="Unknown OAuth error";return n instanceof Error&&(r=n.message,r.includes("invalid_client")||r.includes("client_id")?r="Invalid client ID. Please verify the client ID is correctly registered with the OAuth provider.":r.includes("unauthorized_client")?r="Client not authorized. The client ID may not be registered for this server or scope.":r.includes("invalid_request")&&(r="OAuth request invalid. Please check your client ID and try again.")),{success:!1,error:r}}finally{window.fetch=ff}}async function dq(t){const e=NN();window.fetch=e;try{const n=localStorage.getItem("mcp-oauth-pending");if(!n)throw new Error("No pending OAuth flow found");const r=localStorage.getItem(`mcp-serverUrl-${n}`);if(!r)throw new Error("Server URL not found for OAuth callback");const s=localStorage.getItem(`mcp-client-${n}`),i=s?JSON.parse(s).client_id:void 0,a=s?JSON.parse(s).client_secret:void 0,l=new A0(n,i,a);if(await CN(l,{serverUrl:r,authorizationCode:t})==="AUTHORIZED"){const d=l.tokens();if(d)return localStorage.removeItem("mcp-oauth-pending"),{success:!0,serverConfig:MN(r,d),serverName:n}}return{success:!1,error:"Token exchange failed"}}catch(n){let r="Unknown callback error";return n instanceof Error&&(r=n.message,r.includes("invalid_client")||r.includes("client_id")?r="Invalid client ID during token exchange. Please verify the client ID is correctly registered.":r.includes("unauthorized_client")?r="Client not authorized for token exchange. The client ID may not match the one used for authorization.":r.includes("invalid_grant")&&(r="Authorization code invalid or expired. Please try the OAuth flow again.")),{success:!1,error:r}}finally{window.fetch=ff}}function si(t){const e=localStorage.getItem(`mcp-tokens-${t}`),n=localStorage.getItem(`mcp-client-${t}`);if(!e)return;const r=JSON.parse(e),s=n?JSON.parse(n):{};return{...r,client_id:s.client_id||r.client_id}}function RN(t){const e=localStorage.getItem(`mcp-serverUrl-${t}`),n=localStorage.getItem(`mcp-client-${t}`),r=localStorage.getItem(`mcp-oauth-config-${t}`),s=si(t);return e!=null||n!=null||r!=null||s!=null}async function jN(t){const e=NN();window.fetch=e;try{const n=localStorage.getItem(`mcp-client-${t}`),r=n?JSON.parse(n).client_id:void 0,s=n?JSON.parse(n).client_secret:void 0,i=new A0(t,r,s);if(!i.tokens()?.refresh_token)return{success:!1,error:"No refresh token available"};const l=localStorage.getItem(`mcp-serverUrl-${t}`);if(!l)return{success:!1,error:"Server URL not found for token refresh"};if(await CN(i,{serverUrl:l})==="AUTHORIZED"){const d=i.tokens();if(d)return{success:!0,serverConfig:MN(l,d)}}return{success:!1,error:"Token refresh failed"}}catch(n){let r="Unknown refresh error";return n instanceof Error&&(r=n.message,r.includes("invalid_client")||r.includes("client_id")?r="Invalid client ID during token refresh. The stored client ID may be incorrect.":r.includes("invalid_grant")?r="Refresh token invalid or expired. Please re-authenticate with the OAuth provider.":r.includes("unauthorized_client")&&(r="Client not authorized for token refresh. Please re-authenticate.")),{success:!1,error:r}}finally{window.fetch=ff}}function nb(t){localStorage.removeItem(`mcp-tokens-${t}`),localStorage.removeItem(`mcp-client-${t}`),localStorage.removeItem(`mcp-verifier-${t}`),localStorage.removeItem(`mcp-serverUrl-${t}`),localStorage.removeItem(`mcp-oauth-config-${t}`)}function MN(t,e){return{url:new URL(t),requestInit:{headers:e.access_token?{Authorization:`Bearer ${e.access_token}`}:{}},oauth:e}}const Gue=Object.freeze(Object.defineProperty({__proto__:null,MCPOAuthProvider:A0,clearOAuthData:nb,getStoredTokens:si,handleOAuthCallback:dq,hasOAuthConfig:RN,initiateOAuth:tb,refreshOAuthTokens:jN},Symbol.toStringTag,{value:"Module"}));function kT({isOpen:t,onClose:e,mode:n,onSubmit:r,server:s}){const i=Qr(),[a,l]=w.useState({name:"",type:"stdio",command:"",args:[],url:"",headers:{},env:{},useOAuth:!0,oauthScopes:[],clientId:""}),[u,d]=w.useState(""),[p,h]=w.useState(""),[g,v]=w.useState(""),[x,b]=w.useState(""),[E,S]=w.useState(""),[k,T]=w.useState("none"),[R,j]=w.useState(!1),[A,N]=w.useState(null),[M,I]=w.useState(null),[O,L]=w.useState([]),[z,H]=w.useState([]),V=Y=>{const Z=Y.config;if("url"in Z){const J=Z.requestInit?.headers||{},oe=Y.oauthTokens!=null,pe=RN(Y.name),ye="oauth"in Z&&Z.oauth!=null,je=oe||pe||ye,Ne=localStorage.getItem(`mcp-oauth-config-${Y.name}`),Ae=localStorage.getItem(`mcp-client-${Y.name}`),He=si(Y.name),lt=Ae?JSON.parse(Ae):{},Fe=Ne?JSON.parse(Ne):{},ct=Y.oauthTokens?.scope?.split(" ")||He?.scope?.split(" ")||Fe.scopes||[];return{name:Y.name,type:"http",url:Z.url?.toString()||"",headers:J,useOAuth:je,oauthScopes:ct,clientId:"clientId"in Z?typeof Z.clientId=="string"?Z.clientId:"":He?.client_id||lt?.client_id||"",clientSecret:"clientSecret"in Z?typeof Z.clientSecret=="string"?Z.clientSecret:"":lt?.client_secret||""}}else return{name:Y.name,type:"stdio",command:Z.command||"",args:Z.args||[],env:Z.env||{}}},X=()=>n==="edit"&&s?V(s):{name:"",type:"stdio",command:"",args:[],url:"",headers:{},env:{},useOAuth:!0,oauthScopes:[],clientId:""};w.useEffect(()=>{if(t){const Y=X();if(l(Y),Y.type==="stdio"){const Z=Y.command||"",U=Y.args||[];d([Z,...U].join(" "));const J=Object.entries(Y.env||{}).map(([oe,pe])=>({key:oe,value:String(pe)}));L(J)}else{const Z=Y.headers||{},U=Object.entries(Z).filter(([ye])=>ye.toLowerCase()!=="authorization").map(([ye,je])=>({key:ye,value:String(je)}));H(U);const J=Z.Authorization,oe=J?.startsWith("Bearer ");Y.useOAuth?(T("oauth"),h(Y.oauthScopes?.join(" ")||"mcp:*"),v(Y.clientId||""),b(Y.clientSecret||""),j(!!Y.clientId),l(ye=>({...ye,useOAuth:!0}))):oe?(T("bearer"),S(J.slice(7)),l(ye=>({...ye,useOAuth:!1}))):(T("none"),l(ye=>({...ye,useOAuth:!1})))}}},[n,s,t]);const F=Y=>Y.trim()?/^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$|^[a-zA-Z0-9]$/.test(Y.trim())?Y.trim().length<3?"Client ID must be at least 3 characters long":Y.trim().length>100?"Client ID must be less than 100 characters long":null:"Client ID should contain only letters, numbers, dots, hyphens, and underscores":"Client ID is required when using manual configuration",W=Y=>{if(Y&&Y.trim().length>0){if(Y.trim().length<8)return"Client secret should be at least 8 characters long for security";if(Y.trim().length>512)return"Client secret must be less than 512 characters long";if(Y===Y.toLowerCase()&&Y.length<16)return"Client secret should contain mixed case or be longer for security"}return null},G=Y=>{if(Y.preventDefault(),k==="oauth"&&R){const Z=F(g);if(Z){It.error(Z);return}if(x){const U=W(x);if(U){It.error(U);return}}}if(a.name){let Z={...a};if(a.type==="stdio"&&u){const U=u.split(" ").filter(ye=>ye.trim()),J=U[0]||"",oe=U.slice(1);Z={...Z,command:J,args:oe};const pe=O.reduce((ye,{key:je,value:Ne})=>(je&&Ne&&(ye[je]=Ne),ye),{});Z={...Z,env:pe}}if(a.type==="http"){const U=z.reduce((J,{key:oe,value:pe})=>(oe&&pe&&(J[oe]=pe),J),{});if(k==="none")Z={...Z,useOAuth:!1,headers:U},delete Z.oauthScopes;else if(k==="bearer"&&E)Z={...Z,headers:{...U,Authorization:`Bearer ${E}`},useOAuth:!1},delete Z.oauthScopes;else if(k==="oauth"&&a.useOAuth){const J=(p||"").split(" ").map(oe=>oe.trim()).filter(Boolean);Z={...Z,useOAuth:!0,clientId:R&&g.trim()||void 0,clientSecret:R&&x.trim()||void 0,headers:U},J.length>0?Z.oauthScopes=J:delete Z.oauthScopes}}n==="edit"?r(Z,s?.name):r(Z),P(),e()}},ee=()=>{P(),e()},P=()=>{l({name:"",type:"stdio",command:"",args:[],url:"",headers:{},env:{},useOAuth:!0,oauthScopes:[],clientId:""}),d(""),h(""),v(""),b(""),S(""),T("none"),j(!1),N(null),I(null),L([]),H([])},ie=()=>{L([...O,{key:"",value:""}])},ue=(Y,Z,U)=>{const J=[...O];J[Y][Z]=U,L(J)},D=Y=>{L(O.filter((Z,U)=>U!==Y))},ne=()=>{H([...z,{key:"",value:""}])},fe=(Y,Z,U)=>{const J=[...z];J[Y][Z]=U,H(J)},q=Y=>{H(z.filter((Z,U)=>U!==Y))},K=n==="add"?"Add MCP Server":"Edit MCP Server";return f.jsx(ua,{open:t,onOpenChange:ee,children:f.jsxs(da,{className:"max-w-md sm:max-w-lg",children:[f.jsx(fa,{className:"space-y-2",children:f.jsxs(ha,{className:"flex text-xl font-semibold",children:[f.jsx("img",{src:"/mcp.svg",alt:"MCP",className:"mr-2"})," ",K]})}),f.jsxs("form",{onSubmit:Y=>{i.capture("add_server_button_clicked",{location:"server_modal",platform:on(),environment:void 0}),G(Y)},className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Server Name"}),f.jsx(Dn,{value:a.name,onChange:Y=>l(Z=>({...Z,name:Y.target.value})),placeholder:"my-mcp-server",required:!0,className:"h-10"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Connection Type"}),a.type==="stdio"?f.jsxs("div",{className:"flex",children:[f.jsxs(nu,{value:a.type,onValueChange:Y=>l(Z=>({...Z,type:Y})),children:[f.jsx(su,{className:"w-22 rounded-r-none border-r-0 text-xs border-border",children:f.jsx(ru,{})}),f.jsxs(iu,{children:[f.jsx(ei,{value:"stdio",children:"STDIO"}),f.jsx(ei,{value:"http",children:"HTTP/SSE"})]})]}),f.jsx(Dn,{value:u,onChange:Y=>d(Y.target.value),placeholder:"npx -y @modelcontextprotocol/server-everything",required:!0,className:"flex-1 rounded-l-none text-sm border-border"})]}):f.jsxs("div",{className:"flex",children:[f.jsxs(nu,{value:a.type,onValueChange:Y=>l(Z=>({...Z,type:Y})),children:[f.jsx(su,{className:"w-22 rounded-r-none border-r-0 text-xs border-border",children:f.jsx(ru,{})}),f.jsxs(iu,{children:[f.jsx(ei,{value:"stdio",children:"STDIO"}),f.jsx(ei,{value:"http",children:"HTTP"})]})]}),f.jsx(Dn,{value:a.url,onChange:Y=>l(Z=>({...Z,url:Y.target.value})),placeholder:"http://localhost:8080/mcp",required:!0,className:"flex-1 rounded-l-none text-sm border-border"})]})]}),a.type==="stdio"&&f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Environment Variables"}),f.jsx(Pe,{type:"button",variant:"outline",size:"sm",onClick:ie,className:"text-xs",children:"Add Variable"})]}),O.length>0&&f.jsx("div",{className:"space-y-2 max-h-32 overflow-y-auto",children:O.map((Y,Z)=>f.jsxs("div",{className:"flex gap-2 items-center",children:[f.jsx(Dn,{value:Y.key,onChange:U=>ue(Z,"key",U.target.value),placeholder:"KEY",className:"flex-1 text-xs"}),f.jsx(Dn,{value:Y.value,onChange:U=>ue(Z,"value",U.target.value),placeholder:"value",className:"flex-1 text-xs"}),f.jsx(Pe,{type:"button",variant:"outline",size:"sm",onClick:()=>D(Z),className:"px-2 text-xs",children:"×"})]},Z))})]}),a.type==="http"&&f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Authentication"}),f.jsxs(nu,{value:k,onValueChange:Y=>{T(Y),l(Y==="oauth"?Z=>({...Z,useOAuth:!0}):Z=>({...Z,useOAuth:!1}))},children:[f.jsx(su,{className:"w-full",children:f.jsx(ru,{})}),f.jsxs(iu,{children:[f.jsx(ei,{value:"none",children:"No Authentication"}),f.jsx(ei,{value:"bearer",children:"Bearer Token"}),f.jsx(ei,{value:"oauth",children:"OAuth 2.0"})]})]})]}),k==="bearer"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Bearer Token"}),f.jsx(Dn,{type:"password",value:E,onChange:Y=>S(Y.target.value),placeholder:"Enter your bearer token",className:"h-10"})]}),k==="oauth"&&f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"OAuth Scopes"}),f.jsx(Dn,{value:p,onChange:Y=>h(Y.target.value),placeholder:"mcp:* or custom scopes separated by spaces",className:"h-10"}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Default: mcp:* (space-separated for multiple scopes)"})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx("input",{type:"checkbox",id:"useCustomClientId",checked:R,onChange:Y=>{j(Y.target.checked),Y.target.checked||(v(""),b(""),N(null),I(null))},className:"rounded"}),f.jsx("label",{htmlFor:"useCustomClientId",className:"text-sm font-medium text-foreground",children:"Use custom OAuth credentials"})]}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave unchecked to use the server's default OAuth flow"})]}),R&&f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Client ID"}),f.jsx(Dn,{value:g,onChange:Y=>{const Z=Y.target.value;v(Z);const U=F(Z);N(U)},placeholder:"Your OAuth Client ID",className:`h-10 ${A?"border-red-500":""}`}),A&&f.jsx("p",{className:"text-xs text-red-500",children:A})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Client Secret (Optional)"}),f.jsx(Dn,{type:"password",value:x,onChange:Y=>{const Z=Y.target.value;b(Z);const U=W(Z);I(U)},placeholder:"Your OAuth Client Secret",className:`h-10 ${M?"border-red-500":""}`}),M&&f.jsx("p",{className:"text-xs text-red-500",children:M}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional for public clients using PKCE"})]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Custom Headers"}),f.jsx(Pe,{type:"button",variant:"outline",size:"sm",onClick:ne,className:"text-xs",children:"Add Header"})]}),z.length>0&&f.jsx("div",{className:"space-y-2 max-h-32 overflow-y-auto",children:z.map((Y,Z)=>f.jsxs("div",{className:"flex gap-2 items-center",children:[f.jsx(Dn,{value:Y.key,onChange:U=>fe(Z,"key",U.target.value),placeholder:"Header-Name",className:"flex-1 text-xs"}),f.jsx(Dn,{value:Y.value,onChange:U=>fe(Z,"value",U.target.value),placeholder:"header-value",className:"flex-1 text-xs"}),f.jsx(Pe,{type:"button",variant:"outline",size:"sm",onClick:()=>q(Z),className:"px-2 text-xs",children:"×"})]},Z))}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Add custom HTTP headers for your MCP server connection (e.g. API-Key, X-Custom-Header)"})]})]}),f.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[f.jsx(Pe,{type:"button",variant:"outline",onClick:()=>{i.capture("cancel_button_clicked",{location:"server_modal",platform:on(),environment:void 0}),ee()},className:"px-4",children:"Cancel"}),f.jsx(Pe,{type:"submit",className:"px-4",children:n==="add"?"Add Server":"Update Server"})]})]})]})})}function Qo({className:t,...e}){return f.jsx("textarea",{"data-slot":"textarea",className:Oe("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",t),...e})}function Xc({className:t,...e}){return f.jsx(Jte,{"data-slot":"label",className:Oe("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",t),...e})}const Wue=h0("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Yue({className:t,variant:e,...n}){return f.jsx("div",{"data-slot":"alert",role:"alert",className:Oe(Wue({variant:e}),t),...n})}function Kue({className:t,...e}){return f.jsx("div",{"data-slot":"alert-description",className:Oe("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",t),...e})}function Xue(t){try{const e=JSON.parse(t);if(!e.mcpServers||typeof e.mcpServers!="object")throw new Error('Invalid JSON config: missing or invalid "mcpServers" property');const n=[];for(const[r,s]of Object.entries(e.mcpServers)){if(!s||typeof s!="object"){console.warn(`Skipping invalid server config for "${r}"`);continue}if(s.type==="sse"||s.url)n.push({name:r,type:"http",url:s.url||"",headers:{},env:{},useOAuth:!1});else if(s.command)n.push({name:r,type:"stdio",command:s.command,args:s.args||[],env:s.env||{}});else{console.warn(`Skipping server "${r}": missing required command`);continue}}return n}catch(e){throw e instanceof SyntaxError?new Error("Invalid JSON format: "+e.message):e}}function Que(t){try{const e=JSON.parse(t);if(!e.mcpServers||typeof e.mcpServers!="object")return{success:!1,error:'Missing or invalid "mcpServers" property'};if(Object.keys(e.mcpServers).length===0)return{success:!1,error:'No servers found in "mcpServers" object'};for(const[r,s]of Object.entries(e.mcpServers)){if(!s||typeof s!="object")return{success:!1,error:`Invalid server config for "${r}"`};const i=s,a=i.command&&typeof i.command=="string",l=i.url&&typeof i.url=="string",u=i.type==="sse";if(!a&&!l&&!u)return{success:!1,error:`Server "${r}" must have either "command" or "url" property`};if(a&&l)return{success:!1,error:`Server "${r}" cannot have both "command" and "url" properties`}}return{success:!0}}catch(e){return e instanceof SyntaxError?{success:!1,error:"Invalid JSON format: "+e.message}:{success:!1,error:"Unknown error: "+e.message}}}function Jue({isOpen:t,onClose:e,onImport:n}){const[r,s]=w.useState(""),[i,a]=w.useState(null),[l,u]=w.useState(!1),d=w.useRef(null),p=Qr(),h=k=>{const T=k.target.files?.[0];if(!T)return;if(T.type!=="application/json"&&!T.name.endsWith(".json")){It.error("Please select a valid JSON file");return}const R=new FileReader;R.onload=j=>{const A=j.target?.result;s(A),g(A)},R.readAsText(T)},g=k=>{if(!k.trim()){a(null);return}const T=Que(k);a(T)},v=k=>{s(k),g(k)},x=async()=>{if(!i?.success){It.error("Please fix the JSON validation errors before importing");return}u(!0);try{const k=Xue(r);if(k.length===0){It.error("No valid servers found in the JSON config");return}n(k),It.success(`Successfully imported ${k.length} server${k.length===1?"":"s"}`),b()}catch(k){const T=k instanceof Error?k.message:"Unknown error";It.error(`Failed to import servers: ${T}`)}finally{u(!1)}},b=()=>{s(""),a(null),u(!1),e()},E=()=>i?i.success?f.jsx(lf,{className:"h-4 w-4 text-green-500"}):f.jsx(Am,{className:"h-4 w-4 text-red-500"}):null,S=()=>i?i.success?f.jsx("span",{className:"text-green-600 dark:text-green-400",children:"Valid JSON config"}):f.jsx("span",{className:"text-red-600 dark:text-red-400",children:i.error}):null;return f.jsx(ua,{open:t,onOpenChange:b,children:f.jsxs(da,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[f.jsx(fa,{className:"space-y-2",children:f.jsxs(ha,{className:"flex text-xl font-semibold",children:[f.jsx("img",{src:"/mcp.svg",alt:"MCP",className:"mr-2"})," Import Servers from JSON"]})}),f.jsxs("div",{className:"flex-1 overflow-y-auto space-y-4",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-sm font-medium",children:"Upload JSON File"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("input",{ref:d,type:"file",accept:".json,application/json",onChange:h,className:"hidden"}),f.jsxs(Pe,{type:"button",variant:"outline",onClick:()=>d.current?.click(),className:"flex items-center gap-2",children:[f.jsx(Iie,{className:"h-4 w-4"}),"Choose File"]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx(Xc,{className:"text-sm font-medium",children:"JSON Configuration"}),i&&f.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[E(),S()]})]}),f.jsx(Qo,{value:r,onChange:k=>v(k.target.value),placeholder:"Paste your JSON configuration here or upload a file...",className:"min-h-[200px] font-mono text-sm"})]}),f.jsx(Ha,{className:"p-4 bg-muted/30",children:f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-medium",children:"Example JSON Format:"}),f.jsx("pre",{className:"text-xs text-muted-foreground overflow-x-auto",children:`{
@@ -1820,7 +1820,7 @@ An authorization_code was supplied for a login which did not originate at the ap
1820
1820
  `,...i.current()});return/^[\t ]/.test(d)&&(d=Ym(d.charCodeAt(0))+d.slice(1)),d=d?a+" "+d:a,n.options.closeAtx&&(d+=" "+a),u(),l(),d}$8.peek=$Se;function $8(t){return t.value||""}function $Se(){return"<"}z8.peek=zSe;function z8(t,e,n,r){const s=sj(n),i=s==='"'?"Quote":"Apostrophe",a=n.enter("image");let l=n.enter("label");const u=n.createTracker(r);let d=u.move("![");return d+=u.move(n.safe(t.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),l(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(l=n.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(n.safe(t.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(l=n.enter("destinationRaw"),d+=u.move(n.safe(t.url,{before:d,after:t.title?" ":")",...u.current()}))),l(),t.title&&(l=n.enter(`title${i}`),d+=u.move(" "+s),d+=u.move(n.safe(t.title,{before:d,after:s,...u.current()})),d+=u.move(s),l()),d+=u.move(")"),a(),d}function zSe(){return"!"}F8.peek=FSe;function F8(t,e,n,r){const s=t.referenceType,i=n.enter("imageReference");let a=n.enter("label");const l=n.createTracker(r);let u=l.move("![");const d=n.safe(t.alt,{before:u,after:"]",...l.current()});u+=l.move(d+"]["),a();const p=n.stack;n.stack=[],a=n.enter("reference");const h=n.safe(n.associationId(t),{before:u,after:"]",...l.current()});return a(),n.stack=p,i(),s==="full"||!d||d!==h?u+=l.move(h+"]"):s==="shortcut"?u=u.slice(0,-1):u+=l.move("]"),u}function FSe(){return"!"}U8.peek=USe;function U8(t,e,n){let r=t.value||"",s="`",i=-1;for(;new RegExp("(^|[^`])"+s+"([^`]|$)").test(r);)s+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i<n.unsafe.length;){const a=n.unsafe[i],l=n.compilePattern(a);let u;if(a.atBreak)for(;u=l.exec(r);){let d=u.index;r.charCodeAt(d)===10&&r.charCodeAt(d-1)===13&&d--,r=r.slice(0,d)+" "+r.slice(u.index+1)}}return s+r+s}function USe(){return"`"}function B8(t,e){const n=KR(t);return!!(!e.options.resourceLink&&t.url&&!t.title&&t.children&&t.children.length===1&&t.children[0].type==="text"&&(n===t.url||"mailto:"+n===t.url)&&/^[a-z][a-z+.-]+:/i.test(t.url)&&!/[\0- <>\u007F]/.test(t.url))}q8.peek=BSe;function q8(t,e,n,r){const s=sj(n),i=s==='"'?"Quote":"Apostrophe",a=n.createTracker(r);let l,u;if(B8(t,n)){const p=n.stack;n.stack=[],l=n.enter("autolink");let h=a.move("<");return h+=a.move(n.containerPhrasing(t,{before:h,after:">",...a.current()})),h+=a.move(">"),l(),n.stack=p,h}l=n.enter("link"),u=n.enter("label");let d=a.move("[");return d+=a.move(n.containerPhrasing(t,{before:d,after:"](",...a.current()})),d+=a.move("]("),u(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(u=n.enter("destinationLiteral"),d+=a.move("<"),d+=a.move(n.safe(t.url,{before:d,after:">",...a.current()})),d+=a.move(">")):(u=n.enter("destinationRaw"),d+=a.move(n.safe(t.url,{before:d,after:t.title?" ":")",...a.current()}))),u(),t.title&&(u=n.enter(`title${i}`),d+=a.move(" "+s),d+=a.move(n.safe(t.title,{before:d,after:s,...a.current()})),d+=a.move(s),u()),d+=a.move(")"),l(),d}function BSe(t,e,n){return B8(t,n)?"<":"["}V8.peek=qSe;function V8(t,e,n,r){const s=t.referenceType,i=n.enter("linkReference");let a=n.enter("label");const l=n.createTracker(r);let u=l.move("[");const d=n.containerPhrasing(t,{before:u,after:"]",...l.current()});u+=l.move(d+"]["),a();const p=n.stack;n.stack=[],a=n.enter("reference");const h=n.safe(n.associationId(t),{before:u,after:"]",...l.current()});return a(),n.stack=p,i(),s==="full"||!d||d!==h?u+=l.move(h+"]"):s==="shortcut"?u=u.slice(0,-1):u+=l.move("]"),u}function qSe(){return"["}function ij(t){const e=t.options.bullet||"*";if(e!=="*"&&e!=="+"&&e!=="-")throw new Error("Cannot serialize items with `"+e+"` for `options.bullet`, expected `*`, `+`, or `-`");return e}function VSe(t){const e=ij(t),n=t.options.bulletOther;if(!n)return e==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===e)throw new Error("Expected `bullet` (`"+e+"`) and `bulletOther` (`"+n+"`) to be different");return n}function HSe(t){const e=t.options.bulletOrdered||".";if(e!=="."&&e!==")")throw new Error("Cannot serialize items with `"+e+"` for `options.bulletOrdered`, expected `.` or `)`");return e}function H8(t){const e=t.options.rule||"*";if(e!=="*"&&e!=="-"&&e!=="_")throw new Error("Cannot serialize rules with `"+e+"` for `options.rule`, expected `*`, `-`, or `_`");return e}function GSe(t,e,n,r){const s=n.enter("list"),i=n.bulletCurrent;let a=t.ordered?HSe(n):ij(n);const l=t.ordered?a==="."?")":".":VSe(n);let u=e&&n.bulletLastUsed?a===n.bulletLastUsed:!1;if(!t.ordered){const p=t.children?t.children[0]:void 0;if((a==="*"||a==="-")&&p&&(!p.children||!p.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(u=!0),H8(n)===a&&p){let h=-1;for(;++h<t.children.length;){const g=t.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(a=l),n.bulletCurrent=a;const d=n.containerFlow(t,r);return n.bulletLastUsed=a,n.bulletCurrent=i,s(),d}function WSe(t){const e=t.options.listItemIndent||"one";if(e!=="tab"&&e!=="one"&&e!=="mixed")throw new Error("Cannot serialize items with `"+e+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return e}function YSe(t,e,n,r){const s=WSe(n);let i=n.bulletCurrent||ij(n);e&&e.type==="list"&&e.ordered&&(i=(typeof e.start=="number"&&e.start>-1?e.start:1)+(n.options.incrementListMarker===!1?0:e.children.indexOf(t))+i);let a=i.length+1;(s==="tab"||s==="mixed"&&(e&&e.type==="list"&&e.spread||t.spread))&&(a=Math.ceil(a/4)*4);const l=n.createTracker(r);l.move(i+" ".repeat(a-i.length)),l.shift(a);const u=n.enter("listItem"),d=n.indentLines(n.containerFlow(t,l.current()),p);return u(),d;function p(h,g,v){return g?(v?"":" ".repeat(a))+h:(v?i:i+" ".repeat(a-i.length))+h}}function KSe(t,e,n,r){const s=n.enter("paragraph"),i=n.enter("phrasing"),a=n.containerPhrasing(t,r);return i(),s(),a}const XSe=G0(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function QSe(t,e,n,r){return(t.children.some(function(a){return XSe(a)})?n.containerPhrasing:n.containerFlow).call(n,t,r)}function JSe(t){const e=t.options.strong||"*";if(e!=="*"&&e!=="_")throw new Error("Cannot serialize strong with `"+e+"` for `options.strong`, expected `*`, or `_`");return e}G8.peek=ZSe;function G8(t,e,n,r){const s=JSe(n),i=n.enter("strong"),a=n.createTracker(r),l=a.move(s+s);let u=a.move(n.containerPhrasing(t,{after:s,before:l,...a.current()}));const d=u.charCodeAt(0),p=bb(r.before.charCodeAt(r.before.length-1),d,s);p.inside&&(u=Ym(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=bb(r.after.charCodeAt(0),h,s);g.inside&&(u=u.slice(0,-1)+Ym(h));const v=a.move(s+s);return i(),n.attentionEncodeSurroundingInfo={after:g.outside,before:p.outside},l+u+v}function ZSe(t,e,n){return n.options.strong||"*"}function eEe(t,e,n,r){return n.safe(t.value,r)}function tEe(t){const e=t.options.ruleRepetition||3;if(e<3)throw new Error("Cannot serialize rules with repetition `"+e+"` for `options.ruleRepetition`, expected `3` or more");return e}function nEe(t,e,n){const r=(H8(n)+(n.options.ruleSpaces?" ":"")).repeat(tEe(n));return n.options.ruleSpaces?r.slice(0,-1):r}const W8={blockquote:kSe,break:S4,code:jSe,definition:OSe,emphasis:L8,hardBreak:S4,heading:LSe,html:$8,image:z8,imageReference:F8,inlineCode:U8,link:q8,linkReference:V8,list:GSe,listItem:YSe,paragraph:KSe,root:QSe,strong:G8,text:eEe,thematicBreak:nEe};function rEe(){return{enter:{table:sEe,tableData:E4,tableHeader:E4,tableRow:aEe},exit:{codeText:oEe,table:iEe,tableData:O1,tableHeader:O1,tableRow:O1}}}function sEe(t){const e=t._align;this.enter({type:"table",align:e.map(function(n){return n==="none"?null:n}),children:[]},t),this.data.inTable=!0}function iEe(t){this.exit(t),this.data.inTable=void 0}function aEe(t){this.enter({type:"tableRow",children:[]},t)}function O1(t){this.exit(t)}function E4(t){this.enter({type:"tableCell",children:[]},t)}function oEe(t){let e=this.resume();this.data.inTable&&(e=e.replace(/\\([\\|])/g,lEe));const n=this.stack[this.stack.length-1];n.type,n.value=e,this.exit(t)}function lEe(t,e){return e==="|"?e:t}function cEe(t){const e=t||{},n=e.tableCellPadding,r=e.tablePipeAlign,s=e.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
1821
1821
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:a,tableCell:u,tableRow:l}};function a(v,x,b,E){return d(p(v,b,E),v.align)}function l(v,x,b,E){const S=h(v,b,E),k=d([S]);return k.slice(0,k.indexOf(`
1822
1822
  `))}function u(v,x,b,E){const S=b.enter("tableCell"),k=b.enter("phrasing"),T=b.containerPhrasing(v,{...E,before:i,after:i});return k(),S(),T}function d(v,x){return SSe(v,{align:x,alignDelimiters:r,padding:n,stringLength:s})}function p(v,x,b){const E=v.children;let S=-1;const k=[],T=x.enter("table");for(;++S<E.length;)k[S]=h(E[S],x,b);return T(),k}function h(v,x,b){const E=v.children;let S=-1;const k=[],T=x.enter("tableRow");for(;++S<E.length;)k[S]=u(E[S],v,x,b);return T(),k}function g(v,x,b){let E=W8.inlineCode(v,x,b);return b.stack.includes("tableCell")&&(E=E.replace(/\|/g,"\\$&")),E}}function uEe(){return{exit:{taskListCheckValueChecked:k4,taskListCheckValueUnchecked:k4,paragraph:fEe}}}function dEe(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:hEe}}}function k4(t){const e=this.stack[this.stack.length-2];e.type,e.checked=t.type==="taskListCheckValueChecked"}function fEe(t){const e=this.stack[this.stack.length-2];if(e&&e.type==="listItem"&&typeof e.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=e.children;let i=-1,a;for(;++i<s.length;){const l=s[i];if(l.type==="paragraph"){a=l;break}}a===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(t)}function hEe(t,e,n,r){const s=t.children[0],i=typeof t.checked=="boolean"&&s&&s.type==="paragraph",a="["+(t.checked?"x":" ")+"] ",l=n.createTracker(r);i&&l.move(a);let u=W8.listItem(t,e,n,{...r,...l.current()});return i&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(p){return p+a}}function pEe(){return[Gwe(),hSe(),vSe(),rEe(),uEe()]}function mEe(t){return{extensions:[Wwe(),pSe(t),ySe(),cEe(t),dEe()]}}const gEe={tokenize:wEe,partial:!0},Y8={tokenize:SEe,partial:!0},K8={tokenize:EEe,partial:!0},X8={tokenize:kEe,partial:!0},vEe={tokenize:TEe,partial:!0},Q8={name:"wwwAutolink",tokenize:bEe,previous:Z8},J8={name:"protocolAutolink",tokenize:_Ee,previous:e7},Jo={name:"emailAutolink",tokenize:xEe,previous:t7},Za={};function yEe(){return{text:Za}}let qc=48;for(;qc<123;)Za[qc]=Jo,qc++,qc===58?qc=65:qc===91&&(qc=97);Za[43]=Jo;Za[45]=Jo;Za[46]=Jo;Za[95]=Jo;Za[72]=[Jo,J8];Za[104]=[Jo,J8];Za[87]=[Jo,Q8];Za[119]=[Jo,Q8];function xEe(t,e,n){const r=this;let s,i;return a;function a(h){return!kC(h)||!t7.call(r,r.previous)||aj(r.events)?n(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),l(h))}function l(h){return kC(h)?(t.consume(h),l):h===64?(t.consume(h),u):n(h)}function u(h){return h===46?t.check(vEe,p,d)(h):h===45||h===95||as(h)?(i=!0,t.consume(h),u):p(h)}function d(h){return t.consume(h),s=!0,u}function p(h){return i&&s&&ms(r.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),e(h)):n(h)}}function bEe(t,e,n){const r=this;return s;function s(a){return a!==87&&a!==119||!Z8.call(r,r.previous)||aj(r.events)?n(a):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(gEe,t.attempt(Y8,t.attempt(K8,i),n),n)(a))}function i(a){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),e(a)}}function _Ee(t,e,n){const r=this;let s="",i=!1;return a;function a(h){return(h===72||h===104)&&e7.call(r,r.previous)&&!aj(r.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),s+=String.fromCodePoint(h),t.consume(h),l):n(h)}function l(h){if(ms(h)&&s.length<5)return s+=String.fromCodePoint(h),t.consume(h),l;if(h===58){const g=s.toLowerCase();if(g==="http"||g==="https")return t.consume(h),u}return n(h)}function u(h){return h===47?(t.consume(h),i?d:(i=!0,u)):n(h)}function d(h){return h===null||vb(h)||_n(h)||Au(h)||q0(h)?n(h):t.attempt(Y8,t.attempt(K8,p),n)(h)}function p(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),e(h)}}function wEe(t,e,n){let r=0;return s;function s(a){return(a===87||a===119)&&r<3?(r++,t.consume(a),s):a===46&&r===3?(t.consume(a),i):n(a)}function i(a){return a===null?n(a):e(a)}}function SEe(t,e,n){let r,s,i;return a;function a(d){return d===46||d===95?t.check(X8,u,l)(d):d===null||_n(d)||Au(d)||d!==45&&q0(d)?u(d):(i=!0,t.consume(d),a)}function l(d){return d===95?r=!0:(s=r,r=void 0),t.consume(d),a}function u(d){return s||r||!i?n(d):e(d)}}function EEe(t,e){let n=0,r=0;return s;function s(a){return a===40?(n++,t.consume(a),s):a===41&&r<n?i(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?t.check(X8,e,i)(a):a===null||_n(a)||Au(a)?e(a):(t.consume(a),s)}function i(a){return a===41&&r++,t.consume(a),s}}function kEe(t,e,n){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(t.consume(l),r):l===38?(t.consume(l),i):l===93?(t.consume(l),s):l===60||l===null||_n(l)||Au(l)?e(l):n(l)}function s(l){return l===null||l===40||l===91||_n(l)||Au(l)?e(l):r(l)}function i(l){return ms(l)?a(l):n(l)}function a(l){return l===59?(t.consume(l),r):ms(l)?(t.consume(l),a):n(l)}}function TEe(t,e,n){return r;function r(i){return t.consume(i),s}function s(i){return as(i)?n(i):e(i)}}function Z8(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||_n(t)}function e7(t){return!ms(t)}function t7(t){return!(t===47||kC(t))}function kC(t){return t===43||t===45||t===46||t===95||as(t)}function aj(t){let e=t.length,n=!1;for(;e--;){const r=t[e][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return t.length>0&&!n&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const CEe={tokenize:IEe,partial:!0};function AEe(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:MEe,continuation:{tokenize:OEe},exit:PEe}},text:{91:{name:"gfmFootnoteCall",tokenize:jEe},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:NEe,resolveTo:REe}}}}function NEe(t,e,n){const r=this;let s=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const u=r.events[s][1];if(u.type==="labelImage"){a=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return l;function l(u){if(!a||!a._balanced)return n(u);const d=ia(r.sliceSerialize({start:a.end,end:r.now()}));return d.codePointAt(0)!==94||!i.includes(d.slice(1))?n(u):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(u),t.exit("gfmFootnoteCallLabelMarker"),e(u))}}function REe(t,e){let n=t.length;for(;n--;)if(t[n][1].type==="labelImage"&&t[n][0]==="enter"){t[n][1];break}t[n+1][1].type="data",t[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},t[n+3][1].start),end:Object.assign({},t[t.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},t[n+3][1].end),end:Object.assign({},t[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},t[t.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},l=[t[n+1],t[n+2],["enter",r,e],t[n+3],t[n+4],["enter",s,e],["exit",s,e],["enter",i,e],["enter",a,e],["exit",a,e],["exit",i,e],t[t.length-2],t[t.length-1],["exit",r,e]];return t.splice(n,t.length-n+1,...l),t}function jEe(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,a;return l;function l(h){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?n(h):(t.enter("gfmFootnoteCallMarker"),t.consume(h),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",d)}function d(h){if(i>999||h===93&&!a||h===null||h===91||_n(h))return n(h);if(h===93){t.exit("chunkString");const g=t.exit("gfmFootnoteCallString");return s.includes(ia(r.sliceSerialize(g)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),e):n(h)}return _n(h)||(a=!0),i++,t.consume(h),h===92?p:d}function p(h){return h===91||h===92||h===93?(t.consume(h),i++,d):d(h)}}function MEe(t,e,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,a=0,l;return u;function u(x){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(x),t.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(x){return x===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(x),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",p):n(x)}function p(x){if(a>999||x===93&&!l||x===null||x===91||_n(x))return n(x);if(x===93){t.exit("chunkString");const b=t.exit("gfmFootnoteDefinitionLabelString");return i=ia(r.sliceSerialize(b)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(x),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),g}return _n(x)||(l=!0),a++,t.consume(x),x===92?h:p}function h(x){return x===91||x===92||x===93?(t.consume(x),a++,p):p(x)}function g(x){return x===58?(t.enter("definitionMarker"),t.consume(x),t.exit("definitionMarker"),s.includes(i)||s.push(i),Zt(t,v,"gfmFootnoteDefinitionWhitespace")):n(x)}function v(x){return e(x)}}function OEe(t,e,n){return t.check(Ag,e,t.attempt(CEe,e,n))}function PEe(t){t.exit("gfmFootnoteDefinition")}function IEe(t,e,n){const r=this;return Zt(t,s,"gfmFootnoteDefinitionIndent",5);function s(i){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?e(i):n(i)}}function DEe(t){let n=(t||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(a,l){let u=-1;for(;++u<a.length;)if(a[u][0]==="enter"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._close){let d=u;for(;d--;)if(a[d][0]==="exit"&&a[d][1].type==="strikethroughSequenceTemporary"&&a[d][1]._open&&a[u][1].end.offset-a[u][1].start.offset===a[d][1].end.offset-a[d][1].start.offset){a[u][1].type="strikethroughSequence",a[d][1].type="strikethroughSequence";const p={type:"strikethrough",start:Object.assign({},a[d][1].start),end:Object.assign({},a[u][1].end)},h={type:"strikethroughText",start:Object.assign({},a[d][1].end),end:Object.assign({},a[u][1].start)},g=[["enter",p,l],["enter",a[d][1],l],["exit",a[d][1],l],["enter",h,l]],v=l.parser.constructs.insideSpan.null;v&&oi(g,g.length,0,V0(v,a.slice(d+1,u),l)),oi(g,g.length,0,[["exit",h,l],["enter",a[u][1],l],["exit",a[u][1],l],["exit",p,l]]),oi(a,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<a.length;)a[u][1].type==="strikethroughSequenceTemporary"&&(a[u][1].type="data");return a}function i(a,l,u){const d=this.previous,p=this.events;let h=0;return g;function g(x){return d===126&&p[p.length-1][1].type!=="characterEscape"?u(x):(a.enter("strikethroughSequenceTemporary"),v(x))}function v(x){const b=Mf(d);if(x===126)return h>1?u(x):(a.consume(x),h++,v);if(h<2&&!n)return u(x);const E=a.exit("strikethroughSequenceTemporary"),S=Mf(x);return E._open=!S||S===2&&!!b,E._close=!b||b===2&&!!S,l(x)}}}class LEe{constructor(){this.map=[]}add(e,n,r){$Ee(this,e,n,r)}consume(e){if(this.map.sort(function(i,a){return i[0]-a[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(e.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),e.length=this.map[n][0];r.push(e.slice()),e.length=0;let s=r.pop();for(;s;){for(const i of s)e.push(i);s=r.pop()}this.map.length=0}}function $Ee(t,e,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<t.map.length;){if(t.map[s][0]===e){t.map[s][1]+=n,t.map[s][2].push(...r);return}s+=1}t.map.push([e,n,r])}}function zEe(t,e){let n=!1;const r=[];for(;e<t.length;){const s=t[e];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(t[e+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(t[e-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);e+=1}return r}function FEe(){return{flow:{null:{name:"table",tokenize:UEe,resolveAll:BEe}}}}function UEe(t,e,n){const r=this;let s=0,i=0,a;return l;function l(O){let L=r.events.length-1;for(;L>-1;){const V=r.events[L][1].type;if(V==="lineEnding"||V==="linePrefix")L--;else break}const z=L>-1?r.events[L][1].type:null,H=z==="tableHead"||z==="tableRow"?A:u;return H===A&&r.parser.lazy[r.now().line]?n(O):H(O)}function u(O){return t.enter("tableHead"),t.enter("tableRow"),d(O)}function d(O){return O===124||(a=!0,i+=1),p(O)}function p(O){return O===null?n(O):dt(O)?i>1?(i=0,r.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(O),t.exit("lineEnding"),v):n(O):Wt(O)?Zt(t,p,"whitespace")(O):(i+=1,a&&(a=!1,s+=1),O===124?(t.enter("tableCellDivider"),t.consume(O),t.exit("tableCellDivider"),a=!0,p):(t.enter("data"),h(O)))}function h(O){return O===null||O===124||_n(O)?(t.exit("data"),p(O)):(t.consume(O),O===92?g:h)}function g(O){return O===92||O===124?(t.consume(O),h):h(O)}function v(O){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(O):(t.enter("tableDelimiterRow"),a=!1,Wt(O)?Zt(t,x,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):x(O))}function x(O){return O===45||O===58?E(O):O===124?(a=!0,t.enter("tableCellDivider"),t.consume(O),t.exit("tableCellDivider"),b):j(O)}function b(O){return Wt(O)?Zt(t,E,"whitespace")(O):E(O)}function E(O){return O===58?(i+=1,a=!0,t.enter("tableDelimiterMarker"),t.consume(O),t.exit("tableDelimiterMarker"),S):O===45?(i+=1,S(O)):O===null||dt(O)?R(O):j(O)}function S(O){return O===45?(t.enter("tableDelimiterFiller"),k(O)):j(O)}function k(O){return O===45?(t.consume(O),k):O===58?(a=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(O),t.exit("tableDelimiterMarker"),T):(t.exit("tableDelimiterFiller"),T(O))}function T(O){return Wt(O)?Zt(t,R,"whitespace")(O):R(O)}function R(O){return O===124?x(O):O===null||dt(O)?!a||s!==i?j(O):(t.exit("tableDelimiterRow"),t.exit("tableHead"),e(O)):j(O)}function j(O){return n(O)}function A(O){return t.enter("tableRow"),N(O)}function N(O){return O===124?(t.enter("tableCellDivider"),t.consume(O),t.exit("tableCellDivider"),N):O===null||dt(O)?(t.exit("tableRow"),e(O)):Wt(O)?Zt(t,N,"whitespace")(O):(t.enter("data"),M(O))}function M(O){return O===null||O===124||_n(O)?(t.exit("data"),N(O)):(t.consume(O),O===92?I:M)}function I(O){return O===92||O===124?(t.consume(O),M):M(O)}}function BEe(t,e){let n=-1,r=!0,s=0,i=[0,0,0,0],a=[0,0,0,0],l=!1,u=0,d,p,h;const g=new LEe;for(;++n<t.length;){const v=t[n],x=v[1];v[0]==="enter"?x.type==="tableHead"?(l=!1,u!==0&&(T4(g,e,u,d,p),p=void 0,u=0),d={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},g.add(n,0,[["enter",d,e]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(r=!0,h=void 0,i=[0,0,0,0],a=[0,n+1,0,0],l&&(l=!1,p={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)},g.add(n,0,[["enter",p,e]])),s=x.type==="tableDelimiterRow"?2:p?3:1):s&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(i[1]!==0&&(a[0]=a[1],h=_y(g,e,i,s,void 0,h),i=[0,0,0,0]),a[2]=n)):x.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(a[0]=a[1],h=_y(g,e,i,s,void 0,h)),i=a,a=[i[1],n,0,0])):x.type==="tableHead"?(l=!0,u=n):x.type==="tableRow"||x.type==="tableDelimiterRow"?(u=n,i[1]!==0?(a[0]=a[1],h=_y(g,e,i,s,n,h)):a[1]!==0&&(h=_y(g,e,a,s,n,h)),s=0):s&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(a[3]=n)}for(u!==0&&T4(g,e,u,d,p),g.consume(e.events),n=-1;++n<e.events.length;){const v=e.events[n];v[0]==="enter"&&v[1].type==="table"&&(v[1]._align=zEe(e.events,n))}return t}function _y(t,e,n,r,s,i){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",l="tableContent";n[0]!==0&&(i.end=Object.assign({},Bd(e.events,n[0])),t.add(n[0],0,[["exit",i,e]]));const u=Bd(e.events,n[1]);if(i={type:a,start:Object.assign({},u),end:Object.assign({},u)},t.add(n[1],0,[["enter",i,e]]),n[2]!==0){const d=Bd(e.events,n[2]),p=Bd(e.events,n[3]),h={type:l,start:Object.assign({},d),end:Object.assign({},p)};if(t.add(n[2],0,[["enter",h,e]]),r!==2){const g=e.events[n[2]],v=e.events[n[3]];if(g[1].end=Object.assign({},v[1].end),g[1].type="chunkText",g[1].contentType="text",n[3]>n[2]+1){const x=n[2]+1,b=n[3]-n[2]-1;t.add(x,b,[])}}t.add(n[3]+1,0,[["exit",h,e]])}return s!==void 0&&(i.end=Object.assign({},Bd(e.events,s)),t.add(s,0,[["exit",i,e]]),i=void 0),i}function T4(t,e,n,r,s){const i=[],a=Bd(e.events,n);s&&(s.end=Object.assign({},a),i.push(["exit",s,e])),r.end=Object.assign({},a),i.push(["exit",r,e]),t.add(n+1,0,i)}function Bd(t,e){const n=t[e],r=n[0]==="enter"?"start":"end";return n[1][r]}const qEe={name:"tasklistCheck",tokenize:HEe};function VEe(){return{text:{91:qEe}}}function HEe(t,e,n){const r=this;return s;function s(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(t.enter("taskListCheck"),t.enter("taskListCheckMarker"),t.consume(u),t.exit("taskListCheckMarker"),i)}function i(u){return _n(u)?(t.enter("taskListCheckValueUnchecked"),t.consume(u),t.exit("taskListCheckValueUnchecked"),a):u===88||u===120?(t.enter("taskListCheckValueChecked"),t.consume(u),t.exit("taskListCheckValueChecked"),a):n(u)}function a(u){return u===93?(t.enter("taskListCheckMarker"),t.consume(u),t.exit("taskListCheckMarker"),t.exit("taskListCheck"),l):n(u)}function l(u){return dt(u)?e(u):Wt(u)?t.check({tokenize:GEe},e,n)(u):n(u)}}function GEe(t,e,n){return Zt(t,r,"whitespace");function r(s){return s===null?n(s):e(s)}}function WEe(t){return f8([yEe(),AEe(),DEe(t),FEe(),VEe()])}const YEe={};function KEe(t){const e=this,n=t||YEe,r=e.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(WEe(n)),i.push(pEe()),a.push(mEe(n))}function XEe({node:t,inline:e,className:n,children:r,...s}){return e?f.jsx("code",{className:`${n} text-sm bg-zinc-100 dark:bg-zinc-800 py-0.5 px-1 rounded-md`,...s,children:r}):f.jsx("div",{className:"not-prose flex flex-col",children:f.jsx("div",{...s,className:"text-sm w-full overflow-x-auto dark:bg-zinc-900 p-4 border border-zinc-200 dark:border-zinc-700 rounded-xl dark:text-zinc-50 text-zinc-900 font-mono whitespace-pre-wrap break-words",children:r})})}const QEe={code:XEe,pre:({children:t})=>f.jsx(f.Fragment,{children:t}),img:({src:t,alt:e,...n})=>{if(!t)return null;const[r,s]=w.useState(!1),[i,a]=w.useState(!1);return i?f.jsxs("div",{className:"my-4 p-4 bg-muted/50 rounded-lg border border-border/30 text-center text-muted-foreground",children:["Failed to load image: ",e||"Image"]}):f.jsx("div",{className:"my-4 flex justify-center",children:f.jsx("img",{src:t,alt:e||"Image",className:`max-w-full h-auto rounded-lg border border-border/30 shadow-sm cursor-pointer transition-all hover:shadow-md ${r?"max-h-none":"max-h-96"}`,loading:"lazy",onClick:()=>s(!r),onError:()=>a(!0),title:r?"Click to collapse":"Click to expand",...n})})},ol:({children:t,...e})=>f.jsx("ol",{className:"list-decimal list-outside ml-4",...e,children:t}),li:({children:t,...e})=>f.jsx("li",{className:"py-1",...e,children:t}),ul:({children:t,...e})=>f.jsx("ul",{className:"list-decimal list-outside ml-4",...e,children:t}),strong:({children:t,...e})=>f.jsx("span",{className:"font-semibold",...e,children:t}),a:({children:t,...e})=>f.jsx("a",{className:"text-blue-500 hover:underline",target:"_blank",rel:"noreferrer",...e,children:t}),h1:({children:t,...e})=>f.jsx("h1",{className:"text-3xl font-semibold mt-6 mb-2",...e,children:t}),h2:({children:t,...e})=>f.jsx("h2",{className:"text-2xl font-semibold mt-6 mb-2",...e,children:t}),h3:({children:t,...e})=>f.jsx("h3",{className:"text-xl font-semibold mt-6 mb-2",...e,children:t}),h4:({children:t,...e})=>f.jsx("h4",{className:"text-lg font-semibold mt-6 mb-2",...e,children:t}),h5:({children:t,...e})=>f.jsx("h5",{className:"text-base font-semibold mt-6 mb-2",...e,children:t}),h6:({children:t,...e})=>f.jsx("h6",{className:"text-sm font-semibold mt-6 mb-2",...e,children:t})},JEe=[KEe],ZEe=({children:t})=>f.jsx(Dwe,{remarkPlugins:JEe,components:QEe,children:t}),C4=ZEe;function A4({message:t,onSave:e,onCancel:n}){const[r,s]=w.useState(t.content),i=w.useRef(null);w.useEffect(()=>{i.current&&(i.current.focus(),i.current.select(),a())},[]);const a=()=>{i.current&&(i.current.style.height="auto",i.current.style.height=`${i.current.scrollHeight}px`)},l=()=>{r.trim()!==t.content.trim()?e(r.trim()):n()},u=d=>{d.key==="Enter"&&(d.metaKey||d.ctrlKey)&&(d.preventDefault(),l()),d.key==="Escape"&&(d.preventDefault(),n())};return f.jsxs("div",{className:"w-full space-y-3",children:[f.jsx(Qo,{ref:i,value:r,onChange:d=>{s(d.target.value),a()},onKeyDown:u,className:"min-h-[100px] resize-none",placeholder:"Edit your message..."}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx(Pe,{variant:"outline",size:"sm",onClick:n,children:"Cancel"}),f.jsx(Pe,{size:"sm",onClick:l,disabled:!r.trim(),children:"Save"})]})]})}function N4({data:t,className:e}){const[n,r]=w.useState(!1),s=JSON.stringify(t,null,2),i=async()=>{try{await navigator.clipboard.writeText(s),r(!0),setTimeout(()=>r(!1),2e3)}catch(l){console.error("Failed to copy:",l)}},a=l=>l.replace(/"([^"]+)":/g,'<span class="text-blue-600/70 dark:text-blue-400/70">"$1"</span>:').replace(/: "([^"]*)"/g,': <span class="text-foreground">"$1"</span>').replace(/: (true|false)/g,': <span class="text-purple-600/70 dark:text-purple-400/70">$1</span>').replace(/: (null)/g,': <span class="text-muted-foreground/60">$1</span>').replace(/: (-?\d+(?:\.\d+)?)/g,': <span class="text-orange-600/70 dark:text-orange-400/70">$1</span>');return f.jsxs("div",{className:Oe("relative group",e),children:[f.jsx("button",{onClick:i,className:"absolute top-2 right-2 p-1.5 rounded-md bg-background/80 backdrop-blur-sm border opacity-0 group-hover:opacity-100 transition-opacity hover:bg-muted",title:"Copy JSON",children:n?f.jsx(Ri,{className:"h-3 w-3 text-green-600/70 dark:text-green-400/70"}):f.jsx(zo,{className:"h-3 w-3"})}),f.jsx("pre",{className:"text-xs font-mono whitespace-pre-wrap overflow-x-auto p-3 bg-muted/20 rounded-md border",children:f.jsx("code",{dangerouslySetInnerHTML:{__html:a(s)}})})]})}function n7({data:t,depth:e=0}){const[n,r]=w.useState(e<2);if(typeof t!="object"||t===null)return f.jsx("span",{className:Oe("text-sm",typeof t=="string"&&"text-foreground",typeof t=="number"&&"text-orange-600/70 dark:text-orange-400/70",typeof t=="boolean"&&"text-purple-600/70 dark:text-purple-400/70",t===null&&"text-muted-foreground/60"),children:typeof t=="string"?`"${t}"`:String(t)});const s=Array.isArray(t),i=s?t.map((u,d)=>[d,u]):Object.entries(t),a=s?"[":"{",l=s?"]":"}";return i.length===0?f.jsxs("span",{className:"text-sm text-muted-foreground",children:[a,l]}):f.jsxs("div",{className:"text-sm",children:[f.jsxs("button",{onClick:()=>r(!n),className:"flex items-center gap-1 hover:bg-muted/50 rounded px-1 transition-colors",children:[n?f.jsx(cc,{className:"h-3 w-3"}):f.jsx(la,{className:"h-3 w-3"}),f.jsxs("span",{className:"text-muted-foreground",children:[a," ",!n&&`${i.length} items`]})]}),n&&f.jsx("div",{className:"ml-4 border-l border-border pl-2 space-y-1",children:i.map(([u,d])=>f.jsxs("div",{className:"flex gap-2",children:[f.jsxs("span",{className:"text-blue-600/70 dark:text-blue-400/70 font-medium min-w-0 flex-shrink-0",children:[s?`[${u}]`:`"${u}"`,":"]}),f.jsx("div",{className:"min-w-0 flex-1",children:f.jsx(n7,{data:d,depth:e+1})})]},u))}),n&&f.jsx("span",{className:"text-muted-foreground ml-4",children:l})]})}function R4({toolCall:t,toolResult:e,className:n,serverConfigs:r,onCallTool:s,onSendFollowup:i,toolMeta:a,serverId:l}){const[u,d]=w.useState(!1),[p,h]=w.useState(!1),v=e?e.error?"error":"completed":t.status,x=()=>{switch(v){case"completed":return f.jsxs("div",{className:"relative",children:[f.jsx(lf,{className:"h-4 w-4 text-green-600/70 dark:text-green-400/70"}),f.jsx("div",{className:"absolute inset-0 animate-ping",children:f.jsx(lf,{className:"h-4 w-4 text-green-600/70 dark:text-green-400/70 opacity-20"})})]});case"error":return f.jsxs("div",{className:"relative",children:[f.jsx(cf,{className:"h-4 w-4 text-red-600/70 dark:text-red-400/70"}),f.jsx("div",{className:"absolute inset-0 animate-pulse",children:f.jsx(cf,{className:"h-4 w-4 text-red-600/70 dark:text-red-400/70 opacity-30"})})]});case"executing":return f.jsxs("div",{className:"relative",children:[f.jsx(fI,{className:"h-4 w-4 text-blue-600/70 dark:text-blue-400/70 animate-spin"}),f.jsx("div",{className:"absolute inset-0 animate-ping",children:f.jsx("div",{className:"h-4 w-4 bg-blue-600/30 dark:bg-blue-400/30 rounded-full"})})]});default:return f.jsx(fI,{className:"h-4 w-4 text-muted-foreground/60"})}};return f.jsxs("div",{className:Oe("border rounded-lg bg-gradient-to-br from-muted/20 to-muted/40 backdrop-blur-sm shadow-sm hover:shadow-md transition-all duration-200",v==="completed"&&"border-green-200/50 dark:border-green-800/50",v==="error"&&"border-red-200/50 dark:border-red-800/50",v==="executing"&&"border-blue-200/50 dark:border-blue-800/50 shadow-md animate-pulse",n),children:[f.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-muted/30 transition-all duration-200 rounded-t-lg",children:[f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("div",{className:"p-2 rounded-md bg-background/50 border",children:f.jsx(N0,{className:"h-4 w-4 text-muted-foreground"})}),f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsx("span",{className:"font-semibold text-sm",children:t.name}),v==="executing"&&f.jsx("span",{className:"text-xs text-blue-600/70 dark:text-blue-400/70 font-medium",children:"Running..."}),x()]})]}),f.jsx("div",{className:"flex items-center gap-2",children:u?f.jsx(cc,{className:"h-4 w-4 text-muted-foreground"}):f.jsx(la,{className:"h-4 w-4 text-muted-foreground"})})]}),u&&f.jsxs("div",{className:"border-t bg-background/30 backdrop-blur-sm",children:[Object.keys(t.parameters).length>0&&f.jsxs("div",{className:"p-4 border-b border-border/50",children:[f.jsxs("div",{className:"flex items-center justify-between mb-3",children:[f.jsxs("h4",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[f.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-600/70 dark:bg-blue-400/70"}),"Parameters"]}),f.jsx("button",{onClick:()=>h(!p),className:"text-xs text-muted-foreground hover:text-foreground transition-colors px-2 py-1 rounded bg-muted/50 hover:bg-muted",children:p?"Raw JSON":"Tree View"})]}),p?f.jsx(n7,{data:t.parameters}):f.jsx(N4,{data:t.parameters})]}),e&&f.jsxs("div",{className:"p-4",children:[f.jsxs("h4",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-3 flex items-center gap-2",children:[f.jsx("div",{className:Oe("w-2 h-2 rounded-full",e.error?"bg-red-600/70 dark:bg-red-400/70":"bg-green-600/70 dark:bg-green-400/70")}),e.error?"Error":"Result"]}),f.jsx("div",{children:e.error?f.jsx("div",{className:"bg-red-50/30 dark:bg-red-950/20 border border-red-200/50 dark:border-red-800/50 rounded-lg p-4",children:f.jsxs("div",{className:"flex items-start gap-3",children:[f.jsx(cf,{className:"h-5 w-5 text-red-600/70 dark:text-red-400/70 flex-shrink-0 mt-0.5"}),f.jsxs("div",{children:[f.jsx("p",{className:"font-medium text-foreground mb-1",children:"Tool execution failed"}),f.jsx("p",{className:"text-muted-foreground text-sm",children:e.error})]})]})}):f.jsxs("div",{className:"bg-green-50/30 dark:bg-green-950/20 border border-green-200/50 dark:border-green-800/50 rounded-lg",children:[f.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-green-100/30 dark:bg-green-900/20 border-b border-green-200/50 dark:border-green-800/50",children:[f.jsx(lf,{className:"h-4 w-4 text-green-600/70 dark:text-green-400/70"}),f.jsx("span",{className:"text-sm font-medium text-foreground",children:"Tool executed successfully"})]}),f.jsx("div",{className:"p-4",children:(()=>{const b=R=>{if(!R)return null;const j=Array.isArray(R)?R[0]:R;if(!j)return null;const A=j?.output?.value;if(A&&typeof A=="object"){const I=A.content;if(Array.isArray(I)){for(const L of I)if(L?.type==="resource"&&L?.resource?.uri&&typeof L.resource.uri=="string"&&L.resource.uri.startsWith("ui://"))return L.resource}const O=A.structuredContent?.result;if(Array.isArray(O)){for(const L of O)if(L?.type==="resource"&&L?.resource?.uri&&typeof L.resource.uri=="string"&&L.resource.uri.startsWith("ui://"))return L.resource}}const N=j?.resource;if(N&&typeof N=="object"&&typeof N.uri=="string"&&N.uri.startsWith("ui://"))return N;const M=j?.content;if(Array.isArray(M)){for(const I of M)if(I?.type==="resource"&&I?.resource?.uri&&typeof I.resource.uri=="string"&&I.resource.uri.startsWith("ui://"))return I.resource}return null},E=e?.result,S=a?.["openai/outputTemplate"];if(S&&typeof S=="string"){const R=l||e.serverId;return f.jsx(Qq,{componentUrl:S,toolCall:t,toolResult:e,onCallTool:s,onSendFollowup:i,serverId:R,toolMeta:a})}const k=b(E);if(k)return f.jsx(UN,{resource:k,htmlProps:{autoResizeIframe:!0,style:{width:"100%",overflow:"visible"}},onUIAction:async R=>{if(R.type==="tool"&&R.payload?.toolName){const j=(()=>{if(r&&typeof r=="object"&&Object.keys(r).length===1)return Object.keys(r)[0]})();fetch("/api/mcp/tools/execute",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({toolName:R.payload.toolName,parameters:R.payload.params||{},...j?{serverId:j}:{}})}).catch(()=>{})}else R.type==="link"&&R.payload?.url&&window.open(R.payload.url,"_blank","noopener,noreferrer");return{status:"handled"}}});const T=E?.result||E;return typeof T=="object"?f.jsx(N4,{data:T}):f.jsx("div",{className:"text-sm text-foreground bg-muted/30 p-3 rounded border",children:String(T)})})()})]})})]})]})]})}const e1e="/claude_logo.png",t1e="/openai_logo.png",n1e="/deepseek_logo.svg",r1e="/google_logo.png",s1e="/meta_logo.svg",j4="/ollama_logo.svg",M4="/ollama_dark.png",O4="/grok_light.svg",P4="/grok_dark.png",r7=(t,e)=>{switch(t){case"anthropic":return e1e;case"openai":return t1e;case"deepseek":return n1e;case"google":return r1e;case"ollama":return e==="dark"||e==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?M4:j4;case"meta":return s1e;case"x-ai":return e==="dark"||e==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?P4:O4;default:return null}},i1e=(t,e)=>r7(t.provider,e),a1e=t=>{switch(t){case"anthropic":return"text-orange-600 dark:text-orange-400";case"openai":return"text-green-600 dark:text-green-400";case"deepseek":return"text-blue-600 dark:text-blue-400";case"google":return"text-red-600 dark:text-red-400";case"ollama":return"text-gray-600 dark:text-gray-400";case"x-ai":return"text-purple-600 dark:text-purple-400";default:return"text-blue-600 dark:text-blue-400"}},I4=t=>{let e;const n=new Set,r=(d,p)=>{const h=typeof d=="function"?d(e):d;if(!Object.is(h,e)){const g=e;e=p??(typeof h!="object"||h===null)?h:Object.assign({},e,h),n.forEach(v=>v(e,g))}},s=()=>e,l={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d))},u=e=t(r,s,l);return l},s7=t=>t?I4(t):I4,o1e=t=>t;function i7(t,e=o1e){const n=Ee.useSyncExternalStore(t.subscribe,Ee.useCallback(()=>e(t.getState()),[t,e]),Ee.useCallback(()=>e(t.getInitialState()),[t,e]));return Ee.useDebugValue(n),n}const D4=t=>{const e=s7(t),n=r=>i7(e,r);return Object.assign(n,e),n},l1e=t=>t?D4(t):D4,c1e=t=>s7()(e=>({themeMode:t?.themeMode??"light",themePreset:t?.themePreset??"default",setThemeMode:n=>e({themeMode:n}),setThemePreset:n=>e({themePreset:n})})),a7=w.createContext(null),u1e=({children:t,themeMode:e,themePreset:n})=>{const r=w.useRef(null);return r.current??=c1e({themeMode:e,themePreset:n}),f.jsx(a7.Provider,{value:r.current,children:t})},Of=t=>{const e=w.useContext(a7);if(!e)throw new Error("Missing PreferencesStoreProvider");return i7(e,t)},L4=({attachment:t,align:e="left"})=>{const[n,r]=w.useState(!1),[s,i]=w.useState(!1);return n?f.jsxs("div",{className:`px-3 py-2 bg-muted rounded-lg text-sm text-muted-foreground ${e==="right"?"text-right":""}`,children:["Failed to load image: ",t.name]}):f.jsxs("div",{className:"flex flex-col gap-2",children:[f.jsx("div",{className:`text-xs text-muted-foreground font-medium ${e==="right"?"text-right":""}`,children:t.name}),f.jsx("div",{className:"flex justify-center",children:f.jsx("img",{src:t.url,alt:t.name,className:`max-w-full h-auto rounded-lg border border-border/30 shadow-sm cursor-pointer transition-all hover:shadow-md ${s?"max-h-none":"max-h-96"}`,loading:"lazy",onClick:()=>i(!s),onError:()=>r(!0),title:s?"Click to collapse":"Click to expand"})})]})},$4=()=>f.jsxs("div",{className:"flex items-center gap-2 py-2",children:[f.jsx("span",{className:"text-sm text-muted-foreground",children:"Thinking"}),f.jsxs("div",{className:"flex space-x-1",children:[f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce [animation-delay:-0.2s]"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce [animation-delay:-0.4s]"})]})]}),d1e=({message:t,isLoading:e=!1,onEdit:n,onRegenerate:r,onCopy:s,isReadonly:i=!1,showActions:a=!0,model:l,serverConfigs:u,onCallTool:d,onSendFollowup:p,toolsMetadata:h,serverId:g})=>{const[v,x]=w.useState("view"),[b,E]=w.useState(!1),[S,k]=w.useState(!1),T=Of(I=>I.themeMode),R=()=>{s?s(t.content):navigator.clipboard.writeText(t.content),k(!0),setTimeout(()=>k(!1),2e3)},j=I=>{n&&n(t.id,I),x("view")},A=()=>{x("view")},N=()=>{r&&r(t.id)},M=t.role==="assistant"&&e&&(!t.content||t.content.trim()==="");return f.jsx(pb,{children:f.jsxs(ri.div,{"data-testid":`message-${t.role}`,className:"w-full mx-auto max-w-4xl px-4 group/message",initial:{y:5,opacity:0},animate:{y:0,opacity:1},"data-role":t.role,onMouseEnter:()=>E(!0),onMouseLeave:()=>E(!1),children:[t.role==="assistant"&&f.jsxs("div",{className:"flex gap-4 w-full",children:[f.jsx("div",{className:"size-8 flex items-center rounded-full justify-center shrink-0 bg-muted/50",children:f.jsx("img",{src:i1e(l,T),alt:`${l?.id} logo`,className:"h-4 w-4 object-contain"})}),f.jsxs("div",{className:"flex flex-col gap-4 w-full min-w-0",children:[t.attachments&&t.attachments.length>0&&f.jsx("div",{className:"flex flex-col gap-3",children:t.attachments.map(I=>FD({type:I.contentType})?f.jsx(L4,{attachment:I},I.id):f.jsxs("div",{className:"px-3 py-2 bg-muted rounded-lg text-sm flex items-center gap-2",children:[f.jsx("span",{children:"📎"}),f.jsx("span",{children:I.name}),I.size&&f.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(I.size/1024).toFixed(1)," KB)"]})]},I.id))}),t.contentBlocks&&t.contentBlocks.length>0?f.jsx("div",{className:"space-y-4",children:t.contentBlocks.map((I,O)=>I.type==="text"&&I.content?f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.3,delay:O*.05},className:"prose prose-sm max-w-none dark:prose-invert prose-p:leading-relaxed prose-pre:bg-muted/50 prose-pre:border prose-pre:border-border/30 flex-1 min-w-0",children:f.jsx(C4,{children:oE(I.content)})},I.id):I.type==="tool_call"&&I.toolCall?f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.3,delay:O*.05},children:f.jsx(R4,{toolCall:I.toolCall,toolResult:I.toolResult,serverConfigs:u,onCallTool:d,onSendFollowup:p,toolMeta:h?.[I.toolCall.name],serverId:g})},I.id):null)}):f.jsxs(f.Fragment,{children:[t.toolCalls&&t.toolCalls.length>0&&f.jsx("div",{className:"space-y-2",children:t.toolCalls.map((I,O)=>{const L=t.toolResults?.find(z=>z.toolCallId===I.id);return f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.3,delay:O*.1},children:f.jsx(R4,{toolCall:I,toolResult:L,serverConfigs:u,onCallTool:d,onSendFollowup:p,toolMeta:h?.[I.name],serverId:g})},I.id)})}),M?f.jsx(ri.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.3},children:f.jsx($4,{})}):v==="view"&&t.content?f.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-p:leading-relaxed prose-pre:bg-muted/50 prose-pre:border prose-pre:border-border/30 flex-1 min-w-0",children:f.jsx(C4,{children:oE(t.content)})}):null]}),M&&t.contentBlocks&&f.jsx(ri.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.3},children:f.jsx($4,{})}),v==="view"&&f.jsxs("div",{className:`flex items-center justify-between mt-4 transition-opacity duration-200 ${b?"opacity-100":"opacity-0"}`,children:[f.jsx("div",{className:"text-xs text-muted-foreground/60",children:$D(t.timestamp)}),a&&!i&&f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",className:"px-2 h-7 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-all",onClick:R,children:S?f.jsx(Ri,{size:14}):f.jsx(zo,{size:14})})}),f.jsx(La,{children:"Copy"})]}),r&&f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",className:"px-2 h-7 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-all",onClick:N,children:f.jsx(mie,{size:14})})}),f.jsx(La,{children:"Regenerate"})]})]})]}),v==="edit"&&f.jsx("div",{className:"flex flex-row gap-2 items-start",children:f.jsx(A4,{message:t,onSave:j,onCancel:A})})]})]}),t.role==="user"&&f.jsx("div",{className:"flex justify-end w-full",children:f.jsxs("div",{className:"flex flex-col gap-2 max-w-2xl",children:[t.attachments&&t.attachments.length>0&&f.jsx("div",{className:"flex flex-col gap-3",children:t.attachments.map(I=>FD({type:I.contentType})?f.jsx(L4,{attachment:I,align:"right"},I.id):f.jsxs("div",{className:"px-3 py-2 bg-muted rounded-lg text-sm flex items-center gap-2 justify-end",children:[f.jsx("span",{children:I.name}),f.jsx("span",{children:"📎"}),I.size&&f.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(I.size/1024).toFixed(1)," KB)"]})]},I.id))}),v==="view"?f.jsxs("div",{className:"flex items-start gap-2 justify-end",children:[a&&!i&&f.jsx("div",{className:`flex items-center gap-1 mt-1 transition-opacity duration-200 ${b?"opacity-100":"opacity-0"}`,children:f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",className:"px-2 h-7 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-all",onClick:R,children:f.jsx(zo,{size:14})})}),f.jsx(La,{children:"Copy"})]})}),f.jsxs("div",{className:"relative",children:[f.jsx("div",{"data-testid":"message-content",className:"bg-primary text-primary-foreground px-4 py-3 rounded-2xl max-w-fit",children:f.jsx("div",{className:"whitespace-pre-wrap break-words font-medium",children:oE(t.content)})}),f.jsx("div",{className:`absolute -bottom-6 right-0 text-xs text-muted-foreground/60 transition-opacity duration-200 ${b?"opacity-100":"opacity-0"}`,children:$D(t.timestamp)})]})]}):f.jsx("div",{className:"w-full",children:f.jsx(A4,{message:t,onSave:j,onCancel:A})})]})})]})})},f1e=w.memo(d1e,(t,e)=>t.message.id===e.message.id&&t.message.content===e.message.content&&t.isLoading===e.isLoading&&JSON.stringify(t.message.toolCalls)===JSON.stringify(e.message.toolCalls)&&JSON.stringify(t.message.toolResults)===JSON.stringify(e.message.toolResults));function P1({provider:t}){const e=Of(r=>r.themeMode),n=r7(t,e);return n?f.jsx("img",{src:n,width:12,height:12,alt:`${t} logo`,className:"h-3 w-3 object-contain"}):f.jsx("div",{className:AT("h-3 w-3 rounded-sm",a1e(t))})}var Ca=[],Ei=[],h1e=Uint8Array,I1="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Rd=0,p1e=I1.length;Rd<p1e;++Rd)Ca[Rd]=I1[Rd],Ei[I1.charCodeAt(Rd)]=Rd;Ei[45]=62;Ei[95]=63;function m1e(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function g1e(t,e,n){return(e+n)*3/4-n}function Km(t){var e,n=m1e(t),r=n[0],s=n[1],i=new h1e(g1e(t,r,s)),a=0,l=s>0?r-4:r,u;for(u=0;u<l;u+=4)e=Ei[t.charCodeAt(u)]<<18|Ei[t.charCodeAt(u+1)]<<12|Ei[t.charCodeAt(u+2)]<<6|Ei[t.charCodeAt(u+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=Ei[t.charCodeAt(u)]<<2|Ei[t.charCodeAt(u+1)]>>4,i[a++]=e&255),s===1&&(e=Ei[t.charCodeAt(u)]<<10|Ei[t.charCodeAt(u+1)]<<4|Ei[t.charCodeAt(u+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}function v1e(t){return Ca[t>>18&63]+Ca[t>>12&63]+Ca[t>>6&63]+Ca[t&63]}function y1e(t,e,n){for(var r,s=[],i=e;i<n;i+=3)r=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(v1e(r));return s.join("")}function Xm(t){for(var e,n=t.length,r=n%3,s=[],i=16383,a=0,l=n-r;a<l;a+=i)s.push(y1e(t,a,a+i>l?l:a+i));return r===1?(e=t[n-1],s.push(Ca[e>>2]+Ca[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],s.push(Ca[e>>10]+Ca[e>>4&63]+Ca[e<<2&63]+"=")),s.join("")}function Co(t){if(t===void 0)return{};if(!o7(t))throw new Error(`The arguments to a Convex function must be an object. Received: ${t}`);return t}function x1e(t){if(typeof t>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof t!="string")throw new Error(`Invalid deployment address: found ${t}".`);if(!(t.startsWith("http:")||t.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${t}".`);try{new URL(t)}catch{throw new Error(`Invalid deployment address: "${t}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(t.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${t}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function o7(t){const e=typeof t=="object",n=Object.getPrototypeOf(t),r=n===null||n===Object.prototype||n?.constructor?.name==="Object";return e&&r}const l7=!0,Pf=BigInt("-9223372036854775808"),oj=BigInt("9223372036854775807"),TC=BigInt("0"),b1e=BigInt("8"),_1e=BigInt("256");function c7(t){return Number.isNaN(t)||!Number.isFinite(t)||Object.is(t,-0)}function w1e(t){t<TC&&(t-=Pf+Pf);let e=t.toString(16);e.length%2===1&&(e="0"+e);const n=new Uint8Array(new ArrayBuffer(8));let r=0;for(const s of e.match(/.{2}/g).reverse())n.set([parseInt(s,16)],r++),t>>=b1e;return Xm(n)}function S1e(t){const e=Km(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);let n=TC,r=TC;for(const s of e)n+=BigInt(s)*_1e**r,r++;return n>oj&&(n+=Pf+Pf),n}function E1e(t){if(t<Pf||oj<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);const e=new ArrayBuffer(8);return new DataView(e).setBigInt64(0,t,!0),Xm(new Uint8Array(e))}function k1e(t){const e=Km(t);if(e.byteLength!==8)throw new Error(`Received ${e.byteLength} bytes, expected 8 for $integer`);return new DataView(e.buffer).getBigInt64(0,!0)}const T1e=DataView.prototype.setBigInt64?E1e:w1e,C1e=DataView.prototype.getBigInt64?k1e:S1e,z4=1024;function u7(t){if(t.length>z4)throw new Error(`Field name ${t} exceeds maximum field name length ${z4}.`);if(t.startsWith("$"))throw new Error(`Field name ${t} starts with a '$', which is reserved.`);for(let e=0;e<t.length;e+=1){const n=t.charCodeAt(e);if(n<32||n>=127)throw new Error(`Field name ${t} has invalid character '${t[e]}': Field names can only contain non-control ASCII characters`)}}function If(t){if(t===null||typeof t=="boolean"||typeof t=="number"||typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>If(r));if(typeof t!="object")throw new Error(`Unexpected type of ${t}`);const e=Object.entries(t);if(e.length===1){const r=e[0][0];if(r==="$bytes"){if(typeof t.$bytes!="string")throw new Error(`Malformed $bytes field on ${t}`);return Km(t.$bytes).buffer}if(r==="$integer"){if(typeof t.$integer!="string")throw new Error(`Malformed $integer field on ${t}`);return C1e(t.$integer)}if(r==="$float"){if(typeof t.$float!="string")throw new Error(`Malformed $float field on ${t}`);const s=Km(t.$float);if(s.byteLength!==8)throw new Error(`Received ${s.byteLength} bytes, expected 8 for $float`);const a=new DataView(s.buffer).getFloat64(0,l7);if(!c7(a))throw new Error(`Float ${a} should be encoded as a number`);return a}if(r==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(r==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const n={};for(const[r,s]of Object.entries(t))u7(r),n[r]=If(s);return n}function pm(t){return JSON.stringify(t,(e,n)=>n===void 0?"undefined":typeof n=="bigint"?`${n.toString()}n`:n)}function CC(t,e,n,r){if(t===void 0){const a=n&&` (present at path ${n} in original object ${pm(e)})`;throw new Error(`undefined is not a valid Convex value${a}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(t===null)return t;if(typeof t=="bigint"){if(t<Pf||oj<t)throw new Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:T1e(t)}}if(typeof t=="number")if(c7(t)){const a=new ArrayBuffer(8);return new DataView(a).setFloat64(0,t,l7),{$float:Xm(new Uint8Array(a))}}else return t;if(typeof t=="boolean"||typeof t=="string")return t;if(t instanceof ArrayBuffer)return{$bytes:Xm(new Uint8Array(t))};if(Array.isArray(t))return t.map((a,l)=>CC(a,e,n+`[${l}]`));if(t instanceof Set)throw new Error(D1(n,"Set",[...t],e));if(t instanceof Map)throw new Error(D1(n,"Map",[...t],e));if(!o7(t)){const a=t?.constructor?.name,l=a?`${a} `:"";throw new Error(D1(n,l,t,e))}const s={},i=Object.entries(t);i.sort(([a,l],[u,d])=>a===u?0:a<u?-1:1);for(const[a,l]of i)l!==void 0&&(u7(a),s[a]=CC(l,e,n+`.${a}`));return s}function D1(t,e,n,r){return t?`${e}${pm(n)} is not a supported Convex type (present at path ${t} in original object ${pm(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${e}${pm(n)} is not a supported Convex type.`}function ec(t){return CC(t,t,"")}var A1e=Object.defineProperty,N1e=(t,e,n)=>e in t?A1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,L1=(t,e,n)=>N1e(t,typeof e!="symbol"?e+"":e,n),F4,U4;const R1e=Symbol.for("ConvexError");class AC extends(U4=Error,F4=R1e,U4){constructor(e){super(typeof e=="string"?e:pm(e)),L1(this,"name","ConvexError"),L1(this,"data"),L1(this,F4,!0),this.data=e}}const d7=()=>Array.from({length:4},()=>0);d7();d7();const B4="1.28.0";var j1e=Object.defineProperty,M1e=(t,e,n)=>e in t?j1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,q4=(t,e,n)=>M1e(t,typeof e!="symbol"?e+"":e,n);const O1e="color:rgb(0, 145, 255)";function f7(t){switch(t){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class h7{constructor(e){q4(this,"_onLogLineFuncs"),q4(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let n=Math.random().toString(36).substring(2,15);for(let r=0;r<10&&this._onLogLineFuncs[n]!==void 0;r++)n=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[n]=e,()=>{delete this._onLogLineFuncs[n]}}logVerbose(...e){if(this._verbose)for(const n of Object.values(this._onLogLineFuncs))n("debug",`${new Date().toISOString()}`,...e)}log(...e){for(const n of Object.values(this._onLogLineFuncs))n("info",...e)}warn(...e){for(const n of Object.values(this._onLogLineFuncs))n("warn",...e)}error(...e){for(const n of Object.values(this._onLogLineFuncs))n("error",...e)}}function p7(t){const e=new h7(t);return e.addLogLineListener((n,...r)=>{switch(n){case"debug":console.debug(...r);break;case"info":console.log(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break;default:console.log(...r)}}),e}function m7(t){return new h7(t)}function _b(t,e,n,r,s){const i=f7(n);if(typeof s=="object"&&(s=`ConvexError ${JSON.stringify(s.errorData,null,2)}`),e==="info"){const a=s.match(/^\[.*?\] /);if(a===null){t.error(`[CONVEX ${i}(${r})] Could not parse console.log`);return}const l=s.slice(1,a[0].length-2),u=s.slice(a[0].length);t.log(`%c[CONVEX ${i}(${r})] [${l}]`,O1e,u)}else t.error(`[CONVEX ${i}(${r})] ${s}`)}function P1e(t,e){const n=`[CONVEX FATAL ERROR] ${e}`;return t.error(n),new Error(n)}function Zd(t,e,n){return`[CONVEX ${f7(t)}(${e})] ${n.errorMessage}
1823
- Called by client`}function NC(t,e){return e.data=t.errorData,e}function wb(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function uu(t,e){return JSON.stringify({udfPath:wb(t),args:ec(e)})}var I1e=Object.defineProperty,D1e=(t,e,n)=>e in t?I1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sa=(t,e,n)=>D1e(t,typeof e!="symbol"?e+"":e,n);class L1e{constructor(){Sa(this,"nextQueryId"),Sa(this,"querySetVersion"),Sa(this,"querySet"),Sa(this,"queryIdToToken"),Sa(this,"identityVersion"),Sa(this,"auth"),Sa(this,"outstandingQueriesOlderThanRestart"),Sa(this,"outstandingAuthOlderThanRestart"),Sa(this,"paused"),Sa(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,s){const i=wb(e),a=uu(i,n),l=this.querySet.get(a);if(l!==void 0)return l.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{const u=this.nextQueryId++,d={id:u,canonicalizedUdfPath:i,args:n,numSubscribers:1,journal:r,componentPath:s};this.querySet.set(a,d),this.queryIdToToken.set(u,a);const p=this.querySetVersion,h=this.querySetVersion+1,g={type:"Add",queryId:u,udfPath:i,args:[ec(n)],journal:r,componentPath:s};return this.paused?this.pendingQuerySetModifications.set(u,g):this.querySetVersion=h,{queryToken:a,modification:{type:"ModifyQuerySet",baseVersion:p,newVersion:h,modifications:[g]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const s=this.queryIdToToken.get(n.queryId);s!==void 0&&(this.querySet.get(s).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=wb(e),s=uu(r,n),i=this.querySet.get(s);return i!==void 0?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const s=this.identityVersion;return this.paused||(this.identityVersion=s+1),{type:"Authenticate",baseVersion:s,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const n=[];for(const i of this.querySet.values()){const a={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[ec(i.args)],journal:i.journal,componentPath:i.componentPath};n.push(a),e.has(i.id)||this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const r={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:n};if(!this.auth)return this.identityVersion=0,[r,void 0];this.outstandingAuthOlderThanRestart=!0;const s={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[r,s]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,s=this.querySetVersion+1,i={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,i):this.querySetVersion=s,{type:"ModifyQuerySet",baseVersion:r,newVersion:s,modifications:[i]}}}}var $1e=Object.defineProperty,z1e=(t,e,n)=>e in t?$1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,wy=(t,e,n)=>z1e(t,typeof e!="symbol"?e+"":e,n);class F1e{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,wy(this,"inflightRequests"),wy(this,"requestsOlderThanRestart"),wy(this,"inflightMutationsCount",0),wy(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(s=>{const i=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:i,requestedAt:new Date,onResult:s}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",s=n.message.udfPath;for(const u of e.logLines)_b(this.logger,"info",r,s,u);const i=n.status;let a,l;if(e.success)a={success:!0,logLines:e.logLines,value:If(e.result)},l=()=>i.onResult(a);else{const u=e.result,{errorData:d}=e;_b(this.logger,"error",r,s,u),a={success:!1,errorMessage:u,errorData:d!==void 0?If(d):void 0,logLines:e.logLines},l=()=>i.onResult(a)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(n.status={status:"Completed",result:a,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,s]of this.inflightRequests.entries()){const i=s.status;i.status==="Completed"&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),n.set(r,i.result),s.message.type==="Mutation"?this.inflightMutationsCount--:s.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Qm=Symbol.for("functionName"),U1e=Symbol.for("toReferencePath");function B1e(t){return t[U1e]??null}function q1e(t){return t.startsWith("function://")}function V1e(t){let e;if(typeof t=="string")q1e(t)?e={functionHandle:t}:e={name:t};else if(t[Qm])e={name:t[Qm]};else{const n=B1e(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function Ls(t){const e=V1e(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Qm];if(!n)throw new Error(`${t} is not a functionReference`);return n}function lj(t){return{[Qm]:t}}function g7(t=[]){const e={get(n,r){if(typeof r=="string"){const s=[...t,r];return g7(s)}else if(r===Qm){if(t.length<2){const a=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}const s=t.slice(0,-1).join("/"),i=t[t.length-1];return i==="default"?s:s+":"+i}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}g7();var H1e=Object.defineProperty,G1e=(t,e,n)=>e in t?H1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sb=(t,e,n)=>G1e(t,typeof e!="symbol"?e+"":e,n);class Jm{constructor(e){Sb(this,"queryResults"),Sb(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=Co(n[0]),s=Ls(e),i=this.queryResults.get(uu(s,r));if(i!==void 0)return Jm.queryValue(i.result)}getAllQueries(e){const n=[],r=Ls(e);for(const s of this.queryResults.values())s.udfPath===wb(r)&&n.push({args:s.args,value:Jm.queryValue(s.result)});return n}setQuery(e,n,r){const s=Co(n),i=Ls(e),a=uu(i,s);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const u={udfPath:i,args:s,result:l};this.queryResults.set(a,u),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class W1e{constructor(){Sb(this,"queryResults"),Sb(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(a=>!n.has(a.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const s=new Jm(this.queryResults);for(const a of this.optimisticUpdates)a.update(s);const i=[];for(const[a,l]of this.queryResults){const u=r.get(a);(u===void 0||u.result!==l.result)&&i.push(a)}return i}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Jm(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){return this.queryResults.get(e)}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?NC(r,new AC(Zd("query",n.udfPath,r))):new Error(Zd("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var Y1e=Object.defineProperty,K1e=(t,e,n)=>e in t?Y1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$1=(t,e,n)=>K1e(t,typeof e!="symbol"?e+"":e,n);class Zs{constructor(e,n){$1(this,"low"),$1(this,"high"),$1(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new Zs(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?V4:e>=X1e?Q1e:new Zs(e%mm|0,e/mm|0)}toString(){return(BigInt(this.high)*BigInt(mm)+BigInt(this.low)).toString()}equals(e){return Zs.isLong(e)||(e=Zs.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return Zs.isLong(e)||(e=Zs.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?Zs.fromNumber(e):new Zs(e.low,e.high)}}const V4=new Zs(0,0),H4=65536,mm=H4*H4,X1e=mm*mm,Q1e=new Zs(-1,-1);var J1e=Object.defineProperty,Z1e=(t,e,n)=>e in t?J1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sy=(t,e,n)=>Z1e(t,typeof e!="symbol"?e+"":e,n);class G4{constructor(e,n){Sy(this,"version"),Sy(this,"remoteQuerySet"),Sy(this,"queryPath"),Sy(this,"logger"),this.version={querySet:0,ts:Zs.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const s=this.queryPath(r.queryId);if(s)for(const a of r.logLines)_b(this.logger,"info","query",s,a);const i=If(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:i,logLines:r.logLines});break}case"QueryFailed":{const s=this.queryPath(r.queryId);if(s)for(const a of r.logLines)_b(this.logger,"info","query",s,a);const{errorData:i}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:i!==void 0?If(i):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function z1(t){const e=Km(t);return Zs.fromBytesLE(Array.from(e))}function eke(t){const e=new Uint8Array(t.toBytesLE());return Xm(e)}function W4(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:z1(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:z1(t.startVersion.ts)},endVersion:{...t.endVersion,ts:z1(t.endVersion.ts)}}}}function tke(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:eke(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var nke=Object.defineProperty,rke=(t,e,n)=>e in t?nke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vr=(t,e,n)=>rke(t,typeof e!="symbol"?e+"":e,n);const ske=1e3,ike=1001,ake=1005,oke=4040;let ax;function ox(){return ax===void 0&&(ax=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(ax+performance.now())}function Y4(){return`t=${Math.round((ox()-ax)/100)/10}s`}const v7={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function lke(t){if(t===void 0)return"Unknown";for(const e of Object.keys(v7))if(t.startsWith(e))return e;return"Unknown"}class cke{constructor(e,n,r,s,i,a){this.markConnectionStateDirty=i,this.debug=a,Vr(this,"socket"),Vr(this,"connectionCount"),Vr(this,"_hasEverConnected",!1),Vr(this,"lastCloseReason"),Vr(this,"transitionChunkBuffer",null),Vr(this,"defaultInitialBackoff"),Vr(this,"maxBackoff"),Vr(this,"retries"),Vr(this,"serverInactivityThreshold"),Vr(this,"reconnectDueToServerInactivityTimeout"),Vr(this,"uri"),Vr(this,"onOpen"),Vr(this,"onResume"),Vr(this,"onMessage"),Vr(this,"webSocketConstructor"),Vr(this,"logger"),Vr(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=s,this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=W4(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ox()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Y4(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Y4())),this.connectionCount+=1,this.lastCloseReason=null},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let s=W4(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${s.type}`),s.type==="Ping")return;if(s.type==="TransitionChunk"){const a=this.assembleTransition(s);if(!a)return;s=a,this._logVerbose(`assembled full ws message of type ${s.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${s.type} while buffering TransitionChunks`)),s.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:s}),this.onMessage(s).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==ske&&n.code!==ike&&n.code!==ake&&n.code!==oke){let s=`WebSocket closed with code ${n.code}`;n.reason&&(s+=`: ${n.reason}`),this.logger.log(s),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(s)}const r=lke(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=tke(e),s=JSON.stringify(r);let i=!1;try{this.socket.ws.send(s),i=!0}catch(a){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${a}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`),setTimeout(()=>this.connect(),n)}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ox()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:v7[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const s=Math.min(r,this.maxBackoff),i=s*(Math.random()-.5);return s+i}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=ox()-e.clientClockSkew-e.serverTs/1e6,s=`${Math.round(r)}ms`,i=`${Math.round(n/1e4)/100}MB`,a=n/(r/1e3),l=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${s} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${s})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function uke(){return dke()}function dke(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class Xp extends Error{}Xp.prototype.name="InvalidTokenError";function fke(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function hke(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return fke(e)}catch{return atob(e)}}function y7(t,e){if(typeof t!="string")throw new Xp("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new Xp(`Invalid token specified: missing part #${n+1}`);let s;try{s=hke(r)}catch(i){throw new Xp(`Invalid token specified: invalid base64 for part #${n+1} (${i.message})`)}try{return JSON.parse(s)}catch(i){throw new Xp(`Invalid token specified: invalid json for part #${n+1} (${i.message})`)}}var pke=Object.defineProperty,mke=(t,e,n)=>e in t?pke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_i=(t,e,n)=>mke(t,typeof e!="symbol"?e+"":e,n);const gke=20*24*60*60*1e3,K4=2;class vke{constructor(e,n,r){_i(this,"authState",{state:"noAuth"}),_i(this,"configVersion",0),_i(this,"syncState"),_i(this,"authenticate"),_i(this,"stopSocket"),_i(this,"tryRestartSocket"),_i(this,"pauseSocket"),_i(this,"resumeSocket"),_i(this,"clearAuth"),_i(this,"logger"),_i(this,"refreshTokenLeewaySeconds"),_i(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=K4){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${K4-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:s}=n;if(!r||!s){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const i=s-r;if(i<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let a=Math.min(gke,(i-this.refreshTokenLeewaySeconds)*1e3);a<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${i}s`),a=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},a);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${a}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const s=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:s}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return y7(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const yke=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function xke(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function bke(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function _ke(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of yke){const r=performance.getEntriesByName(n).filter(s=>s.entryType==="mark").filter(s=>s.detail.sessionId===t);e.push(...r)}return e.map(bke)}var wke=Object.defineProperty,Ske=(t,e,n)=>e in t?wke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pr=(t,e,n)=>Ske(t,typeof e!="symbol"?e+"":e,n);class Eke{constructor(e,n,r){if(pr(this,"address"),pr(this,"state"),pr(this,"requestManager"),pr(this,"webSocketManager"),pr(this,"authenticationManager"),pr(this,"remoteQuerySet"),pr(this,"optimisticQueryResults"),pr(this,"_transitionHandlerCounter",0),pr(this,"_nextRequestId"),pr(this,"_onTransitionFns",new Map),pr(this,"_sessionId"),pr(this,"firstMessageReceived",!1),pr(this,"debug"),pr(this,"logger"),pr(this,"maxObservedTimestamp"),pr(this,"connectionStateSubscribers",new Map),pr(this,"nextConnectionStateSubscriberId",0),pr(this,"_lastPublishedConnectionState"),pr(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const v=this.connectionState();if(JSON.stringify(v)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=v;for(const x of this.connectionStateSubscribers.values())x(v)}})}),pr(this,"mark",v=>{this.debug&&xke(v,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&x1e(e),r={...r};const s=r.authRefreshTokenLeewaySeconds??2;let i=r.webSocketConstructor;if(!i&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");i=i||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?m7({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:p7({verbose:r.verbose??!1});const a=e.search("://");if(a===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(a+3),u=e.substring(0,a);let d;if(u==="http")d="ws";else if(u==="https")d="wss";else throw new Error(`Unknown parent protocol ${u}`);const p=`${d}://${l}/api/${B4}/sync`;this.state=new L1e,this.remoteQuerySet=new G4(v=>this.state.queryPath(v),this.logger),this.requestManager=new F1e(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new vke(this.state,{authenticate:v=>{const x=this.state.setAuth(v);return this.webSocketManager.sendMessage(x),x.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:s}),this.optimisticQueryResults=new W1e,this.addOnTransitionHandler(v=>{n(v.queries.map(x=>x.token))}),this._nextRequestId=0,this._sessionId=uke();const{unsavedChangesWarning:g}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(g===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else g!==!1&&window.addEventListener("beforeunload",v=>{if(this.requestManager.hasIncompleteRequests()){v.preventDefault();const x="Are you sure you want to leave? Your changes may not be saved.";return(v||window.event).returnValue=x,x}});this.webSocketManager=new cke(p,{onOpen:v=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...v,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const x=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new G4(S=>this.state.queryPath(S),this.logger);const[b,E]=this.state.restart(x);E&&this.webSocketManager.sendMessage(E),this.webSocketManager.sendMessage(b);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[v,x]=this.state.resume();x&&this.webSocketManager.sendMessage(x),v&&this.webSocketManager.sendMessage(v);for(const b of this.requestManager.resume())this.webSocketManager.sendMessage(b)},onMessage:v=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),v.type){case"Transition":{this.observedTimestamp(v.endVersion.ts),this.authenticationManager.onTransition(v),this.remoteQuerySet.transition(v),this.state.transition(v);const x=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(x);break}case"MutationResponse":{v.success&&this.observedTimestamp(v.ts);const x=this.requestManager.onResponse(v);x!==null&&this.notifyOnQueryResultChanges(new Map([[x.requestId,x.result]]));break}case"ActionResponse":{this.requestManager.onResponse(v);break}case"AuthError":{this.authenticationManager.onAuthError(v);break}case"FatalError":{const x=P1e(this.logger,v.error);throw this.webSocketManager.terminate(),x}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[i,a]of n){const l=this.state.queryToken(i);if(l!==null){const u={result:a,udfPath:this.state.queryPath(i),args:this.state.queryArgs(i)};r.set(l,u)}}const s=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:s.map(i=>{const a=this.optimisticQueryResults.rawQueryResult(i);return{token:i,modification:{kind:"Updated",result:a.result}}}),reflectedMutations:Array.from(e).map(([i,a])=>({requestId:i,result:a})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?y7(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const s=Co(n),{modification:i,queryToken:a,unsubscribe:l}=this.state.subscribe(e,s,r?.journal,r?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{const u=l();u&&this.webSocketManager.sendMessage(u)}}}localQueryResult(e,n){const r=Co(n),s=uu(e,r);return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=Co(n),s=uu(e,r);return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,n){const r=Co(n),s=uu(e,r);return this.state.queryJournal(s)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const s=await this.mutationInternal(e,n,r);if(!s.success)throw s.errorData!==void 0?NC(s,new AC(Zd("mutation",e,s))):new Error(Zd("mutation",e,s));return s.value}async mutationInternal(e,n,r,s){const{mutationPromise:i}=this.enqueueMutation(e,n,r,s);return i}enqueueMutation(e,n,r,s){const i=Co(n);this.tryReportLongDisconnect();const a=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const p=r.optimisticUpdate;if(p!==void 0){const h=x=>{p(x,i)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},v=this.optimisticQueryResults.applyOptimisticUpdate(h,a).map(x=>{const b=this.localQueryResultByToken(x);return{token:x,modification:{kind:"Updated",result:b===void 0?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:v,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:a,udfPath:e,componentPath:s,args:[ec(i)]},u=this.webSocketManager.sendMessage(l),d=this.requestManager.request(l,u);return{requestId:a,mutationPromise:d}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?NC(r,new AC(Zd("action",e,r))):new Error(Zd("action",e,r));return r.value}async actionInternal(e,n,r){const s=Co(n),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const a={type:"Action",requestId:i,udfPath:e,componentPath:r,args:[ec(s)]},l=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=_ke(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${B4}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function kke({getCurrentValue:t,subscribe:e}){const[n,r]=w.useState(()=>({getCurrentValue:t,subscribe:e,value:t()}));let s=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(s=t(),r({getCurrentValue:t,subscribe:e,value:s})),w.useEffect(()=>{let i=!1;const a=()=>{i||r(u=>{if(u.getCurrentValue!==t||u.subscribe!==e)return u;const d=t();return u.value===d?u:{...u,value:d}})},l=e(a);return a(),()=>{i=!0,l()}},[t,e]),s}var Tke=Object.defineProperty,Cke=(t,e,n)=>e in t?Tke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kl=(t,e,n)=>Cke(t,typeof e!="symbol"?e+"":e,n);const Ake=5e3;if(typeof Ee>"u")throw new Error("Required dependency 'react' not found");function x7(t,e,n){function r(s){return Pke(s),e.mutation(t,s,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(i){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${Ls(t)}`);return x7(t,e,i)},r}function Nke(t,e){return function(n){return e.action(t,n)}}class Rke{constructor(e,n){if(kl(this,"address"),kl(this,"cachedSync"),kl(this,"listeners"),kl(this,"options"),kl(this,"closed",!1),kl(this,"_logger"),kl(this,"adminAuth"),kl(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?m7({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:p7({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new Eke(this.address,e=>this.transition(e),this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedSync)}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,s]=n,i=Ls(e);return{onUpdate:a=>{const{queryToken:l,unsubscribe:u}=this.sync.subscribe(i,r,s),d=this.listeners.get(l);return d!==void 0?d.add(a):this.listeners.set(l,new Set([a])),()=>{if(this.closed)return;const p=this.listeners.get(l);p.delete(a),p.size===0&&this.listeners.delete(l),u()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(i,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(i,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(i,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??Ake,s=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(s,n)}mutation(e,...n){const[r,s]=n,i=Ls(e);return this.sync.mutation(i,r,s)}action(e,...n){const r=Ls(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),s=r.localQueryResult();return s!==void 0?Promise.resolve(s):new Promise((i,a)=>{const l=r.onUpdate(()=>{l();try{i(r.localQueryResult())}catch(u){a(u)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const s of r)s()}}}const Y0=Ee.createContext(void 0);function jke(){return w.useContext(Y0)}const Mke=({client:t,children:e})=>Ee.createElement(Y0.Provider,{value:t},e);function Eb(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:Co(e[0]),s=typeof t=="string"?lj(t):t,i=Ls(s),a=w.useMemo(()=>n?{}:{query:{query:s,args:r}},[JSON.stringify(ec(r)),i,n]),u=$ke(a).query;if(u instanceof Error)throw u;return u}function b7(t){const e=typeof t=="string"?lj(t):t,n=w.useContext(Y0);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return w.useMemo(()=>x7(e,n),[n,Ls(e)])}function Oke(t){const e=w.useContext(Y0),n=lj(t);if(e===void 0)throw new Error("Could not find Convex client! `useAction` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return w.useMemo(()=>Nke(n,e),[e,Ls(n)])}function Pke(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var Ike=Object.defineProperty,Dke=(t,e,n)=>e in t?Ike(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F1=(t,e,n)=>Dke(t,typeof e!="symbol"?e+"":e,n);class Lke{constructor(e){F1(this,"createWatch"),F1(this,"queries"),F1(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:s}=e[n];if(Ls(r),this.queries[n]===void 0)this.addQuery(n,r,s);else{const i=this.queries[n];(Ls(r)!==Ls(i.query)||JSON.stringify(ec(s))!==JSON.stringify(ec(i.args)))&&(this.removeQuery(n),this.addQuery(n,r,s))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:s,args:i}=e[r];Ls(s);const a=this.createWatch(s,i);let l;try{l=a.localQueryResult()}catch(u){if(u instanceof Error)l=u;else throw u}n[r]=l}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:s,watch:i}=this.queries[n],a=i.journal();this.removeQuery(n),this.addQuery(n,r,s,a)}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,s){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const i=this.createWatch(n,r,s),a=i.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:i,unsubscribe:a}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function $ke(t){const e=jke();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=w.useMemo(()=>(r,s,i)=>e.watchQuery(r,s,i?{journal:i}:{}),[e]);return zke(t,n)}function zke(t,e){const[n]=w.useState(()=>new Lke(e));n.createWatch!==e&&n.setCreateWatch(e),w.useEffect(()=>()=>n.destroy(),[n]);const r=w.useMemo(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:s=>(n.setQueries(t),n.subscribe(s))}),[n,t]);return kke(r)}const _7=w.createContext(void 0);function pa(){const t=w.useContext(_7);if(t===void 0)throw new Error("Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project.");return t}function Fke({children:t,client:e,useAuth:n}){const{isLoading:r,isAuthenticated:s,fetchAccessToken:i}=n(),[a,l]=w.useState(null);return r&&a!==null&&l(null),!r&&!s&&a!==!1&&l(!1),Ee.createElement(_7.Provider,{value:{isLoading:a===null,isAuthenticated:s&&(a??!1)}},Ee.createElement(Uke,{authProviderAuthenticated:s,fetchAccessToken:i,authProviderLoading:r,client:e,setIsConvexAuthenticated:l}),Ee.createElement(Mke,{client:e},t),Ee.createElement(Bke,{authProviderAuthenticated:s,fetchAccessToken:i,authProviderLoading:r,client:e,setIsConvexAuthenticated:l}))}function Uke({authProviderAuthenticated:t,fetchAccessToken:e,authProviderLoading:n,client:r,setIsConvexAuthenticated:s}){return w.useEffect(()=>{let i=!0;if(t)return r.setAuth(e,a=>{i&&s(()=>a)}),()=>{i=!1,s(a=>a?!1:null)}},[t,e,n,r,s]),null}function Bke({authProviderAuthenticated:t,fetchAccessToken:e,authProviderLoading:n,client:r,setIsConvexAuthenticated:s}){return w.useEffect(()=>{if(t)return()=>{r.clearAuth(),s(()=>null)}},[t,e,n,r,s]),null}const qke=t=>{const e=new Map;return t.forEach(n=>{const r=e.get(n.provider)||[];e.set(n.provider,[...r,n])}),e},X4=t=>{switch(t){case"anthropic":return"Anthropic";case"openai":return"OpenAI";case"deepseek":return"DeepSeek";case"google":return"Google AI";case"ollama":return"Ollama";case"meta":return"Meta";case"x-ai":return"xAI";default:return t}};function w7({currentModel:t,availableModels:e,onModelChange:n,disabled:r,isLoading:s,hideProvidedModels:i=!1}){const[a,l]=w.useState(!1),u=t,{isAuthenticated:d}=pa(),p=qke(e),h=Array.from(p.keys()).sort(),g=i?[]:h.filter(x=>(p.get(x)||[]).some(E=>ra(E.id))),v=h.filter(x=>(p.get(x)||[]).some(E=>!ra(E.id)));return f.jsxs(m0,{open:a,onOpenChange:l,children:[f.jsx(g0,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",disabled:r||s,className:"h-8 px-2 rounded-full hover:bg-muted/80 transition-colors text-xs cursor-pointer",children:f.jsxs(f.Fragment,{children:[f.jsx(P1,{provider:u.provider}),f.jsx("span",{className:"text-[10px] font-medium",children:u.name})]})})}),f.jsxs(v0,{align:"start",className:"min-w-[200px]",children:[g.length>0&&f.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Provided Models"}),g.map(x=>{const E=(p.get(x)||[]).filter(k=>ra(k.id)),S=E.length;return f.jsxs(vI,{children:[f.jsxs(yI,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[f.jsx(P1,{provider:x}),f.jsxs("div",{className:"flex flex-col flex-1",children:[f.jsx("span",{className:"font-medium",children:X4(x)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:[S," model",S!==1?"s":""]})]})]}),f.jsx(xI,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:E.map(k=>{const T=ra(k.id),R=!!k.disabled||T&&!d,j=T&&!d?"Sign in to use MCPJam provided models":k.disabledReason,A=f.jsxs(Ro,{onSelect:()=>{n(k),l(!1)},className:"flex items-center gap-3 text-sm cursor-pointer",disabled:R,children:[f.jsx("div",{className:"flex flex-col flex-1",children:f.jsx("span",{className:"font-medium",children:k.name})}),k.id===t.id&&f.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},k.id);return R?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx("div",{className:"pointer-events-auto",children:A})}),f.jsx(La,{side:"right",children:j})]},k.id):A})})]},x)}),g.length>0&&v.length>0&&f.jsx("div",{className:"my-1 h-px bg-muted/50"}),v.length>0&&f.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your providers"}),v.map(x=>{const E=(p.get(x)||[]).filter(k=>!ra(k.id)),S=E.length;return f.jsxs(vI,{children:[f.jsxs(yI,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[f.jsx(P1,{provider:x}),f.jsxs("div",{className:"flex flex-col flex-1",children:[f.jsx("span",{className:"font-medium",children:X4(x)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:[S," model",S!==1?"s":""]})]})]}),f.jsx(xI,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:E.map(k=>{const T=!!k.disabled,R=f.jsxs(Ro,{onSelect:()=>{n(k),l(!1)},className:"flex items-center gap-3 text-sm cursor-pointer",disabled:T,children:[f.jsx("div",{className:"flex flex-col flex-1",children:f.jsx("span",{className:"font-medium",children:k.name})}),k.id===t.id&&f.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},k.id);return T?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx("div",{className:"pointer-events-auto",children:R})}),f.jsx(La,{side:"right",children:k.disabledReason})]},k.id):R})})]},x)})]})]})}function Vke({className:t,defaultValue:e,value:n,min:r=0,max:s=100,...i}){const a=w.useMemo(()=>Array.isArray(n)?n:Array.isArray(e)?e:[r,s],[n,e,r,s]);return f.jsxs(hre,{"data-slot":"slider",defaultValue:e,value:n,min:r,max:s,className:Oe("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",t),...i,children:[f.jsx(pre,{"data-slot":"slider-track",className:Oe("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:f.jsx(mre,{"data-slot":"slider-range",className:Oe("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:a.length},(l,u)=>f.jsx(gre,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},u))]})}function Hke({systemPrompt:t,onSystemPromptChange:e,temperature:n,onTemperatureChange:r,disabled:s,isLoading:i}){const[a,l]=w.useState(!1),[u,d]=w.useState(t),[p,h]=w.useState(n),g=b=>{l(b),b&&(d(t),h(n))},v=()=>{e(u),r(p),l(!1),It.success("System prompt and temperature updated")},x=()=>{d(t),h(n),l(!1)};return f.jsxs(ua,{open:a,onOpenChange:g,children:[f.jsx(gN,{asChild:!0,children:f.jsxs(Pe,{variant:"ghost",size:"sm",disabled:s||i,className:"h-8 px-2 rounded-full hover:bg-muted/80 transition-colors text-xs cursor-pointer",children:[f.jsx(bie,{className:"h-2 w-2 mr-1"}),f.jsx("span",{className:"text-[10px] font-medium",children:"System Prompt & Temperature"})]})}),f.jsxs(da,{className:"sm:max-w-md",children:[f.jsx(fa,{children:f.jsx(ha,{children:"System Prompt & Temperature"})}),f.jsxs("div",{className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"text-sm font-medium",children:"System Prompt"}),f.jsx(Qo,{value:u,onChange:b=>d(b.target.value),placeholder:"You are a helpful assistant with access to MCP tools.",className:"h-[140px] resize-none"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("label",{className:"text-sm font-medium",children:"Temperature"}),f.jsx("span",{className:"text-sm text-muted-foreground",children:p.toFixed(1)})]}),f.jsx(Vke,{value:[p],onValueChange:b=>h(b[0]),min:0,max:2,step:.1,className:"w-full"}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Lower values (0-0.3) for focused tasks, higher values (0.7-2.0) for creative tasks"})]}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx(Pe,{variant:"ghost",onClick:x,className:"cursor-pointer",children:"Cancel"}),f.jsx(Pe,{onClick:v,className:"cursor-pointer",children:"Save"})]})]})]})]})}function Q4({value:t,onChange:e,onSubmit:n,onStop:r,disabled:s=!1,isLoading:i=!1,placeholder:a="Type your message...",className:l,showScrollToBottom:u=!1,onScrollToBottom:d,currentModel:p,availableModels:h,onModelChange:g,systemPrompt:v,onSystemPromptChange:x,temperature:b,onTemperatureChange:E,isSendBlocked:S=!1}){const k=w.useRef(null),T=w.useRef(null),[R,j]=w.useState([]),[A,N]=w.useState([]),M=p;w.useEffect(()=>{I()},[t]);const I=()=>{k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,120)}px`)},O=()=>{k.current&&(k.current.style.height="auto")},L=w.useCallback(()=>{!t.trim()||s||i||A.length>0||S||(n(t.trim(),R.length>0?R:void 0),e(""),j([]),O(),setTimeout(()=>{k.current?.focus()},0))},[t,s,i,A.length,n,R,e,S]),z=X=>{X.key==="Enter"&&!X.shiftKey&&!X.nativeEvent.isComposing&&(X.preventDefault(),L())},H=w.useCallback(async X=>{const F=Array.from(X.target.files||[]);if(F.length!==0){N(F.map(W=>W.name));try{const W=await Promise.all(F.map(async G=>(await new Promise(ee=>setTimeout(ee,1e3)),{id:Math.random().toString(36).substr(2,9),name:G.name,url:URL.createObjectURL(G),contentType:G.type,size:G.size})));j(G=>[...G,...W])}catch(W){console.error("Error uploading files:",W)}finally{N([]),T.current&&(T.current.value="")}}},[]),V=X=>{j(F=>F.filter(W=>W.id!==X))};return f.jsxs("div",{className:"relative w-full",children:[f.jsx(pb,{children:u&&f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"absolute left-1/2 bottom-full mb-4 -translate-x-1/2 z-50",children:f.jsx(Pe,{size:"sm",variant:"outline",className:"rounded-full shadow-lg cursor-pointer",onClick:d,children:f.jsx(Jre,{className:"h-4 w-4"})})})}),f.jsx("input",{ref:T,type:"file",multiple:!0,className:"hidden",onChange:H,accept:"image/*,.pdf,.txt,.json,.csv"}),(R.length>0||A.length>0)&&f.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[R.map(X=>f.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[f.jsx("span",{className:"truncate max-w-[200px]",children:X.name}),f.jsx("button",{onClick:()=>V(X.id),className:"text-muted-foreground hover:text-foreground cursor-pointer",children:"×"})]},X.id)),A.map(X=>f.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 px-3 py-2 rounded-lg text-sm animate-pulse",children:[f.jsx("span",{className:"truncate max-w-[200px]",children:X}),f.jsx("div",{className:"w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"})]},X))]}),f.jsxs("div",{className:"relative",children:[f.jsx(Qo,{ref:k,value:t,onChange:X=>{S||e(X.target.value)},onKeyDown:z,placeholder:a,disabled:s,readOnly:s||S,className:AT("min-h-[56px] max-h-[120px] resize-none pl-16 pr-14 py-4 rounded-3xl","border-border/30 bg-background/50 focus-visible:border-border/50","focus-visible:ring-0 focus-visible:ring-offset-0","transition-all duration-200 ease-in-out overflow-y-auto","text-base placeholder:text-muted-foreground/60",S?"cursor-not-allowed bg-muted/30 text-muted-foreground":"",l),rows:1,autoFocus:!S}),f.jsx("div",{className:"absolute bottom-3 left-4 flex items-center gap-1",children:f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-8 p-0 rounded-full hover:bg-muted/80 transition-colors cursor-pointer",onClick:()=>T.current?.click(),disabled:s||i||S,children:f.jsx(lie,{size:16})})}),f.jsx(La,{children:"Add files"})]})}),f.jsx("div",{className:"absolute bottom-3 right-4 flex items-center gap-1",children:i?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",size:"sm",variant:"outline",className:"h-8 w-8 p-0 rounded-full border-border/30 hover:border-border/50 transition-colors cursor-pointer",onClick:r,children:f.jsx(Rie,{size:16})})}),f.jsx(La,{children:"Stop generating"})]}):f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",size:"sm",className:AT("h-8 w-8 p-0 rounded-full transition-all duration-200 cursor-pointer",t.trim()&&!s&&A.length===0&&!S?"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),onClick:L,disabled:!t.trim()||s||A.length>0||S,children:f.jsx(bB,{size:16})})}),f.jsx(La,{children:"Send message"})]})})]}),f.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[h.length>0&&M&&f.jsx(w7,{currentModel:M,availableModels:h,onModelChange:g,disabled:!1,isLoading:i}),x&&E&&f.jsx(Hke,{systemPrompt:v||"You are a helpful assistant with access to MCP tools.",onSystemPromptChange:x,temperature:b||0,onTemperatureChange:E,disabled:s,isLoading:i})]})]})}function Gke({serverConfigs:t,connectedServerConfigs:e,systemPrompt:n=""}){const r=w.useRef(null),[s,i]=w.useState(!0),{isAuthenticated:a}=pa(),{signUp:l}=Fi(),u=Qr(),[d,p]=w.useState(n||"You are a helpful assistant with access to MCP tools."),[h,g]=w.useState(1),[v,x]=w.useState({}),E=Object.keys(t||{}).filter(Z=>e?.[Z]?.connectionStatus==="connected"),S=E.length===0,{messages:k,isLoading:T,error:R,input:j,setInput:A,sendMessage:N,stopGeneration:M,regenerateMessage:I,clearChat:O,model:L,availableModels:z,setModel:H,elicitationRequest:V,elicitationLoading:X,handleElicitationResponse:F}=xV({systemPrompt:d,temperature:h,selectedServers:E,onError:Z=>{It.error(Z)}}),G=(L?ra(L.id):!1)&&!a,ee="Sign in to use MCPJam provided models";w.useEffect(()=>{G&&A("")},[G,A]),w.useEffect(()=>{u.capture("chat_tab_viewed",{location:"chat_tab",platform:on(),environment:void 0})},[]),w.useEffect(()=>{const Z=localStorage.getItem("chat-selected-model");if(Z&&z.length>0){const U=z.find(J=>J.id===Z);U&&(!L||L.id!==Z)&&H(U)}},[z]),w.useEffect(()=>{L&&localStorage.setItem("chat-selected-model",L.id)},[L]),w.useEffect(()=>{L&&g(Ide(L))},[L]),w.useEffect(()=>{const Z=async()=>{const U={};for(const J of E)try{const oe=await ON(J);oe.toolsMetadata&&Object.assign(U,oe.toolsMetadata)}catch(oe){console.error(`Failed to fetch tools for server ${J}:`,oe)}x(U)};E&&E.length>0?Z():x({})},[JSON.stringify(E)]);const P=k.length>0,ie=G||S,ue=G?"Sign in to use free chat":"Connect an MCP server to send your first message",D=[{label:"Available tools",value:"What tools are available?",icon:EB}];w.useEffect(()=>{s&&r.current&&(r.current.scrollTop=r.current.scrollHeight)},[k,s]);const ne=()=>{if(!r.current)return;const{scrollTop:Z,scrollHeight:U,clientHeight:J}=r.current,pe=U-Z-J<100;i(pe)},fe=Z=>{navigator.clipboard.writeText(Z)},q=async(Z,U)=>{try{return(await(await fetch("/api/mcp/tools/execute",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({toolName:Z,parameters:U,...E.length===1?{serverId:E[0]}:{}})})).json()).result}catch(J){throw J}},K=Z=>{A(Z),N(Z)},Y=(Z,U)=>f.jsxs("div",{className:"flex flex-col h-screen",children:[f.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-4",children:[f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.35},className:"w-full max-w-xl space-y-6 text-center",children:Z}),f.jsxs(ri.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.35,delay:.05},className:"w-full max-w-2xl pt-10",children:[f.jsx(Q4,{value:j,onChange:A,onSubmit:()=>{u.capture("send_message",{location:"chat_tab",platform:on(),environment:void 0,model_id:L?.id??null,model_name:L?.name??null,model_provider:L?.provider??null}),N(j)},onStop:M,disabled:z.length===0||U.disabled,isLoading:T,placeholder:U.placeholder,className:"border shadow-sm",currentModel:L||null,availableModels:z,onModelChange:H,onClearChat:O,hasMessages:!1,systemPrompt:d,onSystemPromptChange:p,temperature:h,onTemperatureChange:g,isSendBlocked:G}),z.length===0&&f.jsx(ri.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.25},className:"mt-3 text-center text-xs text-muted-foreground",children:"Configure API keys in Settings or start Ollama to enable chat"})]})]}),f.jsx(TT,{elicitationRequest:V,onResponse:F,loading:X})]});if(!P&&ie)return Y(G?f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx("h2",{className:"text-base font-medium",children:"Create an account to use free models"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"or bring your own API key in the settings tab"})]}),f.jsx("div",{className:"flex justify-center gap-2",children:f.jsx(Pe,{onClick:()=>{u.capture("sign_up_button_clicked",{location:"chat_tab",platform:on(),environment:void 0}),l()},style:{backgroundColor:"#E55A3A"},className:"hover:opacity-90 cursor-pointer",children:"Create account"})})]}):f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"space-y-1",children:f.jsx("h2",{className:"text-base font-medium",children:"You must connect to an MCP server"})}),f.jsxs("div",{className:"flex justify-center gap-2 text-xs text-muted-foreground",children:[f.jsxs("a",{href:"#servers",className:"inline-flex items-center gap-1 rounded-full border px-3 py-1 transition hover:bg-muted/30",children:[f.jsx(vse,{className:"h-3 w-3"})," Add server"]}),f.jsxs("a",{href:"#settings",className:"inline-flex items-center gap-1 rounded-full border px-3 py-1 transition hover:bg-muted/30",children:[f.jsx(rN,{className:"h-3 w-3"})," Settings"]})]})]}),{placeholder:ue,disabled:!0});if(!P){const Z=f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx("h2",{className:"text-base font-medium",children:"Test your servers"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Start typing or choose a quick suggestion to begin."})]}),f.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:D.map(({label:U,value:J,icon:oe})=>f.jsxs("button",{type:"button",onClick:()=>A(J),className:"inline-flex items-center gap-2 rounded-full border border-border/60 px-3 py-1.5 text-xs transition hover:border-border hover:bg-muted/40 cursor-pointer",children:[f.jsx(oe,{className:"h-3.5 w-3.5 text-muted-foreground"}),U]},U))})]});return Y(Z,{placeholder:"Send a message...",disabled:!1})}return f.jsx(p0,{children:f.jsxs(Fa,{direction:"horizontal",className:"h-screen",children:[f.jsx(cr,{defaultSize:70,minSize:40,children:f.jsxs("div",{className:"flex flex-col bg-background h-full overflow-hidden",children:[f.jsx("div",{ref:r,onScroll:ne,className:"flex-1 overflow-y-auto pb-4",children:f.jsx("div",{className:"max-w-4xl mx-auto px-4 pt-8 pb-8",children:f.jsxs(pb,{mode:"popLayout",children:[k.map((Z,U)=>f.jsx(ri.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.3,delay:U*.05},className:"mb-8",children:f.jsx(f1e,{message:Z,model:L||null,isLoading:T&&U===k.length-1,onEdit:()=>{},onRegenerate:I,onCopy:fe,showActions:!0,serverConfigs:t,onCallTool:q,onSendFollowup:K,toolsMetadata:v,serverId:E.length===1?E[0]:void 0})},Z.id)),T&&k.length>0&&k[k.length-1].role==="user"&&f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"mb-8",children:f.jsxs("div",{className:"flex gap-4 items-start",children:[f.jsx("div",{className:"w-8 h-8 flex items-center rounded-full justify-center bg-muted/50 shrink-0",children:f.jsx(SB,{className:"h-4 w-4 text-muted-foreground"})}),f.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[f.jsx("span",{className:"text-sm text-muted-foreground",children:"Thinking"}),f.jsxs("div",{className:"flex space-x-1",children:[f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce delay-100"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce delay-200"})]})]})]})})]})})}),f.jsx(pb,{children:R&&f.jsx(ri.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},className:"px-4 py-3 bg-destructive/5 border-t border-destructive/10",children:f.jsx("div",{className:"max-w-4xl mx-auto",children:f.jsx("p",{className:"text-sm text-destructive",children:R})})})}),f.jsx("div",{className:"border-t border-border/50 bg-background/80 backdrop-blur-sm flex-shrink-0",children:f.jsx("div",{className:"max-w-4xl mx-auto p-4",children:f.jsx("div",{children:f.jsx(Q4,{value:j,onChange:A,onSubmit:(Z,U)=>{u.capture("send_message",{location:"chat_tab",platform:on(),environment:void 0,model_id:L?.id??null,model_name:L?.name??null,model_provider:L?.provider??null}),N(Z,U)},onStop:M,disabled:z.length===0||S||G,isLoading:T,placeholder:G?ee:"Send a message...",className:"border-2 shadow-sm",currentModel:L,availableModels:z,onModelChange:H,onClearChat:O,hasMessages:P,systemPrompt:d,onSystemPromptChange:p,temperature:h,onTemperatureChange:g,isSendBlocked:G})})})}),f.jsx(TT,{elicitationRequest:V,onResponse:F,loading:X})]})}),f.jsx(Ua,{withHandle:!0}),f.jsx(cr,{defaultSize:30,minSize:20,maxSize:50,children:f.jsx(L0,{})})]})})}function S7(t,e,n){const r=n.reduce((i,a)=>(a.status==="pending"||a.status==="running"||a.result==="pending"?i.pending+=1:a.result==="passed"?i.passed+=1:a.result==="failed"?i.failed+=1:a.result==="cancelled"&&(i.cancelled+=1),i.tokens+=a.tokensUsed||0,i),{passed:0,failed:0,cancelled:0,pending:0,tokens:0}),s=new Map;for(const i of n){const a=i.testCaseId;if(!a)continue;if(!s.has(a)){const u=e.find(p=>p._id===a),d=n.filter(p=>p.testCaseId===a).length;s.set(a,{testCaseId:a,title:u?.title||"Untitled",provider:u?.provider||"",model:u?.model||"",runs:d,passed:0,failed:0,cancelled:0,tokens:0})}const l=s.get(a);i.status==="pending"||i.status==="running"||i.result==="pending"||(i.result==="passed"?l.passed+=1:i.result==="failed"?l.failed+=1:i.result==="cancelled"&&(l.cancelled+=1)),l.tokens+=i.tokensUsed||0}return{filteredIterations:n,totals:r,byCase:Array.from(s.values())}}function Wke(t,e,n,r){const s=[];return t>0&&s.push(`${t} passed`),e>0&&s.push(`${e} failed`),n>0&&s.push(`${n} cancelled`),r>0&&s.push(`${r} pending`),s.join(" · ")||"No results"}function Yke({suite:t,onSelectSuite:e}){const{isAuthenticated:n}=pa(),{user:r}=Fi(),s=t.config?.environment.servers,a=Eb("evals:getAllTestCasesAndIterationsBySuite",n&&!!r?{suiteId:t._id}:"skip"),l=w.useMemo(()=>a?S7(t,a.testCases,a.iterations):null,[t,a]),u=Array.isArray(t.config?.tests)?t.config.tests.length:0,d=w.useMemo(()=>{if(!Array.isArray(s))return[];const g=s.filter(x=>typeof x=="string").map(x=>x.trim()).filter(Boolean);if(g.length<=2)return g;const v=g.length-2;return[...g.slice(0,2),`+${v} more`]},[s]),p=l?.filteredIterations.length??0,h=()=>{if(!l)return"bg-zinc-300/50";const{passed:g,failed:v,cancelled:x,pending:b}=l.totals;if(g+v+x+b===0)return"bg-zinc-300/50";const S=g+v;if(S===0)return"bg-zinc-300/50";const k=v/S*100;return k===0?"bg-emerald-500/50":k<=30?"bg-amber-500/50":"bg-red-500/50"};return f.jsxs("button",{onClick:()=>e(t._id),className:"group relative flex w-full items-center gap-4 py-3 pl-4 pr-4 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer",children:[f.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${h()}`}),f.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] items-center gap-4",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:new Date(t._creationTime||0).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}),f.jsx("div",{className:"text-xs text-muted-foreground",children:d.length>0?d.join(", "):"No servers"})]}),f.jsxs("div",{className:"text-sm text-muted-foreground",children:[u," test",u!==1?"s":""," · ",p," ","iteration",p!==1?"s":""]}),f.jsx("div",{className:"text-sm text-muted-foreground",children:l?Wke(l.totals.passed,l.totals.failed,l.totals.cancelled,l.totals.pending):"Loading..."})]})]})}function Kke({suites:t,onSelectSuite:e}){if(t.length===0)return f.jsx("div",{className:"h-[calc(100vh-220px)] flex items-center justify-center rounded-xl border border-dashed",children:f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("div",{className:"text-lg font-semibold",children:"No evaluation suites yet"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Trigger a test run to see your evaluation history here."})]})});const n=[...t].sort((r,s)=>(s._creationTime||0)-(r._creationTime||0));return f.jsx("div",{className:"space-y-4",children:f.jsxs("div",{className:"overflow-hidden rounded-xl border",children:[f.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] items-center gap-4 border-b bg-muted/50 px-4 py-2 text-xs font-semibold text-muted-foreground",children:[f.jsx("div",{children:"Created"}),f.jsx("div",{children:"Tests"}),f.jsx("div",{children:"Results"})]}),f.jsx("div",{className:"divide-y",children:n.map(r=>f.jsx(Yke,{suite:r,onSelectSuite:e},r._id))})]})})}function Xke({iteration:t,testCase:e}){const n=Oke("evals:getEvalTestBlob"),[r,s]=w.useState(null),[i,a]=w.useState(!1),[l,u]=w.useState(null);return w.useEffect(()=>{let d=!1;async function p(){if(!t.blob){s(null),a(!1),u(null);return}a(!0),u(null);try{const h=await n({blobId:t.blob});d||s(h)}catch(h){d||(u(h?.message||"Failed to load blob"),console.error("Blob load error:",h))}finally{d||a(!1)}}return p(),()=>{d=!0}},[t.blob,n]),f.jsxs("div",{className:"space-y-3 py-2",children:[(e?.expectedToolCalls.length||0)>0&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Expected tools"}),f.jsx("div",{className:"flex flex-wrap gap-1.5",children:e?.expectedToolCalls.map((d,p)=>f.jsx(xr,{variant:"outline",className:"font-mono text-xs",children:d},p))})]}),t.actualToolCalls.length>0&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Actual tools called"}),f.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.actualToolCalls.map((d,p)=>f.jsx(xr,{variant:"outline",className:"font-mono text-xs",children:d},p))})]}),t.blob&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Trace"}),f.jsx("div",{className:"rounded-md bg-muted/20 p-3",children:i?f.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading trace"}):l?f.jsx("div",{className:"text-xs text-red-600",children:l}):f.jsx("pre",{className:"max-h-[360px] overflow-auto whitespace-pre-wrap break-words text-xs",children:JSON.stringify(r,null,2)})})]})]})}function Qke({suite:t,cases:e,iterations:n,aggregate:r,onBack:s}){const[i,a]=w.useState(null),[l,u]=w.useState(new Set),d=w.useMemo(()=>{const h=new Map,g=b=>{const E={runs:b.length,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null};let S=0,k=0;return b.forEach(T=>{T.result==="passed"?E.passed+=1:T.result==="failed"?E.failed+=1:T.result==="cancelled"?E.cancelled+=1:E.pending+=1,E.tokens+=T.tokensUsed||0;const R=T.startedAt??T.createdAt,j=T.updatedAt??T.createdAt;if(R&&j){const A=Math.max(j-R,0);S+=A,k+=1}}),k>0&&(E.avgDuration=S/k),E};e.forEach(b=>{h.set(b._id,{testCase:b,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})});const v={testCase:null,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}};n.forEach(b=>{const E=b.testCaseId?h.get(b.testCaseId):void 0;E?E.iterations.push(b):v.iterations.push(b)});const x=e.map(b=>{const E=h.get(b._id),S=[...E.iterations].sort((k,T)=>k.iterationNumber!=null&&T.iterationNumber!=null?k.iterationNumber-T.iterationNumber:(k.createdAt??0)-(T.createdAt??0));return{...E,iterations:S,summary:g(S)}});if(v.iterations.length>0){const b=[...v.iterations].sort((E,S)=>E.iterationNumber!=null&&S.iterationNumber!=null?E.iterationNumber-S.iterationNumber:(E.createdAt??0)-(S.createdAt??0));x.push({...v,iterations:b,summary:g(b)})}return x},[e,n]),p=h=>h==="passed"?"bg-emerald-500/50":h==="failed"?"bg-red-500/50":h==="cancelled"?"bg-zinc-300/50":"bg-amber-500/50";return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{children:f.jsx(Pe,{variant:"ghost",size:"sm",onClick:s,children:"← Back to suites"})}),f.jsx("div",{className:"space-y-4",children:d.map((h,g)=>{const{testCase:v,iterations:x}=h,b=x.length>0,E=v?._id??`unassigned-${g}`,S=l.has(E),k=100,T=v?.query&&v.query.length>k,R=T&&!S?v.query.slice(0,k)+"...":v?.query,j=()=>{u(A=>{const N=new Set(A);return N.has(E)?N.delete(E):N.add(E),N})};return f.jsxs("div",{className:"overflow-hidden rounded-xl border",children:[f.jsx("div",{className:"border-b bg-muted/50 px-4 py-2.5",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-semibold pr-2",children:v?v.title:"Unassigned iterations"}),v?.provider?f.jsx(f.Fragment,{children:f.jsx("span",{className:"text-xs text-muted-foreground",children:v.provider})}):null,v?.model?f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-muted-foreground",children:"•"}),f.jsx("span",{className:"text-xs text-muted-foreground",children:v.model})]}):null]}),v?.query?f.jsxs("div",{className:"flex items-start gap-2",children:[f.jsxs("p",{className:"text-xs text-muted-foreground italic flex-1",children:['"',R,'"']}),T?f.jsx("button",{onClick:j,className:"text-xs text-primary hover:underline focus:outline-none whitespace-nowrap",children:S?"Show less":"Show more"}):null]}):null]})}),b?f.jsx("div",{className:"divide-y",children:x.map(A=>{const N=i===A._id,M=A.startedAt??A.createdAt,I=A.updatedAt??A.createdAt,O=M&&I?Math.max(I-M,0):null,L=A.result==="pending";return f.jsxs("div",{className:`relative ${L?"opacity-60":""}`,children:[f.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${p(A.result)}`}),f.jsx("button",{onClick:()=>{L||a(z=>z===A._id?null:A._id)},disabled:L,className:`flex w-full items-center gap-4 px-4 py-3 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${L?"cursor-not-allowed":"cursor-pointer hover:bg-muted/50"}`,children:f.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-[auto_1fr_auto_auto] items-center gap-4 pl-3",children:[f.jsx("div",{className:"text-muted-foreground",children:L?f.jsx(la,{className:"h-4 w-4"}):N?f.jsx(cc,{className:"h-4 w-4"}):f.jsx(la,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-sm font-medium",children:["Iteration #",A.iterationNumber]}),L?f.jsx(bu,{className:"h-4 w-4 animate-spin text-amber-600"}):null]}),f.jsx("div",{className:"text-sm text-muted-foreground",children:L?"—":`${Number(A.tokensUsed||0).toLocaleString()} tokens`}),f.jsx("div",{className:"text-sm text-muted-foreground",children:L?"—":O!==null?Jke(O):"—"})]})}),N&&!L?f.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:f.jsx(Xke,{iteration:A,testCase:v})}):null]},A._id)})}):f.jsx("div",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:"No iterations recorded for this test case yet."})]},E)})})]})}function Jke(t){if(t<1e3)return`${t}ms`;const e=Math.round(t/1e3);if(e<60)return`${e}s`;const n=Math.floor(e/60),r=e%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const s=Math.floor(n/60),i=n%60;return i?`${s}h ${i}m`:`${s}h`}function Zke(){const{isAuthenticated:t,isLoading:e}=pa(),{user:n}=Fi(),[r,s]=w.useState(null),i=t&&!!n,a=Eb("evals:getCurrentUserEvalTestSuitesWithMetadata",i?{}:"skip"),l=t&&!!n&&!!r,u=Eb("evals:getAllTestCasesAndIterationsBySuite",l?{suiteId:r}:"skip"),d=a?.testSuites,p=a===void 0,h=l&&u===void 0,g=w.useMemo(()=>!r||!d?null:d.find(b=>b._id===r)??null,[r,d]),v=w.useMemo(()=>u?[...u.iterations].sort((b,E)=>(E.startedAt||E.createdAt)-(b.startedAt||b.createdAt)):[],[u]),x=w.useMemo(()=>!g||!u?null:S7(g,u.testCases,u.iterations),[g,u]);return e?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!n?f.jsx("div",{className:"p-6",children:f.jsx(rh,{icon:wB,title:"Sign in to view your evals",description:"Create an account or sign in to see previous runs and metrics.",className:"h-[calc(100vh-200px)]"})}):p&&i?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading your eval data..."})]})})}):f.jsxs("div",{className:"space-y-6 p-6",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsx("h1",{className:"text-2xl font-semibold",children:"Evaluation results"})}),g?h?f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading suite details..."})]})}):f.jsx(Qke,{suite:g,cases:u?.testCases||[],iterations:v,aggregate:x,onBack:()=>s(null)}):f.jsx(Kke,{suites:d||[],onSelectSuite:s})]})}const eTe="modulepreload",tTe=function(t){return"/"+t},J4={},nTe=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let d=function(p){return Promise.all(p.map(h=>Promise.resolve(h).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};var a=d;document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=d(n.map(p=>{if(p=tTe(p),p in J4)return;J4[p]=!0;const h=p.endsWith(".css"),g=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${g}`))return;const v=document.createElement("link");if(v.rel=h?"stylesheet":eTe,h||(v.as="script"),v.crossOrigin="",v.href=p,u&&v.setAttribute("nonce",u),document.head.appendChild(v),h)return new Promise((x,b)=>{v.addEventListener("load",x),v.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},RC={servers:{},selectedServer:"none",selectedMultipleServers:[],isMultiSelectMode:!1},Tp=(t,e,n={})=>({...t,connectionStatus:e,...n});function rTe(t,e){switch(e.type){case"HYDRATE_STATE":return e.payload;case"UPSERT_SERVER":return{...t,servers:{...t.servers,[e.name]:e.server}};case"CONNECT_REQUEST":{const n=t.servers[e.name],r=n?Tp(n,"connecting",{enabled:!0}):{name:e.name,config:e.config,lastConnectionTime:new Date,connectionStatus:"connecting",retryCount:0,enabled:!0};return{...t,servers:{...t.servers,[e.name]:{...r,config:e.config}},selectedServer:e.select?e.name:t.selectedServer}}case"CONNECT_SUCCESS":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"connected",{config:e.config,lastConnectionTime:new Date,retryCount:0,lastError:void 0,oauthTokens:e.tokens??n.oauthTokens,enabled:!0})}}:t}case"CONNECT_FAILURE":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"failed",{retryCount:n.retryCount,lastError:e.error})}}:t}case"RECONNECT_REQUEST":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"connecting",{enabled:!0})}}:t}case"DISCONNECT":{const n=t.servers[e.name];if(!n)return t;const r=t.selectedServer===e.name?"none":t.selectedServer;return{...t,servers:{...t.servers,[e.name]:Tp(n,"disconnected",{enabled:!1,lastError:e.error??n.lastError})},selectedServer:r,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"REMOVE_SERVER":{const{[e.name]:n,...r}=t.servers;return{...t,servers:r,selectedServer:t.selectedServer===e.name?"none":t.selectedServer,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"SYNC_AGENT_STATUS":{const n=new Map(e.servers.map(s=>[s.id,s.status])),r={};for(const[s,i]of Object.entries(t.servers)){if(i.connectionStatus==="connecting"||i.connectionStatus==="oauth-flow"){r[s]=i;continue}const l=n.get(s);l?r[s]={...i,connectionStatus:l}:r[s]={...i,connectionStatus:"disconnected"}}return{...t,servers:r}}case"SELECT_SERVER":return{...t,selectedServer:e.name};case"SET_MULTI_SELECTED":return{...t,selectedMultipleServers:e.names};case"SET_MULTI_MODE":return{...t,isMultiSelectMode:e.enabled,selectedMultipleServers:e.enabled?[]:t.selectedMultipleServers};default:return t}}const E7="mcp-inspector-state";function sTe(t){const e=t.config;let n=e;if(e&&typeof e.url=="string")try{n={...e,url:new URL(e.url)}}catch{}return{...t,config:n,connectionStatus:t.connectionStatus||"disconnected",retryCount:t.retryCount||0,lastConnectionTime:t.lastConnectionTime?new Date(t.lastConnectionTime):new Date,enabled:t.enabled!==!1}}function iTe(){try{const t=localStorage.getItem(E7);if(!t)return RC;const e=JSON.parse(t);return{servers:Object.fromEntries(Object.entries(e.servers||{}).map(([r,s])=>[r,sTe(s)])),selectedServer:e.selectedServer||"none",selectedMultipleServers:e.selectedMultipleServers||[],isMultiSelectMode:e.isMultiSelectMode||!1}}catch{return RC}}function aTe(t){const e={...t,servers:Object.fromEntries(Object.entries(t.servers).map(([n,r])=>{const s=r.config,i=s&&s.url instanceof URL?{...s,url:s.url.toString()}:s;return[n,{...r,config:i}]}))};localStorage.setItem(E7,JSON.stringify(e))}async function Ey(t,e){return(await fetch("/api/mcp/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverConfig:t,serverId:e})})).json()}async function oTe(t){return(await fetch(`/api/mcp/servers/${encodeURIComponent(t)}`,{method:"DELETE"})).json()}async function lTe(){return(await fetch("/api/mcp/servers")).json()}async function cTe(t,e){return(await fetch("/api/mcp/servers/reconnect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:t,serverConfig:e})})).json()}async function uTe(t){if(!t.oauthTokens&&!RN(t.name))return{kind:"ready",serverConfig:t.config,tokens:void 0};if(t.oauthTokens){const a=await jN(t.name);if(a.success&&a.serverConfig)return{kind:"ready",serverConfig:a.serverConfig,tokens:si(t.name)}}const e=localStorage.getItem(`mcp-serverUrl-${t.name}`),n=localStorage.getItem(`mcp-client-${t.name}`),r=localStorage.getItem(`mcp-oauth-config-${t.name}`),s=si(t.name),i=t.config?.url?.toString?.()||e;if(i){const a=r?JSON.parse(r):{},l=n?JSON.parse(n):{},u={serverName:t.name,serverUrl:i,clientId:t.oauthTokens?.client_id||s?.client_id||l?.client_id,clientSecret:t.oauthTokens?.client_secret||l?.client_secret,scopes:a.scopes},d=await tb(u);return d.success&&d.serverConfig?{kind:"ready",serverConfig:d.serverConfig,tokens:si(t.name)}:d.success&&!d.serverConfig?{kind:"redirect"}:{kind:"error",error:d.error||"OAuth init failed"}}return{kind:"error",error:"OAuth refresh failed and no URL present"}}function U1(t){return t.type==="stdio"?{command:t.command,args:t.args,env:t.env}:{url:new URL(t.url),requestInit:{headers:t.headers||{}}}}function k7(){const t=QN("Connections"),[e,n]=w.useReducer(rTe,RC),[r,s]=w.useState(!0),i=w.useRef(new Map),a=A=>{const M=(i.current.get(A)??0)+1;return i.current.set(A,M),M},l=(A,N)=>(i.current.get(A)??0)!==N;w.useEffect(()=>{try{const A=iTe();n({type:"HYDRATE_STATE",payload:A})}catch(A){t.error("Failed to load saved state",{error:A instanceof Error?A.message:"Unknown error"})}finally{s(!1)}},[t]),w.useEffect(()=>{r||aTe(e)},[e,r]);const u=A=>{if(A.type==="stdio")return!A.command||A.command.trim()===""?"Command is required for STDIO connections":null;if(!A.url||A.url.trim()==="")return"URL is required for HTTP connections";try{new URL(A.url)}catch(N){return`Invalid URL format: ${A.url} ${N}`}return null},d=w.useCallback(()=>{const A=Object.entries(e.servers).filter(([,N])=>N.connectionStatus==="connected").map(([N])=>N);n({type:"SET_MULTI_SELECTED",names:A})},[e.servers]),p=w.useCallback(async A=>{window.history.replaceState({},document.title,window.location.pathname);try{const N=await dq(A);if(N.success&&N.serverConfig&&N.serverName){const M=N.serverName;n({type:"CONNECT_REQUEST",name:M,config:N.serverConfig,select:!0});try{const I=await Ey(N.serverConfig,M);I.success?(n({type:"CONNECT_SUCCESS",name:M,config:N.serverConfig,tokens:si(M)}),t.info("OAuth connection successful",{serverName:M}),It.success(`OAuth connection successful! Connected to ${M}.`)):(n({type:"CONNECT_FAILURE",name:M,error:I.error||"Connection test failed after OAuth"}),t.error("OAuth connection test failed",{serverName:M,error:I.error}),It.error(`OAuth succeeded but connection test failed: ${I.error}`))}catch(I){const O=I instanceof Error?I.message:"Unknown connection error";n({type:"CONNECT_FAILURE",name:M,error:O}),t.error("OAuth connection test error",{serverName:M,error:O}),It.error(`OAuth succeeded but connection test failed: ${O}`)}}else throw new Error(N.error||"OAuth callback failed")}catch(N){const M=N instanceof Error?N.message:"Unknown error";It.error(`Error completing OAuth flow: ${M}`),t.error("OAuth callback failed",{error:M})}},[t]);w.useEffect(()=>{if(!r){const A=new URLSearchParams(window.location.search),N=A.get("code"),M=A.get("error");N?p(N):M&&(It.error(`OAuth authorization failed: ${M}`),localStorage.removeItem("mcp-oauth-pending"),window.history.replaceState({},document.title,window.location.pathname))}},[r,p]);const h=w.useCallback(async A=>{const N=u(A);if(N){It.error(N);return}const M=U1(A);n({type:"CONNECT_REQUEST",name:A.name,config:M,select:!0});const I=a(A.name);try{if(A.type==="http"&&A.useOAuth&&A.url){n({type:"UPSERT_SERVER",name:A.name,server:{name:A.name,config:M,lastConnectionTime:new Date,connectionStatus:"oauth-flow",retryCount:0,enabled:!0}});const{initiateOAuth:L}=await nTe(async()=>{const{initiateOAuth:V}=await Promise.resolve().then(()=>Gue);return{initiateOAuth:V}},void 0),z={serverName:A.name,serverUrl:A.url,clientId:A.clientId,clientSecret:A.clientSecret};A.oauthScopes&&A.oauthScopes.length>0&&(z.scopes=A.oauthScopes);const H=await L(z);if(H.success){if(H.serverConfig){const V=await Ey(H.serverConfig,A.name);if(l(A.name,I))return;V.success?(n({type:"CONNECT_SUCCESS",name:A.name,config:H.serverConfig,tokens:si(A.name)}),It.success("Connected successfully with OAuth!")):(n({type:"CONNECT_FAILURE",name:A.name,error:V.error||"OAuth connection test failed"}),It.error(`OAuth succeeded but connection failed: ${V.error}`))}else It.success("OAuth flow initiated. You will be redirected to authorize access.");return}else{if(l(A.name,I))return;n({type:"CONNECT_FAILURE",name:A.name,error:H.error||"OAuth initialization failed"}),It.error(`OAuth initialization failed: ${H.error}`);return}}const O=await Ey(M,A.name);if(l(A.name,I))return;O.success?(n({type:"CONNECT_SUCCESS",name:A.name,config:M}),t.info("Connection successful",{serverName:A.name}),It.success("Connected successfully!")):(n({type:"CONNECT_FAILURE",name:A.name,error:O.error||"Connection test failed"}),t.error("Connection failed",{serverName:A.name,error:O.error}),It.error(`Failed to connect to ${A.name}`))}catch(O){const L=O instanceof Error?O.message:"Unknown error";if(l(A.name,I))return;n({type:"CONNECT_FAILURE",name:A.name,error:L}),t.error("Connection failed",{serverName:A.name,error:L}),It.error(`Network error: ${L}`)}},[e.servers,t]),g=w.useRef(!1);w.useEffect(()=>{!r&&!g.current&&(g.current=!0,fetch("/api/mcp-cli-config").then(A=>A.json()).then(A=>{const N=A.config;if(N){if(N.servers&&Array.isArray(N.servers)){const M=N.autoConnectServer;t.info("Processing CLI-provided MCP servers (from config file)",{serverCount:N.servers.length,autoConnectServer:M||"all",cliConfig:N}),N.servers.forEach(I=>{const O={name:I.name||"CLI Server",type:I.type==="sse"?"http":I.type||"stdio",command:I.command,args:I.args||[],url:I.url,env:I.env||{}},L=U1(O);n({type:"UPSERT_SERVER",name:O.name,server:{name:O.name,config:L,lastConnectionTime:new Date,connectionStatus:"disconnected",retryCount:0,enabled:!1}}),!M||I.name===M?(t.info("Auto-connecting to server",{serverName:I.name}),h(O)):t.info("Skipping auto-connect for server",{serverName:I.name,reason:"filtered out"})});return}if(N.command){t.info("Auto-connecting to CLI-provided MCP server",{cliConfig:N});const M={name:N.name||"CLI Server",type:"stdio",command:N.command,args:N.args||[],env:N.env||{}};h(M)}}}).catch(A=>{t.debug("Could not fetch CLI config from API",{error:A})}))},[r,h,t,e.servers]);const v=w.useCallback(async A=>{const N=e.servers[A];return N?.oauthTokens&&N.oauthTokens.access_token||null},[e.servers]),x=w.useCallback(async A=>{t.info("Disconnecting from server",{serverName:A}),n({type:"DISCONNECT",name:A});try{const N=await oTe(A);N.success||n({type:"DISCONNECT",name:A,error:N.error})}catch(N){n({type:"DISCONNECT",name:A,error:N instanceof Error?N.message:"Unknown error"})}},[]),b=w.useCallback(async A=>{t.info("Removing server",{serverName:A}),nb(A),n({type:"REMOVE_SERVER",name:A})},[]),E=w.useCallback(async A=>{t.info("Reconnecting to server",{serverName:A});const N=e.servers[A];if(!N)throw new Error(`Server ${A} not found`);n({type:"RECONNECT_REQUEST",name:A});const M=a(A);try{const I=await uTe(N);if(I.kind==="redirect")return;if(I.kind==="error"){if(l(A,M))return;n({type:"CONNECT_FAILURE",name:A,error:I.error}),It.error(`Failed to connect: ${A}`);return}const O=await cTe(A,I.serverConfig);if(l(A,M))return;if(O.success)return n({type:"CONNECT_SUCCESS",name:A,config:I.serverConfig,tokens:I.tokens}),t.info("Reconnection successful",{serverName:A,result:O}),{success:!0};{n({type:"CONNECT_FAILURE",name:A,error:O.error||"Reconnection failed"}),t.error("Reconnection failed",{serverName:A,result:O});const L=O.error||`Failed to reconnect: ${A}`;It.error(L)}}catch(I){const O=I instanceof Error?I.message:"Unknown error";if(l(A,M))return;throw n({type:"CONNECT_FAILURE",name:A,error:O}),t.error("Reconnection failed",{serverName:A,error:O}),I}},[e.servers]);w.useEffect(()=>{if(r)return;(async()=>{try{const N=await lTe();N?.success&&N.servers&&n({type:"SYNC_AGENT_STATUS",servers:N.servers})}catch(N){t.debug("Failed to sync server status on startup",{error:N instanceof Error?N.message:"Unknown error"})}})()},[r,t]);const S=w.useCallback(A=>{n({type:"SELECT_SERVER",name:A})},[]),k=w.useCallback(A=>{n({type:"SET_MULTI_SELECTED",names:A})},[]),T=w.useCallback(A=>{n({type:"SET_MULTI_MODE",enabled:A})},[]),R=w.useCallback(A=>{const N=e.selectedMultipleServers,M=N.includes(A)?N.filter(I=>I!==A):[...N,A];n({type:"SET_MULTI_SELECTED",names:M})},[e.selectedMultipleServers]),j=w.useCallback(async(A,N)=>{const M=e.servers[A];if(M?.oauthTokens!=null&&N.useOAuth&&N.name===A&&N.type==="http"&&N.url===(M?.config).url?.toString()&&M){const L=U1(N);n({type:"CONNECT_REQUEST",name:A,config:L});try{if((await Ey(M.config,A)).success){n({type:"CONNECT_SUCCESS",name:A,config:L}),It.success("Server configuration updated successfully!");return}else console.warn("OAuth connection test failed, falling back to full reconnect")}catch(z){console.warn("OAuth connection test error, falling back to full reconnect",z)}}await x(A),await h(N),e.selectedServer===A&&N.name!==A&&S(N.name)},[e.servers,e.selectedServer,x,h]);return{appState:e,isLoading:r,connectedServerConfigs:e.servers,selectedServerEntry:e.servers[e.selectedServer],selectedMCPConfig:e.servers[e.selectedServer]?.config,selectedMCPConfigs:e.selectedMultipleServers.map(A=>e.servers[A]).filter(Boolean),selectedMCPConfigsMap:e.selectedMultipleServers.reduce((A,N)=>(e.servers[N]&&(A[N]=e.servers[N].config),A),{}),isMultiSelectMode:e.isMultiSelectMode,handleConnect:h,handleDisconnect:x,handleReconnect:E,handleUpdate:j,handleRemoveServer:b,setSelectedServer:S,setSelectedMCPConfigs:k,toggleMultiSelectMode:T,toggleServerSelection:R,getValidAccessToken:v,setSelectedMultipleServersToAllServers:d}}function dTe({server:t,selected:e,onToggle:n}){const[r,s]=w.useState(null),[i,a]=w.useState(!1),{label:l,Icon:u,iconClassName:d,indicatorColor:p}=TB(t.connectionStatus),h=AB(t.config),g=CB(t.config),v=JSON.stringify(t.config,null,2),x=()=>{n(t.name)},b=k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),x())},E=async(k,T,R)=>{k.stopPropagation();try{await navigator.clipboard.writeText(T),s(R),setTimeout(()=>s(null),2e3)}catch(j){console.error("Failed to copy text:",j)}},S=t.connectionStatus==="failed"?`${l} (${t.retryCount} retries)`:l;return f.jsxs(Ha,{role:"button",tabIndex:0,onClick:x,onKeyDown:b,className:Oe("relative gap-3 p-3 border border-border/40 bg-card/40 transition-colors","hover:border-border cursor-pointer",e&&"border-primary/60 ring-2 ring-primary/30"),children:[f.jsxs("div",{className:"flex items-start justify-between gap-2",children:[f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:p}}),f.jsx("div",{className:"min-w-0",children:f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[f.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.name}),f.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[f.jsx(u,{className:d}),f.jsx("span",{children:S})]})]})})]}),e&&f.jsxs(xr,{variant:"secondary",className:"h-5 px-1 text-[11px]",children:[f.jsx(Ri,{className:"mr-1 h-3 w-3"}),"Selected"]})]}),f.jsx("p",{className:"mt-0.5 text-[11px] uppercase tracking-wide text-muted-foreground",children:h}),f.jsxs("div",{className:"relative break-all rounded border border-border/30 bg-muted/30 p-1.5 font-mono text-[11px] text-muted-foreground",children:[f.jsx("div",{className:"pr-6",children:g}),f.jsx("button",{type:"button",onClick:k=>E(k,g,"command"),className:"absolute right-1 top-1 cursor-pointer p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:r==="command"?f.jsx(Ri,{className:"h-3 w-3 text-green-500"}):f.jsx(zo,{className:"h-3 w-3"})})]}),i&&f.jsxs("div",{className:"relative rounded border border-border/20 bg-muted/20 p-1.5 font-mono text-[11px] text-muted-foreground",children:[f.jsx("pre",{className:"max-h-40 overflow-auto pr-6 whitespace-pre-wrap",children:v}),f.jsx("button",{type:"button",onClick:k=>E(k,v,"config"),className:"absolute right-1 top-1 cursor-pointer p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:r==="config"?f.jsx(Ri,{className:"h-3 w-3 text-green-500"}):f.jsx(zo,{className:"h-3 w-3"})})]}),f.jsx("div",{className:"flex justify-end pt-0.5",children:f.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),a(T=>!T)},"aria-label":i?"Hide config":"Show config",className:"rounded-full border border-border/50 bg-background/70 p-1 text-muted-foreground transition-colors hover:text-foreground",children:i?f.jsx(_B,{className:"h-3 w-3"}):f.jsx(cc,{className:"h-3 w-3"})})})]})}const Z4="mcp-inspector-eval-runner-preferences",Tl=[{key:"servers",title:"Select Servers",description:"Choose the MCP servers to evaluate."},{key:"model",title:"Choose Model",description:"Pick the model and ensure credentials are ready."},{key:"tests",title:"Define Tests",description:"Author the scenarios you want to run or generate them with AI."},{key:"review",title:"Review & Run",description:"Confirm the configuration before launching the run."}],B1=(t,e)=>({title:"",query:"",runs:1,model:e?.id??"",provider:e?.provider??"",expectedToolCalls:[]});function fTe({availableModels:t,inline:e=!1}){const[n,r]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(!1),[u,d]=w.useState(0),[p,h]=w.useState(null),{isAuthenticated:g}=pa(),{getAccessToken:v}=Fi(),{appState:x}=k7(),{getToken:b,hasToken:E}=lR(),[S,k]=w.useState([]),[T,R]=w.useState(null),[j,A]=w.useState([B1(1,null)]),N=w.useMemo(()=>Object.entries(x.servers).filter(([,U])=>U.connectionStatus==="connected"),[x.servers]),M=w.useMemo(()=>new Set(N.map(([U])=>U)),[N]);w.useEffect(()=>{if(!(typeof window>"u"))try{const U=localStorage.getItem(Z4);if(!U)return;const J=JSON.parse(U);h({servers:J.servers??[],modelId:J.modelId??null})}catch(U){console.warn("Failed to load eval runner preferences",U)}},[]),w.useEffect(()=>{if(p&&p.servers?.length){const U=p.servers.filter(J=>M.has(J));U.length&&k(U)}},[p,M]),w.useEffect(()=>{if(t.length===0){R(null);return}if(p?.modelId){const U=t.find(J=>J.id===p.modelId);if(U){R(U);return}}R(U=>U&&t.some(oe=>oe.id===U.id)?U:t[0])},[t,p]),w.useEffect(()=>{if(!(typeof window>"u"))try{const U={servers:S,modelId:T?.id??null};localStorage.setItem(Z4,JSON.stringify(U))}catch(U){console.warn("Failed to persist eval runner preferences",U)}},[S,T]),w.useEffect(()=>{A(U=>T?U.map((J,oe)=>J.model===T.id&&J.provider===T.provider?J:{...J,model:T.id,provider:T.provider}):U)},[T]),w.useEffect(()=>{!e&&!n&&d(0)},[e,n]);const I=T?ra(T.id):!1,O=T?.provider,L=O?E(O):!1,z=w.useMemo(()=>j.filter(U=>U.query.trim().length>0),[j]),H=w.useMemo(()=>({servers:S.length>0,model:!!T&&(I||O&&L),tests:z.length>0}),[z.length,T,I,O,L,S.length]),V=w.useMemo(()=>H.servers?H.model?H.tests?3:2:1:0,[H]),X=w.useMemo(()=>{switch(u){case 0:return H.servers;case 1:return H.model;case 2:return H.tests;case 3:return H.tests&&H.servers&&H.model;default:return!1}},[u,H]),F=U=>{k(J=>J.includes(U)?J.filter(oe=>oe!==U):[...J,U])},W=U=>{A(J=>{const oe=J.length,pe=Array.from({length:U},(ye,je)=>B1(oe+je+1,T));return[...J,...pe]})},G=()=>{W(1)},ee=U=>{A(J=>J.filter((oe,pe)=>pe!==U))},P=(U,J,oe)=>{A(pe=>{const ye=[...pe];return ye[U]={...ye[U],[J]:oe},ye})},ie=async()=>{if(!g){It.error("Please sign in to generate tests");return}if(S.length===0){It.error("Please select at least one server");return}l(!0);try{const U=await v(),J=await fetch("/api/mcp/evals/generate-tests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:S,convexAuthToken:U})}),oe=await J.json();if(!J.ok)throw new Error(oe.error||"Failed to generate tests");if(oe.tests&&oe.tests.length>0){const pe=oe.tests.map((ye,je)=>({title:ye.title||`Generated test ${je+1}`,query:ye.query||"",runs:Number(ye.runs)>0?Number(ye.runs):1,model:T?.id||"",provider:T?.provider||"",expectedToolCalls:Array.isArray(ye.expectedToolCalls)?ye.expectedToolCalls:[]}));A(pe),d(2),It.success(`Generated ${pe.length} test case(s).`)}}catch(U){console.error("Failed to generate tests:",U),It.error(U instanceof Error?U.message:"Failed to generate test cases")}finally{l(!1)}},ue=()=>{u>=Tl.length-1||X&&d(U=>Math.min(U+1,Tl.length-1))},D=()=>{u!==0&&d(U=>Math.max(U-1,0))},ne=async()=>{if(!g){It.error("Please sign in to run evals");return}if(S.length===0){It.error("Please select at least one server"),d(0);return}if(!T){It.error("Please select a model"),d(1);return}const U=ra(T.id),J=!U&&O?b(O):"";if(!U&&(!O||!J)){It.error(`Please configure your ${T.provider} API key in Settings`),d(1);return}if(z.length===0){It.error("Please add at least one test case with a query"),d(2);return}i(!0);try{const oe=await v(),pe=z.map(Ne=>({...Ne,model:T.id,provider:T.provider})),ye=await fetch("/api/mcp/evals/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tests:pe,serverIds:S,llmConfig:{provider:T.provider,apiKey:U?"router":J||"router"},convexAuthToken:oe})}),je=await ye.json();if(!ye.ok)throw new Error(je.error||"Failed to start evals");It.success(je.message||"Evals started successfully!"),A([B1(1,T)]),d(3),e||r(!1),window.location.hash="eval-results"}catch(oe){It.error(oe instanceof Error?oe.message:"Failed to start evals")}finally{i(!1)}},fe=()=>{switch(Tl[u].key){case"servers":return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Select servers to test"}),f.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Choose at least one connected MCP server. You can evaluate multiple servers in the same run."})]})}),N.length>0?f.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:N.map(([U,J])=>{const oe=S.includes(U);return f.jsx(dTe,{server:J,selected:oe,onToggle:F},U)})}):f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"No connected servers yet"}),f.jsx("p",{className:"mt-2",children:"Launch a server from the Servers tab to make it available here. Once connected, it will appear instantly."})]})]});case"model":return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Choose your evaluation model"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"For example, if you want to simulate using your server with Claude Desktop, select an Anthropic model."})]})}),t.length===0?f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"No models available"}),f.jsx("p",{className:"mt-2",children:"Connect a provider or enable MCPJam provided models in Settings to unlock model selection."})]}):T?f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"flex items-center gap-3",children:f.jsx(w7,{currentModel:T,availableModels:t,onModelChange:R})}),!I&&!L&&O&&f.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/5 p-3 text-sm",children:[f.jsx(Am,{className:"mt-0.5 h-4 w-4 text-destructive"}),f.jsxs("div",{children:[f.jsxs("p",{className:"font-medium text-destructive",children:["Add your ",T.provider," API key"]}),f.jsx("p",{className:"text-muted-foreground",children:"Configure credentials in Settings to run this model. Keys are stored locally and never sent to our servers."})]})]})]}):null]});case"tests":return f.jsxs("div",{className:"space-y-6",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Define your test cases"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Create testing scenarios that simulate how real users would use your server."})]})}),!H.servers||!H.model?f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"Finish previous steps first"}),f.jsx("p",{className:"mt-2",children:"Select at least one server and choose a model to unlock test authoring. That ensures generated tests know which stack to target."})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex flex-wrap items-center justify-between gap-2",children:f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Pe,{type:"button",variant:"outline",size:"lg",onClick:ie,disabled:a,children:[f.jsx("span",{className:"bg-gradient-to-r from-purple-600 via-violet-600 to-indigo-600 bg-clip-text text-transparent",children:a?"Generating...":"Generate tests"}),f.jsx(EB,{className:"h-4 w-4 ml-2 fill-purple-600"})]})})}),a&&f.jsx("div",{className:"flex items-center justify-center rounded-lg border p-6",children:f.jsx("div",{className:"text-center text-sm text-muted-foreground",children:"Generating test cases..."})}),!a&&f.jsxs("div",{className:"space-y-12",children:[j.map((U,J)=>f.jsxs("div",{className:"space-y-3 rounded-lg border bg-background p-4",children:[f.jsxs("div",{className:"flex items-start justify-between gap-3",children:[f.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),f.jsx(Dn,{className:"w-full",value:U.title,onChange:oe=>P(J,"title",oe.target.value),placeholder:"(Paypal) List transactions"})]}),j.length>1&&f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>ee(J),children:f.jsx(uc,{className:"h-4 w-4"})})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Query"}),f.jsx(Qo,{value:U.query,onChange:oe=>P(J,"query",oe.target.value),placeholder:"Can you find the most recent Paypal transactions, then create an invoice?",rows:3})]}),f.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),f.jsx(Dn,{type:"number",min:1,value:U.runs,onChange:oe=>P(J,"runs",Number(oe.target.value)>0?Number(oe.target.value):1)})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Expected tools (comma separated)"}),f.jsx(Dn,{value:U.expectedToolCalls.join(", "),onChange:oe=>P(J,"expectedToolCalls",oe.target.value.split(",").map(pe=>pe.trim()).filter(Boolean)),placeholder:"paypal_list_transactions, paypal_create_invoice"})]})]})]},J)),f.jsxs(Pe,{type:"button",variant:"outline",onClick:G,"aria-label":"Add test",className:"w-full",children:[f.jsx(Ax,{className:"h-4 w-4 mr-2"}),"Add test case"]})]})]})]});case"review":return f.jsxs("div",{className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h3",{className:"text-lg",children:"Review your tests"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"After confirming the run, you will see your run begin in the eval results tab."})]}),f.jsxs("div",{className:"space-y-4 rounded-lg border bg-background p-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Servers"}),f.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:S.map(U=>f.jsx(xr,{variant:"outline",children:U},U))})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(0),children:"Edit"})]}),f.jsx(Rk,{}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Model"}),T?f.jsx("div",{className:"mt-2 flex items-center gap-2",children:f.jsx(xr,{variant:"outline",children:T.name})}):f.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No model selected"})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(1),children:"Edit"})]}),f.jsx(Rk,{}),f.jsxs("div",{className:"flex items-start justify-between gap-6",children:[f.jsxs("div",{className:"flex-1",children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Tests"}),f.jsx("div",{className:"mt-3 space-y-3",children:z.map((U,J)=>f.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[f.jsx("p",{className:"text-sm font-semibold text-foreground",children:U.title}),f.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:U.query}),f.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[f.jsxs("span",{children:[U.runs," run",U.runs===1?"":"s"]}),U.expectedToolCalls.length>0&&f.jsxs("span",{children:["Tools: ",U.expectedToolCalls.join(", ")]})]})]},J))})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(2),children:"Edit"})]})]})]});default:return null}},q=f.jsx("ol",{className:"flex flex-col items-center gap-4 text-center md:flex-row md:gap-6",children:Tl.map((U,J)=>{const oe=u===J,pe=J<u&&J<=V,ye=J<=Math.max(V,u);return f.jsx("li",{className:"flex flex-col items-center gap-2",children:f.jsxs("button",{type:"button",onClick:()=>ye?d(J):void 0,disabled:!ye,className:Oe("flex flex-col items-center gap-2 transition",!ye&&"cursor-not-allowed opacity-60"),children:[f.jsx("span",{className:Oe("flex h-8 w-8 items-center justify-center rounded-full border text-sm font-medium",pe&&"border-primary bg-primary text-primary-foreground",oe&&!pe&&"border-primary bg-primary/10 text-primary",!oe&&!pe&&"border-border text-muted-foreground"),children:J+1}),f.jsx("span",{className:Oe("text-xs leading-tight",oe?"text-foreground":"text-muted-foreground"),children:U.title})]})},U.key)})}),K=u<Tl.length-1?!X:s||!X,Y=K?"secondary":"default",Z=f.jsxs("div",{className:Oe("mx-auto flex w-full flex-col gap-8 pb-10 pt-4",e?"max-w-none px-4 sm:px-6 md:px-12 lg:px-32":"max-w-3xl px-4"),children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.jsxs(Pe,{type:"button",variant:"outline",onClick:D,disabled:u===0,"aria-label":"Back",className:"justify-center gap-2",children:[f.jsx(ose,{className:"h-4 w-4"}),"Back"]}),f.jsx("div",{className:"flex flex-1 justify-center",children:f.jsx("div",{className:"max-w-xl",children:q})}),f.jsxs(Pe,{type:"button",variant:Y,onClick:()=>{u<Tl.length-1?ue():ne()},disabled:K,"aria-label":u===Tl.length-1?"Start":"Next",className:Oe("justify-center gap-2",!K&&"shadow-sm"),children:[u===Tl.length-1?"Start":"Next",f.jsx(la,{className:"h-4 w-4"})]})]}),f.jsx("div",{className:"space-y-6",children:fe()})]});return e?Z:f.jsxs(ua,{open:n,onOpenChange:r,children:[f.jsx(gN,{asChild:!0,children:f.jsxs(Pe,{children:[f.jsx(Ax,{className:"mr-2 h-4 w-4"}),"New eval run"]})}),f.jsxs(da,{className:"max-h-[80vh] w-full max-w-4xl overflow-y-auto sm:max-w-4xl",children:[f.jsxs(fa,{className:"mx-auto w-full max-w-3xl gap-1 text-left",children:[f.jsx(ha,{children:"Create eval run"}),f.jsx(nh,{children:"Follow the guided steps to configure your evaluation and run it with confidence."})]}),Z]})]})}function hTe(){const{isAuthenticated:t,isLoading:e}=pa(),{user:n}=Fi(),{availableModels:r}=xV({systemPrompt:"",temperature:1,selectedServers:[]});return e?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!n?f.jsx("div",{className:"p-6",children:f.jsx(rh,{icon:wB,title:"Sign in to run evals",description:"Create an account or sign in to generate and launch evaluation runs.",className:"h-[calc(100vh-200px)]"})}):f.jsxs("div",{className:"space-y-6 p-6",children:[f.jsx("div",{className:"space-y-2",children:f.jsx("h1",{className:"text-2xl font-semibold",children:"Evaluation runner"})}),f.jsx("div",{className:"w-full",children:f.jsx(fTe,{availableModels:r,inline:!0})})]})}function pTe({config:t,isConfigured:e,onEdit:n,onDelete:r}){const s=t.description?.trim();return f.jsxs(Ha,{className:Oe("group h-full gap-4 border bg-card px-6 py-6 transition-all hover:border-primary/40 hover:shadow-md dark:hover:shadow-xl",e?"border-green-200/80 dark:border-green-400/30":"border-border/60"),children:[f.jsxs("div",{className:"flex items-start justify-between gap-6",children:[f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("img",{src:t.logo,alt:t.logoAlt,className:"size-6 object-contain"}),f.jsxs("div",{className:"",children:[f.jsxs("h3",{className:"text-md font-semibold text-foreground pb-1",children:[t.name," ",e&&f.jsx("span",{className:"text-md",children:"✔️"})]}),s?f.jsx("p",{className:"line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})]}),e?f.jsxs(m0,{children:[f.jsx(g0,{asChild:!0,children:f.jsx(Pe,{size:"icon",variant:"ghost",className:"size-8 rounded-md border border-transparent hover:bg-muted/50",children:f.jsx(jse,{className:"size-4"})})}),f.jsx(v0,{align:"end",className:"w-44",children:f.jsx(Ro,{variant:"destructive",onClick:()=>r(t.id),children:"Remove provider"})})]}):null]}),f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{size:"sm",variant:e?"outline":"secondary",className:"w-full",onClick:()=>n(t.id),children:e?"Manage":"Configure"})})]})}function mTe({baseUrl:t,onEdit:e}){const n=!!t;return f.jsxs(Ha,{className:Oe("group h-full gap-4 border bg-card px-6 py-6 transition-all hover:border-primary/40 hover:shadow-md dark:hover:shadow-xl",n?"border-green-200/80 dark:border-green-400/30":"border-border/60"),children:[f.jsx("div",{className:"flex items-start justify-between gap-6",children:f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"size-6 object-contain"}),f.jsxs("div",{className:"",children:[f.jsxs("h3",{className:"text-md font-semibold text-foreground pb-1",children:["Ollama ",n&&f.jsx("span",{className:"text-md",children:"✔️"})]}),f.jsx("p",{className:"line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:n?"Local models available":"Install and connect Ollama locally"})]})]})}),f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{size:"sm",variant:n?"outline":"secondary",className:"w-full",onClick:e,children:n?"Manage":"Configure"})})]})}function gTe({providerConfigs:t,hasToken:e,onEditProvider:n,onDeleteProvider:r,ollamaBaseUrl:s,onEditOllama:i}){return f.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[t.map(a=>{const l=e(a.id);return f.jsx(pTe,{config:a,isConfigured:l,onEdit:n,onDelete:r},a.id)}),f.jsx(mTe,{baseUrl:s,onEdit:i})]})}function vTe({open:t,onOpenChange:e,provider:n,value:r,onValueChange:s,onSave:i,onCancel:a}){const l=Qr();return f.jsx(ua,{open:t,onOpenChange:e,children:f.jsxs(da,{className:"max-w-md",children:[f.jsx(fa,{children:f.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n&&f.jsx("div",{className:"w-12 h-12 rounded-lg bg-white p-2 border",children:f.jsx("img",{src:n.logo,alt:n.logoAlt,className:"w-full h-full object-contain"})}),f.jsxs("div",{children:[f.jsxs(ha,{className:"text-left",children:["Configure ",n?.name]}),f.jsx(nh,{className:"text-left",children:n?.description})]})]})}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{htmlFor:"api-key",className:"text-sm font-medium",children:"API Key"}),f.jsx(Dn,{id:"api-key",type:"password",value:r,onChange:u=>s(u.target.value),placeholder:n?.placeholder,className:"mt-1"})]}),f.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-lg",children:[f.jsx(tN,{className:"w-4 h-4 text-blue-600"}),f.jsxs("span",{className:"text-sm text-blue-600",children:["Need an API key?"," ",f.jsx("button",{onClick:()=>n&&window.open(n.getApiKeyUrl,"_blank"),className:"underline hover:no-underline",children:"Get one here"})]})]})]}),f.jsxs(S0,{children:[f.jsx(Pe,{variant:"outline",onClick:a,children:"Cancel"}),f.jsx(Pe,{onClick:()=>{l.capture("save_api_key",{location:"provider_config_dialog",platform:on(),environment:void 0}),i()},disabled:!r.trim(),children:"Save API Key"})]})]})})}function yTe({open:t,onOpenChange:e,value:n,onValueChange:r,onSave:s,onCancel:i}){return f.jsx(ua,{open:t,onOpenChange:e,children:f.jsxs(da,{className:"max-w-md",children:[f.jsx(fa,{children:f.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[f.jsx("div",{className:"w-12 h-12 rounded-lg bg-white p-2 border",children:f.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"w-full h-full object-contain"})}),f.jsxs("div",{children:[f.jsx(ha,{className:"text-left pb-2",children:"Configure Ollama URL"}),f.jsx(nh,{className:"text-left",children:"Set the base URL for your Ollama instance"})]})]})}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{htmlFor:"ollama-url",className:"text-sm font-medium",children:"Base URL"}),f.jsx(Dn,{id:"ollama-url",type:"url",value:n,onChange:a=>r(a.target.value),placeholder:"http://localhost:11434/api",className:"mt-1"})]}),f.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-lg",children:[f.jsx(tN,{className:"w-4 h-4 text-blue-600"}),f.jsxs("span",{className:"text-sm text-blue-600",children:["Need help?"," ",f.jsx("button",{onClick:()=>window.open("https://ollama.ai/download","_blank"),className:"underline hover:no-underline",children:"Download Ollama"})]})]})]}),f.jsxs(S0,{children:[f.jsx(Pe,{variant:"outline",onClick:i,children:"Cancel"}),f.jsx(Pe,{onClick:s,disabled:!n.trim(),children:"Save URL"})]})]})})}function xTe({...t}){return f.jsx(IJ,{"data-slot":"alert-dialog",...t})}function bTe({...t}){return f.jsx(DJ,{"data-slot":"alert-dialog-trigger",...t})}function _Te({...t}){return f.jsx(LJ,{"data-slot":"alert-dialog-portal",...t})}function wTe({className:t,...e}){return f.jsx($J,{"data-slot":"alert-dialog-overlay",className:Oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function STe({className:t,...e}){return f.jsxs(_Te,{children:[f.jsx(wTe,{}),f.jsx(zJ,{"data-slot":"alert-dialog-content",className:Oe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...e})]})}function ETe({className:t,...e}){return f.jsx("div",{"data-slot":"alert-dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",t),...e})}function kTe({className:t,...e}){return f.jsx("div",{"data-slot":"alert-dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...e})}function TTe({className:t,...e}){return f.jsx(BJ,{"data-slot":"alert-dialog-title",className:Oe("text-lg font-semibold",t),...e})}function CTe({className:t,...e}){return f.jsx(qJ,{"data-slot":"alert-dialog-description",className:Oe("text-muted-foreground text-sm",t),...e})}function ATe({className:t,...e}){return f.jsx(FJ,{className:Oe(eN(),t),...e})}function NTe({className:t,...e}){return f.jsx(UJ,{className:Oe(eN({variant:"outline"}),t),...e})}function bn(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function tc(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}const T7=6048e5,RTe=864e5,C7=6e4,A7=36e5,ky=43200,e$=1440;let jTe={};function Rg(){return jTe}function Zm(t,e){const n=Rg(),r=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=bn(t),i=s.getDay(),a=(i<r?7:0)+i-r;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function kb(t){return Zm(t,{weekStartsOn:1})}function N7(t){const e=bn(t),n=e.getFullYear(),r=tc(t,0);r.setFullYear(n+1,0,4),r.setHours(0,0,0,0);const s=kb(r),i=tc(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const a=kb(i);return e.getTime()>=s.getTime()?n+1:e.getTime()>=a.getTime()?n:n-1}function t$(t){const e=bn(t);return e.setHours(0,0,0,0),e}function Tb(t){const e=bn(t),n=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return n.setUTCFullYear(e.getFullYear()),+t-+n}function MTe(t,e){const n=t$(t),r=t$(e),s=+n-Tb(n),i=+r-Tb(r);return Math.round((s-i)/RTe)}function OTe(t){const e=N7(t),n=tc(t,0);return n.setFullYear(e,0,4),n.setHours(0,0,0,0),kb(n)}function lx(t,e){const n=bn(t),r=bn(e),s=n.getTime()-r.getTime();return s<0?-1:s>0?1:s}function PTe(t){return tc(t,Date.now())}function ITe(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function DTe(t){if(!ITe(t)&&typeof t!="number")return!1;const e=bn(t);return!isNaN(Number(e))}function LTe(t,e){const n=bn(t),r=bn(e),s=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return s*12+i}function $Te(t){return e=>{const r=(t?Math[t]:Math.trunc)(e);return r===0?0:r}}function zTe(t,e){return+bn(t)-+bn(e)}function FTe(t){const e=bn(t);return e.setHours(23,59,59,999),e}function UTe(t){const e=bn(t),n=e.getMonth();return e.setFullYear(e.getFullYear(),n+1,0),e.setHours(23,59,59,999),e}function BTe(t){const e=bn(t);return+FTe(e)==+UTe(e)}function qTe(t,e){const n=bn(t),r=bn(e),s=lx(n,r),i=Math.abs(LTe(n,r));let a;if(i<1)a=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-s*i);let l=lx(n,r)===-s;BTe(bn(t))&&i===1&&lx(t,r)===1&&(l=!1),a=s*(i-Number(l))}return a===0?0:a}function VTe(t,e,n){const r=zTe(t,e)/1e3;return $Te(n?.roundingMethod)(r)}function HTe(t){const e=bn(t),n=tc(t,0);return n.setFullYear(e.getFullYear(),0,1),n.setHours(0,0,0,0),n}const GTe={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},WTe=(t,e,n)=>{let r;const s=GTe[t];return typeof s=="string"?r=s:e===1?r=s.one:r=s.other.replace("{{count}}",e.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function q1(t){return(e={})=>{const n=e.width?String(e.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const YTe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},KTe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},XTe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},QTe={date:q1({formats:YTe,defaultWidth:"full"}),time:q1({formats:KTe,defaultWidth:"full"}),dateTime:q1({formats:XTe,defaultWidth:"full"})},JTe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ZTe=(t,e,n,r)=>JTe[t];function Cp(t){return(e,n)=>{const r=n?.context?String(n.context):"standalone";let s;if(r==="formatting"&&t.formattingValues){const a=t.defaultFormattingWidth||t.defaultWidth,l=n?.width?String(n.width):a;s=t.formattingValues[l]||t.formattingValues[a]}else{const a=t.defaultWidth,l=n?.width?String(n.width):t.defaultWidth;s=t.values[l]||t.values[a]}const i=t.argumentCallback?t.argumentCallback(e):e;return s[i]}}const eCe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},tCe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},nCe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},rCe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},sCe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},iCe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},aCe=(t,e)=>{const n=Number(t),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},oCe={ordinalNumber:aCe,era:Cp({values:eCe,defaultWidth:"wide"}),quarter:Cp({values:tCe,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Cp({values:nCe,defaultWidth:"wide"}),day:Cp({values:rCe,defaultWidth:"wide"}),dayPeriod:Cp({values:sCe,defaultWidth:"wide",formattingValues:iCe,defaultFormattingWidth:"wide"})};function Ap(t){return(e,n={})=>{const r=n.width,s=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],i=e.match(s);if(!i)return null;const a=i[0],l=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],u=Array.isArray(l)?cCe(l,h=>h.test(a)):lCe(l,h=>h.test(a));let d;d=t.valueCallback?t.valueCallback(u):u,d=n.valueCallback?n.valueCallback(d):d;const p=e.slice(a.length);return{value:d,rest:p}}}function lCe(t,e){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return n}function cCe(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n}function uCe(t){return(e,n={})=>{const r=e.match(t.matchPattern);if(!r)return null;const s=r[0],i=e.match(t.parsePattern);if(!i)return null;let a=t.valueCallback?t.valueCallback(i[0]):i[0];a=n.valueCallback?n.valueCallback(a):a;const l=e.slice(s.length);return{value:a,rest:l}}}const dCe=/^(\d+)(th|st|nd|rd)?/i,fCe=/\d+/i,hCe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},pCe={any:[/^b/i,/^(a|c)/i]},mCe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},gCe={any:[/1/i,/2/i,/3/i,/4/i]},vCe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},yCe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},xCe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},bCe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},_Ce={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},wCe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},SCe={ordinalNumber:uCe({matchPattern:dCe,parsePattern:fCe,valueCallback:t=>parseInt(t,10)}),era:Ap({matchPatterns:hCe,defaultMatchWidth:"wide",parsePatterns:pCe,defaultParseWidth:"any"}),quarter:Ap({matchPatterns:mCe,defaultMatchWidth:"wide",parsePatterns:gCe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Ap({matchPatterns:vCe,defaultMatchWidth:"wide",parsePatterns:yCe,defaultParseWidth:"any"}),day:Ap({matchPatterns:xCe,defaultMatchWidth:"wide",parsePatterns:bCe,defaultParseWidth:"any"}),dayPeriod:Ap({matchPatterns:_Ce,defaultMatchWidth:"any",parsePatterns:wCe,defaultParseWidth:"any"})},R7={code:"en-US",formatDistance:WTe,formatLong:QTe,formatRelative:ZTe,localize:oCe,match:SCe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ECe(t){const e=bn(t);return MTe(e,HTe(e))+1}function kCe(t){const e=bn(t),n=+kb(e)-+OTe(e);return Math.round(n/T7)+1}function j7(t,e){const n=bn(t),r=n.getFullYear(),s=Rg(),i=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,a=tc(t,0);a.setFullYear(r+1,0,i),a.setHours(0,0,0,0);const l=Zm(a,e),u=tc(t,0);u.setFullYear(r,0,i),u.setHours(0,0,0,0);const d=Zm(u,e);return n.getTime()>=l.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function TCe(t,e){const n=Rg(),r=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=j7(t,e),i=tc(t,0);return i.setFullYear(s,0,r),i.setHours(0,0,0,0),Zm(i,e)}function CCe(t,e){const n=bn(t),r=+Zm(n,e)-+TCe(n,e);return Math.round(r/T7)+1}function dn(t,e){const n=t<0?"-":"",r=Math.abs(t).toString().padStart(e,"0");return n+r}const Cl={y(t,e){const n=t.getFullYear(),r=n>0?n:1-n;return dn(e==="yy"?r%100:r,e.length)},M(t,e){const n=t.getMonth();return e==="M"?String(n+1):dn(n+1,2)},d(t,e){return dn(t.getDate(),e.length)},a(t,e){const n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(t,e){return dn(t.getHours()%12||12,e.length)},H(t,e){return dn(t.getHours(),e.length)},m(t,e){return dn(t.getMinutes(),e.length)},s(t,e){return dn(t.getSeconds(),e.length)},S(t,e){const n=e.length,r=t.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return dn(s,e.length)}},jd={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},n$={G:function(t,e,n){const r=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(t,e,n){if(e==="yo"){const r=t.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return Cl.y(t,e)},Y:function(t,e,n,r){const s=j7(t,r),i=s>0?s:1-s;if(e==="YY"){const a=i%100;return dn(a,2)}return e==="Yo"?n.ordinalNumber(i,{unit:"year"}):dn(i,e.length)},R:function(t,e){const n=N7(t);return dn(n,e.length)},u:function(t,e){const n=t.getFullYear();return dn(n,e.length)},Q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return dn(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return dn(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(t,e,n){const r=t.getMonth();switch(e){case"M":case"MM":return Cl.M(t,e);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(t,e,n){const r=t.getMonth();switch(e){case"L":return String(r+1);case"LL":return dn(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(t,e,n,r){const s=CCe(t,r);return e==="wo"?n.ordinalNumber(s,{unit:"week"}):dn(s,e.length)},I:function(t,e,n){const r=kCe(t);return e==="Io"?n.ordinalNumber(r,{unit:"week"}):dn(r,e.length)},d:function(t,e,n){return e==="do"?n.ordinalNumber(t.getDate(),{unit:"date"}):Cl.d(t,e)},D:function(t,e,n){const r=ECe(t);return e==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):dn(r,e.length)},E:function(t,e,n){const r=t.getDay();switch(e){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(t,e,n,r){const s=t.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return dn(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(t,e,n,r){const s=t.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return dn(i,e.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(t,e,n){const r=t.getDay(),s=r===0?7:r;switch(e){case"i":return String(s);case"ii":return dn(s,e.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(t,e,n){const s=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(t,e,n){const r=t.getHours();let s;switch(r===12?s=jd.noon:r===0?s=jd.midnight:s=r/12>=1?"pm":"am",e){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(t,e,n){const r=t.getHours();let s;switch(r>=17?s=jd.evening:r>=12?s=jd.afternoon:r>=4?s=jd.morning:s=jd.night,e){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(t,e,n){if(e==="ho"){let r=t.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Cl.h(t,e)},H:function(t,e,n){return e==="Ho"?n.ordinalNumber(t.getHours(),{unit:"hour"}):Cl.H(t,e)},K:function(t,e,n){const r=t.getHours()%12;return e==="Ko"?n.ordinalNumber(r,{unit:"hour"}):dn(r,e.length)},k:function(t,e,n){let r=t.getHours();return r===0&&(r=24),e==="ko"?n.ordinalNumber(r,{unit:"hour"}):dn(r,e.length)},m:function(t,e,n){return e==="mo"?n.ordinalNumber(t.getMinutes(),{unit:"minute"}):Cl.m(t,e)},s:function(t,e,n){return e==="so"?n.ordinalNumber(t.getSeconds(),{unit:"second"}):Cl.s(t,e)},S:function(t,e){return Cl.S(t,e)},X:function(t,e,n){const r=t.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return s$(r);case"XXXX":case"XX":return Yc(r);case"XXXXX":case"XXX":default:return Yc(r,":")}},x:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"x":return s$(r);case"xxxx":case"xx":return Yc(r);case"xxxxx":case"xxx":default:return Yc(r,":")}},O:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+r$(r,":");case"OOOO":default:return"GMT"+Yc(r,":")}},z:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+r$(r,":");case"zzzz":default:return"GMT"+Yc(r,":")}},t:function(t,e,n){const r=Math.trunc(t.getTime()/1e3);return dn(r,e.length)},T:function(t,e,n){const r=t.getTime();return dn(r,e.length)}};function r$(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=Math.trunc(r/60),i=r%60;return i===0?n+String(s):n+String(s)+e+dn(i,2)}function s$(t,e){return t%60===0?(t>0?"-":"+")+dn(Math.abs(t)/60,2):Yc(t,e)}function Yc(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=dn(Math.trunc(r/60),2),i=dn(r%60,2);return n+s+e+i}const i$=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},M7=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},ACe=(t,e)=>{const n=t.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return i$(t,e);let i;switch(r){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",i$(r,e)).replace("{{time}}",M7(s,e))},NCe={p:M7,P:ACe},RCe=/^D+$/,jCe=/^Y+$/,MCe=["D","DD","YY","YYYY"];function OCe(t){return RCe.test(t)}function PCe(t){return jCe.test(t)}function ICe(t,e,n){const r=DCe(t,e,n);if(console.warn(r),MCe.includes(t))throw new RangeError(r)}function DCe(t,e,n){const r=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const LCe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$Ce=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,zCe=/^'([^]*?)'?$/,FCe=/''/g,UCe=/[a-zA-Z]/;function O7(t,e,n){const r=Rg(),s=r.locale??R7,i=r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,a=r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=bn(t);if(!DTe(l))throw new RangeError("Invalid time value");let u=e.match($Ce).map(p=>{const h=p[0];if(h==="p"||h==="P"){const g=NCe[h];return g(p,s.formatLong)}return p}).join("").match(LCe).map(p=>{if(p==="''")return{isToken:!1,value:"'"};const h=p[0];if(h==="'")return{isToken:!1,value:BCe(p)};if(n$[h])return{isToken:!0,value:p};if(h.match(UCe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:p}});s.localize.preprocessor&&(u=s.localize.preprocessor(l,u));const d={firstWeekContainsDate:i,weekStartsOn:a,locale:s};return u.map(p=>{if(!p.isToken)return p.value;const h=p.value;(PCe(h)||OCe(h))&&ICe(h,e,String(t));const g=n$[h[0]];return g(l,h,s.localize,d)}).join("")}function BCe(t){const e=t.match(zCe);return e?e[1].replace(FCe,"'"):t}function qCe(t,e,n){const r=Rg(),s=n?.locale??r.locale??R7,i=2520,a=lx(t,e);if(isNaN(a))throw new RangeError("Invalid time value");const l=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:a});let u,d;a>0?(u=bn(e),d=bn(t)):(u=bn(t),d=bn(e));const p=VTe(d,u),h=(Tb(d)-Tb(u))/1e3,g=Math.round((p-h)/60);let v;if(g<2)return n?.includeSeconds?p<5?s.formatDistance("lessThanXSeconds",5,l):p<10?s.formatDistance("lessThanXSeconds",10,l):p<20?s.formatDistance("lessThanXSeconds",20,l):p<40?s.formatDistance("halfAMinute",0,l):p<60?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",1,l):g===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",g,l);if(g<45)return s.formatDistance("xMinutes",g,l);if(g<90)return s.formatDistance("aboutXHours",1,l);if(g<e$){const x=Math.round(g/60);return s.formatDistance("aboutXHours",x,l)}else{if(g<i)return s.formatDistance("xDays",1,l);if(g<ky){const x=Math.round(g/e$);return s.formatDistance("xDays",x,l)}else if(g<ky*2)return v=Math.round(g/ky),s.formatDistance("aboutXMonths",v,l)}if(v=qTe(d,u),v<12){const x=Math.round(g/ky);return s.formatDistance("xMonths",x,l)}else{const x=v%12,b=Math.trunc(v/12);return x<3?s.formatDistance("aboutXYears",b,l):x<9?s.formatDistance("overXYears",b,l):s.formatDistance("almostXYears",b+1,l)}}function VCe(t,e){return qCe(t,PTe(t),e)}function HCe(t,e){const r=KCe(t);let s;if(r.date){const u=XCe(r.date,2);s=QCe(u.restDateString,u.year)}if(!s||isNaN(s.getTime()))return new Date(NaN);const i=s.getTime();let a=0,l;if(r.time&&(a=JCe(r.time),isNaN(a)))return new Date(NaN);if(r.timezone){if(l=ZCe(r.timezone),isNaN(l))return new Date(NaN)}else{const u=new Date(i+a),d=new Date(0);return d.setFullYear(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),d.setHours(u.getUTCHours(),u.getUTCMinutes(),u.getUTCSeconds(),u.getUTCMilliseconds()),d}return new Date(i+a+l)}const Ty={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},GCe=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,WCe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,YCe=/^([+-])(\d{2})(?::?(\d{2}))?$/;function KCe(t){const e={},n=t.split(Ty.dateTimeDelimiter);let r;if(n.length>2)return e;if(/:/.test(n[0])?r=n[0]:(e.date=n[0],r=n[1],Ty.timeZoneDelimiter.test(e.date)&&(e.date=t.split(Ty.timeZoneDelimiter)[0],r=t.substr(e.date.length,t.length))),r){const s=Ty.timezone.exec(r);s?(e.time=r.replace(s[1],""),e.timezone=s[1]):e.time=r}return e}function XCe(t,e){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),r=t.match(n);if(!r)return{year:NaN,restDateString:""};const s=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?s:i*100,restDateString:t.slice((r[1]||r[2]).length)}}function QCe(t,e){if(e===null)return new Date(NaN);const n=t.match(GCe);if(!n)return new Date(NaN);const r=!!n[4],s=Np(n[1]),i=Np(n[2])-1,a=Np(n[3]),l=Np(n[4]),u=Np(n[5])-1;if(r)return sAe(e,l,u)?eAe(e,l,u):new Date(NaN);{const d=new Date(0);return!nAe(e,i,a)||!rAe(e,s)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(s,a)),d)}}function Np(t){return t?parseInt(t):1}function JCe(t){const e=t.match(WCe);if(!e)return NaN;const n=V1(e[1]),r=V1(e[2]),s=V1(e[3]);return iAe(n,r,s)?n*A7+r*C7+s*1e3:NaN}function V1(t){return t&&parseFloat(t.replace(",","."))||0}function ZCe(t){if(t==="Z")return 0;const e=t.match(YCe);if(!e)return 0;const n=e[1]==="+"?-1:1,r=parseInt(e[2]),s=e[3]&&parseInt(e[3])||0;return aAe(r,s)?n*(r*A7+s*C7):NaN}function eAe(t,e,n){const r=new Date(0);r.setUTCFullYear(t,0,4);const s=r.getUTCDay()||7,i=(e-1)*7+n+1-s;return r.setUTCDate(r.getUTCDate()+i),r}const tAe=[31,null,31,30,31,30,31,31,30,31,30,31];function P7(t){return t%400===0||t%4===0&&t%100!==0}function nAe(t,e,n){return e>=0&&e<=11&&n>=1&&n<=(tAe[e]||(P7(t)?29:28))}function rAe(t,e){return e>=1&&e<=(P7(t)?366:365)}function sAe(t,e,n){return e>=1&&e<=53&&n>=0&&n<=6}function iAe(t,e,n){return t===24?e===0&&n===0:n>=0&&n<60&&e>=0&&e<60&&t>=0&&t<25}function aAe(t,e){return e>=0&&e<=59}function a$({value:t,isCopied:e,onCopy:n,copyLabel:r,tooltip:s="Copy to clipboard"}){return f.jsxs("div",{className:"relative w-full",children:[f.jsx(Dn,{readOnly:!0,value:t,className:"h-12 w-full rounded-lg border border-border/40 bg-background/50 font-mono text-sm tracking-wide text-foreground pr-16 shadow-sm focus-visible:border-primary focus-visible:ring-1 focus-visible:ring-primary/20",style:{fontFamily:'ui-monospace, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'}}),f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",variant:"ghost",onClick:n,className:"absolute right-3 top-3 h-6 w-6 p-0 rounded-md border-0 bg-transparent text-foreground/60 hover:text-foreground hover:bg-foreground/10 transition-all duration-200",children:e?f.jsx(Ri,{className:"h-4 w-4"}):f.jsx(zo,{className:"h-4 w-4"})})}),f.jsx(La,{side:"bottom",children:s})]})]})}function oAe(){const[t,e]=w.useState(null),[n,r]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(!1),[u,d]=w.useState(!1),{isAuthenticated:p,isLoading:h}=pa(),{signIn:g}=Fi(),v=Qr(),x=Eb("apiKeys:list"),b=b7("apiKeys:regenerateAndGet"),E=async()=>{if(t)try{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),2e3)}catch(R){console.error("Clipboard error",R)}},S=async()=>{if(!p)return!1;try{r(!0),i(!1);const R=await b();return e(R.apiKey),d(!0),!0}catch(R){return console.error("Failed to generate key",R),!1}finally{r(!1)}};if(h)return f.jsx("div",{className:"rounded-md border p-3 text-sm text-muted-foreground",children:"Checking authentication…"});if(!p)return f.jsxs("div",{className:"space-y-3 rounded-md border p-4",children:[f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("h3",{className:"text-lg font-semibold",children:"MCPJam API Key"})}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Sign in to view and manage your API key."}),f.jsx(Pe,{type:"button",onClick:()=>{v.capture("login_button_clicked",{location:"account_api_key_section",platform:on(),environment:void 0}),g()},size:"sm",children:"Sign in"})]});const k=x&&x.length>0?x[0]:null,T=(R,j="Never")=>{if(!R)return j;const A=new Date(R),N=VCe(A,{addSuffix:!0});return`${O7(A,"PP p")} · ${N}`};return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("h3",{className:"text-lg font-semibold",children:"MCPJam API Key"})}),x===void 0?f.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading API key status…"}):t?f.jsxs("div",{className:"space-y-4",children:[f.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Copy and save this key now. You won't be able to view it again later."}),f.jsx(a$,{value:t,isCopied:s,onCopy:E,copyLabel:"Copy key"})]}):(x?.length??0)===0?f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{type:"button",onClick:()=>{S()},disabled:n,children:n?"Generating…":"Generate API key"})}):f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs(xTe,{open:a,onOpenChange:l,children:[f.jsx(bTe,{asChild:!0,children:f.jsxs(Pe,{type:"button",variant:"outline",disabled:n,className:"inline-flex items-center gap-2.5 rounded-lg border border-border/50 bg-background px-4 py-2.5 text-sm font-medium text-foreground/80 hover:border-border hover:bg-background/80 hover:text-foreground transition-all duration-200",children:[f.jsx(or,{className:`h-4 w-4 ${n?"animate-spin":""} text-foreground/60`}),f.jsx("span",{children:n?"Regenerating…":"Regenerate"})]})}),f.jsxs(STe,{children:[f.jsxs(ETe,{children:[f.jsx(TTe,{className:"text-lg font-semibold",children:"Confirm"}),f.jsx(CTe,{className:"text-sm text-muted-foreground leading-relaxed",children:"Regenerating an API key will replace your previous API key."})]}),f.jsxs(kTe,{className:"gap-3",children:[f.jsx(NTe,{disabled:n,className:"font-medium",children:"Cancel"}),f.jsx(ATe,{onClick:async R=>{R.preventDefault(),await S()&&l(!1)},disabled:n,className:"font-medium",children:n?"Regenerating…":"Regenerate"})]})]})]})}),k?f.jsx("div",{className:"rounded-lg border border-border/30 bg-background/50 p-4",children:f.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[f.jsxs("div",{className:"flex flex-col gap-0.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground/50 uppercase tracking-wide",children:"Created"}),f.jsx("span",{className:"text-xs text-foreground/70",children:T(k.createdAt)})]}),f.jsxs("div",{className:"flex flex-col gap-0.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground/50 uppercase tracking-wide",children:"Last Used"}),f.jsx("span",{className:"text-xs text-foreground/70",children:T(k.lastUsedAt,"Never used")})]})]})}):null]}),f.jsx(ua,{open:!!t&&u,onOpenChange:R=>{R||i(!1),d(R)},children:f.jsxs(da,{children:[f.jsxs(fa,{children:[f.jsx(ha,{children:"API Key"}),f.jsx(nh,{children:"Copy and store this key securely. You will not be able to view it again."})]}),f.jsx(a$,{value:t??"",isCopied:s,onCopy:E,copyLabel:"Copy"})]})})]})}function lAe(){const{tokens:t,setToken:e,clearToken:n,hasToken:r,getOllamaBaseUrl:s,setOllamaBaseUrl:i}=lR(),[a,l]=w.useState(""),[u,d]=w.useState(!1),[p,h]=w.useState(null),[g,v]=w.useState(!1),[x,b]=w.useState(""),E=[{id:"openai",name:"OpenAI",logo:"/openai_logo.png",logoAlt:"OpenAI",description:"GPT-4, GPT-4o, GPT-4o-mini, GPT-4.1, GPT-5, etc.",placeholder:"sk-...",getApiKeyUrl:"https://platform.openai.com/api-keys"},{id:"anthropic",name:"Anthropic",logo:"/claude_logo.png",logoAlt:"Claude",description:"Claude 3.5, Claude 3.7, Claude Opus 4, etc.",placeholder:"sk-ant-...",getApiKeyUrl:"https://console.anthropic.com/"},{id:"deepseek",name:"DeepSeek",logo:"/deepseek_logo.svg",logoAlt:"DeepSeek",description:"DeepSeek Chat, DeepSeek Reasoner, etc.",placeholder:"sk-...",getApiKeyUrl:"https://platform.deepseek.com/api_keys"},{id:"google",name:"Google AI",logo:"/google_logo.png",logoAlt:"Google AI",description:"Gemini 2.5, Gemini 2.5 Flash, Gemini 2.5 Flash Lite",placeholder:"AI...",getApiKeyUrl:"https://aistudio.google.com/app/apikey"}],S=M=>{const I=E.find(O=>O.id===M);I&&(h(I),l(t[M]||""),d(!0))},k=()=>{p&&(e(p.id,a),d(!1),h(null),l(""))},T=()=>{d(!1),h(null),l("")},R=M=>{n(M)},j=()=>{b(s()),v(!0)},A=()=>{i(x),v(!1),b("")},N=()=>{v(!1),b("")};return f.jsxs("div",{className:"container mx-auto p-6 max-w-6xl space-y-8",children:[f.jsx("div",{className:"flex items-center gap-3 mb-6",children:f.jsx("h1",{className:"text-2xl font-bold",children:"Settings"})}),f.jsx(oAe,{}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{children:f.jsx("h3",{className:"text-lg font-semibold",children:"LLM Provider API Keys"})}),f.jsx(gTe,{providerConfigs:E,hasToken:M=>r(M),onEditProvider:S,onDeleteProvider:R,ollamaBaseUrl:s(),onEditOllama:j})]}),f.jsx(vTe,{open:u,onOpenChange:d,provider:p,value:a,onValueChange:l,onSave:k,onCancel:T}),f.jsx(yTe,{open:g,onOpenChange:v,value:x,onValueChange:b,onSave:A,onCancel:N})]})}const cAe=(t,e="HH:mm:ss.SSS")=>{const n=typeof t=="string"?HCe(t):t;return O7(n,e)},uAe={error:"bg-red-500/10 text-red-700 border-red-200 dark:text-red-400 dark:border-red-800",warn:"bg-yellow-500/10 text-yellow-700 border-yellow-200 dark:text-yellow-400 dark:border-yellow-800",info:"bg-blue-500/10 text-blue-700 border-blue-200 dark:text-blue-400 dark:border-blue-800",debug:"bg-purple-500/10 text-purple-700 border-purple-200 dark:text-purple-400 dark:border-purple-800",trace:"bg-gray-500/10 text-gray-700 border-gray-200 dark:text-gray-400 dark:border-gray-800"};function I7({level:t}){return f.jsx(xr,{variant:"outline",className:Oe("font-mono",uAe[t]),children:t.toUpperCase()})}function dAe({entry:t,isExpanded:e,onToggleExpand:n}){const r=t.data!==void 0||t.error!==void 0;return f.jsxs("div",{className:"border rounded-lg font-mono",children:[f.jsx("div",{className:`p-3 cursor-pointer hover:bg-muted/50 ${r?"":"cursor-default"}`,onClick:r?n:void 0,children:f.jsxs("div",{className:"flex items-start gap-3",children:[r&&f.jsx("div",{className:"mt-0.5",children:e?f.jsx(cc,{className:"h-4 w-4 text-muted-foreground"}):f.jsx(la,{className:"h-4 w-4 text-muted-foreground"})}),f.jsx("div",{className:"flex-1 min-w-0",children:f.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:`[${cAe(t.timestamp)}]`}),f.jsx(I7,{level:t.level}),f.jsx(xr,{variant:"secondary",children:t.context}),f.jsx("span",{className:"flex-1 break-words",children:t.message})]})})]})}),e&&r&&f.jsxs("div",{className:"border-t bg-muted/20 p-3 space-y-3",children:[t.data!==void 0&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:"DATA:"}),f.jsx("div",{className:"text-xs bg-background border rounded overflow-auto max-h-60",children:f.jsx(Mo,{src:t.data,dark:!0,theme:"atom",enableClipboard:!0,displaySize:!1,collapseStringsAfterLength:100,style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', monospace",backgroundColor:"hsl(var(--background))",padding:"0",borderRadius:"0",border:"none"}})})]}),t.error&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:"ERROR:"}),f.jsxs("pre",{className:"text-xs bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded p-2 overflow-auto max-h-40 text-red-700 dark:text-red-400",children:[t.error.message,t.error.stack&&`
1823
+ Called by client`}function NC(t,e){return e.data=t.errorData,e}function wb(t){const e=t.split(":");let n,r;return e.length===1?(n=e[0],r="default"):(n=e.slice(0,e.length-1).join(":"),r=e[e.length-1]),n.endsWith(".js")&&(n=n.slice(0,-3)),`${n}:${r}`}function uu(t,e){return JSON.stringify({udfPath:wb(t),args:ec(e)})}var I1e=Object.defineProperty,D1e=(t,e,n)=>e in t?I1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sa=(t,e,n)=>D1e(t,typeof e!="symbol"?e+"":e,n);class L1e{constructor(){Sa(this,"nextQueryId"),Sa(this,"querySetVersion"),Sa(this,"querySet"),Sa(this,"queryIdToToken"),Sa(this,"identityVersion"),Sa(this,"auth"),Sa(this,"outstandingQueriesOlderThanRestart"),Sa(this,"outstandingAuthOlderThanRestart"),Sa(this,"paused"),Sa(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,n,r,s){const i=wb(e),a=uu(i,n),l=this.querySet.get(a);if(l!==void 0)return l.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{const u=this.nextQueryId++,d={id:u,canonicalizedUdfPath:i,args:n,numSubscribers:1,journal:r,componentPath:s};this.querySet.set(a,d),this.queryIdToToken.set(u,a);const p=this.querySetVersion,h=this.querySetVersion+1,g={type:"Add",queryId:u,udfPath:i,args:[ec(n)],journal:r,componentPath:s};return this.paused?this.pendingQuerySetModifications.set(u,g):this.querySetVersion=h,{queryToken:a,modification:{type:"ModifyQuerySet",baseVersion:p,newVersion:h,modifications:[g]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(const n of e.modifications)switch(n.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);const r=n.journal;if(r!==void 0){const s=this.queryIdToToken.get(n.queryId);s!==void 0&&(this.querySet.get(s).journal=r)}break}case"QueryRemoved":{this.outstandingQueriesOlderThanRestart.delete(n.queryId);break}default:throw new Error(`Invalid modification ${n.type}`)}}queryId(e,n){const r=wb(e),s=uu(r,n),i=this.querySet.get(s);return i!==void 0?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};const n=this.identityVersion;return this.paused||(this.identityVersion=n+1),{type:"Authenticate",baseVersion:n,...this.auth}}setAdminAuth(e,n){const r={tokenType:"Admin",value:e,impersonating:n};this.auth=r;const s=this.identityVersion;return this.paused||(this.identityVersion=s+1),{type:"Authenticate",baseVersion:s,...r}}clearAuth(){this.auth=void 0,this.markAuthCompletion();const e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).canonicalizedUdfPath:null}queryArgs(e){const n=this.queryIdToToken.get(e);return n?this.querySet.get(n).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(e){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();const n=[];for(const i of this.querySet.values()){const a={type:"Add",queryId:i.id,udfPath:i.canonicalizedUdfPath,args:[ec(i.args)],journal:i.journal,componentPath:i.componentPath};n.push(a),e.has(i.id)||this.outstandingQueriesOlderThanRestart.add(i.id)}this.querySetVersion=1;const r={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:n};if(!this.auth)return this.identityVersion=0,[r,void 0];this.outstandingAuthOlderThanRestart=!0;const s={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[r,s]}pause(){this.paused=!0}resume(){const e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,n=this.auth!==void 0?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,n]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){const n=this.querySet.get(e);if(n.numSubscribers>1)return n.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(n.id),this.outstandingQueriesOlderThanRestart.delete(n.id);const r=this.querySetVersion,s=this.querySetVersion+1,i={type:"Remove",queryId:n.id};return this.paused?this.pendingQuerySetModifications.has(n.id)?this.pendingQuerySetModifications.delete(n.id):this.pendingQuerySetModifications.set(n.id,i):this.querySetVersion=s,{type:"ModifyQuerySet",baseVersion:r,newVersion:s,modifications:[i]}}}}var $1e=Object.defineProperty,z1e=(t,e,n)=>e in t?$1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,wy=(t,e,n)=>z1e(t,typeof e!="symbol"?e+"":e,n);class F1e{constructor(e,n){this.logger=e,this.markConnectionStateDirty=n,wy(this,"inflightRequests"),wy(this,"requestsOlderThanRestart"),wy(this,"inflightMutationsCount",0),wy(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,n){const r=new Promise(s=>{const i=n?"Requested":"NotSent";this.inflightRequests.set(e.requestId,{message:e,status:{status:i,requestedAt:new Date,onResult:s}}),e.type==="Mutation"?this.inflightMutationsCount++:e.type==="Action"&&this.inflightActionsCount++});return this.markConnectionStateDirty(),r}onResponse(e){const n=this.inflightRequests.get(e.requestId);if(n===void 0||n.status.status==="Completed")return null;const r=n.message.type==="Mutation"?"mutation":"action",s=n.message.udfPath;for(const u of e.logLines)_b(this.logger,"info",r,s,u);const i=n.status;let a,l;if(e.success)a={success:!0,logLines:e.logLines,value:If(e.result)},l=()=>i.onResult(a);else{const u=e.result,{errorData:d}=e;_b(this.logger,"error",r,s,u),a={success:!1,errorMessage:u,errorData:d!==void 0?If(d):void 0,logLines:e.logLines},l=()=>i.onResult(a)}return e.type==="ActionResponse"||!e.success?(l(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),n.message.type==="Action"?this.inflightActionsCount--:n.message.type==="Mutation"&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(n.status={status:"Completed",result:a,ts:e.ts,onResolve:l},null)}removeCompleted(e){const n=new Map;for(const[r,s]of this.inflightRequests.entries()){const i=s.status;i.status==="Completed"&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),n.set(r,i.result),s.message.type==="Mutation"?this.inflightMutationsCount--:s.message.type==="Action"&&this.inflightActionsCount--,this.inflightRequests.delete(r),this.requestsOlderThanRestart.delete(r))}return n.size>0&&this.markConnectionStateDirty(),n}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());const e=[];for(const[n,r]of this.inflightRequests){if(r.status.status==="NotSent"){r.status.status="Requested",e.push(r.message);continue}if(r.message.type==="Mutation")e.push(r.message);else if(r.message.type==="Action"){if(this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n),this.inflightActionsCount--,r.status.status==="Completed")throw new Error("Action should never be in 'Completed' state");r.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){const e=[];for(const[,n]of this.inflightRequests)if(n.status.status==="NotSent"){n.status.status="Requested",e.push(n.message);continue}return e}hasIncompleteRequests(){for(const e of this.inflightRequests.values())if(e.status.status==="Requested")return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(const n of this.inflightRequests.values())n.status.status!=="Completed"&&n.status.requestedAt.getTime()<e&&(e=n.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}const Qm=Symbol.for("functionName"),U1e=Symbol.for("toReferencePath");function B1e(t){return t[U1e]??null}function q1e(t){return t.startsWith("function://")}function V1e(t){let e;if(typeof t=="string")q1e(t)?e={functionHandle:t}:e={name:t};else if(t[Qm])e={name:t[Qm]};else{const n=B1e(t);if(!n)throw new Error(`${t} is not a functionReference`);e={reference:n}}return e}function Ls(t){const e=V1e(t);if(e.name===void 0)throw e.functionHandle!==void 0?new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${e.functionHandle}`):e.reference!==void 0?new Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${e.reference}`):new Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(e)}`);if(typeof t=="string")return t;const n=t[Qm];if(!n)throw new Error(`${t} is not a functionReference`);return n}function lj(t){return{[Qm]:t}}function g7(t=[]){const e={get(n,r){if(typeof r=="string"){const s=[...t,r];return g7(s)}else if(r===Qm){if(t.length<2){const a=["api",...t].join(".");throw new Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}const s=t.slice(0,-1).join("/"),i=t[t.length-1];return i==="default"?s:s+":"+i}else return r===Symbol.toStringTag?"FunctionReference":void 0}};return new Proxy({},e)}g7();var H1e=Object.defineProperty,G1e=(t,e,n)=>e in t?H1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sb=(t,e,n)=>G1e(t,typeof e!="symbol"?e+"":e,n);class Jm{constructor(e){Sb(this,"queryResults"),Sb(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...n){const r=Co(n[0]),s=Ls(e),i=this.queryResults.get(uu(s,r));if(i!==void 0)return Jm.queryValue(i.result)}getAllQueries(e){const n=[],r=Ls(e);for(const s of this.queryResults.values())s.udfPath===wb(r)&&n.push({args:s.args,value:Jm.queryValue(s.result)});return n}setQuery(e,n,r){const s=Co(n),i=Ls(e),a=uu(i,s);let l;r===void 0?l=void 0:l={success:!0,value:r,logLines:[]};const u={udfPath:i,args:s,result:l};this.queryResults.set(a,u),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0)return e.success?e.value:void 0}}class W1e{constructor(){Sb(this,"queryResults"),Sb(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,n){this.optimisticUpdates=this.optimisticUpdates.filter(a=>!n.has(a.mutationId));const r=this.queryResults;this.queryResults=new Map(e);const s=new Jm(this.queryResults);for(const a of this.optimisticUpdates)a.update(s);const i=[];for(const[a,l]of this.queryResults){const u=r.get(a);(u===void 0||u.result!==l.result)&&i.push(a)}return i}applyOptimisticUpdate(e,n){this.optimisticUpdates.push({update:e,mutationId:n});const r=new Jm(this.queryResults);return e(r),r.modifiedQueries}rawQueryResult(e){return this.queryResults.get(e)}queryResult(e){const n=this.queryResults.get(e);if(n===void 0)return;const r=n.result;if(r!==void 0){if(r.success)return r.value;throw r.errorData!==void 0?NC(r,new AC(Zd("query",n.udfPath,r))):new Error(Zd("query",n.udfPath,r))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}}var Y1e=Object.defineProperty,K1e=(t,e,n)=>e in t?Y1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$1=(t,e,n)=>K1e(t,typeof e!="symbol"?e+"":e,n);class Zs{constructor(e,n){$1(this,"low"),$1(this,"high"),$1(this,"__isUnsignedLong__"),this.low=e|0,this.high=n|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(e){return new Zs(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){const e=this.high,n=this.low;return[n&255,n>>>8&255,n>>>16&255,n>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?V4:e>=X1e?Q1e:new Zs(e%mm|0,e/mm|0)}toString(){return(BigInt(this.high)*BigInt(mm)+BigInt(this.low)).toString()}equals(e){return Zs.isLong(e)||(e=Zs.fromValue(e)),this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return Zs.isLong(e)||(e=Zs.fromValue(e)),this.equals(e)?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(e){return typeof e=="number"?Zs.fromNumber(e):new Zs(e.low,e.high)}}const V4=new Zs(0,0),H4=65536,mm=H4*H4,X1e=mm*mm,Q1e=new Zs(-1,-1);var J1e=Object.defineProperty,Z1e=(t,e,n)=>e in t?J1e(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Sy=(t,e,n)=>Z1e(t,typeof e!="symbol"?e+"":e,n);class G4{constructor(e,n){Sy(this,"version"),Sy(this,"remoteQuerySet"),Sy(this,"queryPath"),Sy(this,"logger"),this.version={querySet:0,ts:Zs.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=n}transition(e){const n=e.startVersion;if(this.version.querySet!==n.querySet||this.version.ts.notEquals(n.ts)||this.version.identity!==n.identity)throw new Error(`Invalid start version: ${n.ts.toString()}:${n.querySet}:${n.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(const r of e.modifications)switch(r.type){case"QueryUpdated":{const s=this.queryPath(r.queryId);if(s)for(const a of r.logLines)_b(this.logger,"info","query",s,a);const i=If(r.value??null);this.remoteQuerySet.set(r.queryId,{success:!0,value:i,logLines:r.logLines});break}case"QueryFailed":{const s=this.queryPath(r.queryId);if(s)for(const a of r.logLines)_b(this.logger,"info","query",s,a);const{errorData:i}=r;this.remoteQuerySet.set(r.queryId,{success:!1,errorMessage:r.errorMessage,errorData:i!==void 0?If(i):void 0,logLines:r.logLines});break}case"QueryRemoved":{this.remoteQuerySet.delete(r.queryId);break}default:throw new Error(`Invalid modification ${r.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function z1(t){const e=Km(t);return Zs.fromBytesLE(Array.from(e))}function eke(t){const e=new Uint8Array(t.toBytesLE());return Xm(e)}function W4(t){switch(t.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...t};case"MutationResponse":return t.success?{...t,ts:z1(t.ts)}:{...t};case"Transition":return{...t,startVersion:{...t.startVersion,ts:z1(t.startVersion.ts)},endVersion:{...t.endVersion,ts:z1(t.endVersion.ts)}}}}function tke(t){switch(t.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...t};case"Connect":return t.maxObservedTimestamp!==void 0?{...t,maxObservedTimestamp:eke(t.maxObservedTimestamp)}:{...t,maxObservedTimestamp:void 0}}}var nke=Object.defineProperty,rke=(t,e,n)=>e in t?nke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vr=(t,e,n)=>rke(t,typeof e!="symbol"?e+"":e,n);const ske=1e3,ike=1001,ake=1005,oke=4040;let ax;function ox(){return ax===void 0&&(ax=Date.now()),typeof performance>"u"||!performance.now?Date.now():Math.round(ax+performance.now())}function Y4(){return`t=${Math.round((ox()-ax)/100)/10}s`}const v7={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function lke(t){if(t===void 0)return"Unknown";for(const e of Object.keys(v7))if(t.startsWith(e))return e;return"Unknown"}class cke{constructor(e,n,r,s,i,a){this.markConnectionStateDirty=i,this.debug=a,Vr(this,"socket"),Vr(this,"connectionCount"),Vr(this,"_hasEverConnected",!1),Vr(this,"lastCloseReason"),Vr(this,"transitionChunkBuffer",null),Vr(this,"defaultInitialBackoff"),Vr(this,"maxBackoff"),Vr(this,"retries"),Vr(this,"serverInactivityThreshold"),Vr(this,"reconnectDueToServerInactivityTimeout"),Vr(this,"uri"),Vr(this,"onOpen"),Vr(this,"onResume"),Vr(this,"onMessage"),Vr(this,"webSocketConstructor"),Vr(this,"logger"),Vr(this,"onServerDisconnectError"),this.webSocketConstructor=r,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=n.onOpen,this.onResume=n.onResume,this.onMessage=n.onMessage,this.onServerDisconnectError=n.onServerDisconnectError,this.logger=s,this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,new Error("Invalid TransitionChunk");if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){const n=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,new Error(`TransitionChunk received out of order: expected part ${n}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){const n=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;const r=W4(JSON.parse(n));if(r.type!=="Transition")throw new Error(`Expected Transition, got ${r.type} after assembling chunks`);return r}return null}connect(){if(this.socket.state==="terminated")return;if(this.socket.state!=="disconnected"&&this.socket.state!=="stopped")throw new Error("Didn't start connection from disconnected state: "+this.socket.state);const e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),this.socket.state!=="connecting")throw new Error("onopen called with socket not in connecting state");this.setSocketState({state:"ready",ws:e,paused:this.socket.paused==="yes"?"uninitialized":"no"}),this.resetServerInactivityTimeout(),this.socket.paused==="no"&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ox()})),this.lastCloseReason!=="InitialConnect"&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",Y4(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",Y4())),this.connectionCount+=1,this.lastCloseReason=null},e.onerror=n=>{this.transitionChunkBuffer=null;const r=n.message;r&&this.logger.log(`WebSocket error message: ${r}`)},e.onmessage=n=>{this.resetServerInactivityTimeout();const r=n.data.length;let s=W4(JSON.parse(n.data));if(this._logVerbose(`received ws message with type ${s.type}`),s.type==="Ping")return;if(s.type==="TransitionChunk"){const a=this.assembleTransition(s);if(!a)return;s=a,this._logVerbose(`assembled full ws message of type ${s.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${s.type} while buffering TransitionChunks`)),s.type==="Transition"&&this.reportLargeTransition({messageLength:r,transition:s}),this.onMessage(s).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())},e.onclose=n=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=n.reason||`closed with code ${n.code}`),n.code!==ske&&n.code!==ike&&n.code!==ake&&n.code!==oke){let s=`WebSocket closed with code ${n.code}`;n.reason&&(s+=`: ${n.reason}`),this.logger.log(s),this.onServerDisconnectError&&n.reason&&this.onServerDisconnectError(s)}const r=lke(n.reason);this.scheduleReconnect(r)}}socketState(){return this.socket.state}sendMessage(e){const n={type:e.type,...e.type==="Authenticate"&&e.tokenType==="User"?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state==="ready"&&this.socket.paused==="no"){const r=tke(e),s=JSON.stringify(r);let i=!1;try{this.socket.ws.send(s),i=!0}catch(a){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${a}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(n)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(n)}`),!1}resetServerInactivityTimeout(){this.socket.state!=="terminated"&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.socket={state:"disconnected"};const n=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(n)}ms`),setTimeout(()=>this.connect(),n)}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":{this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return}default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{const e=this.socket.ws;return e.onmessage=n=>{this._logVerbose("Ignoring message received after close")},new Promise(n=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),n()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");const e=this.socket.ws;e.onmessage=r=>{this._logVerbose("Ignoring message received after close")};const n=new Promise(r=>{e.onclose=()=>{r()}});return e.close(),n}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{const e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,new Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{const e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":{this.socket={...this.socket,paused:"yes"};return}default:{this.socket;return}}}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":this.socket.paused==="uninitialized"?(this.socket={...this.socket,paused:"no"},this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ox()})):this.socket.paused==="yes"&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state==="ready",hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){const r=(e==="client"?100:e==="Unknown"?this.defaultInitialBackoff:v7[e].timeout)*Math.pow(2,this.retries);this.retries+=1;const s=Math.min(r,this.maxBackoff),i=s*(Math.random()-.5);return s+i}reportLargeTransition({transition:e,messageLength:n}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;const r=ox()-e.clientClockSkew-e.serverTs/1e6,s=`${Math.round(r)}ms`,i=`${Math.round(n/1e4)/100}MB`,a=n/(r/1e3),l=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${s} at ${l}`),n>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):r>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${s})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:r,messageLength:n}})}}function uke(){return dke()}function dke(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}class Xp extends Error{}Xp.prototype.name="InvalidTokenError";function fke(t){return decodeURIComponent(atob(t).replace(/(.)/g,(e,n)=>{let r=n.charCodeAt(0).toString(16).toUpperCase();return r.length<2&&(r="0"+r),"%"+r}))}function hke(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw new Error("base64 string is not of the correct length")}try{return fke(e)}catch{return atob(e)}}function y7(t,e){if(typeof t!="string")throw new Xp("Invalid token specified: must be a string");e||(e={});const n=e.header===!0?0:1,r=t.split(".")[n];if(typeof r!="string")throw new Xp(`Invalid token specified: missing part #${n+1}`);let s;try{s=hke(r)}catch(i){throw new Xp(`Invalid token specified: invalid base64 for part #${n+1} (${i.message})`)}try{return JSON.parse(s)}catch(i){throw new Xp(`Invalid token specified: invalid json for part #${n+1} (${i.message})`)}}var pke=Object.defineProperty,mke=(t,e,n)=>e in t?pke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_i=(t,e,n)=>mke(t,typeof e!="symbol"?e+"":e,n);const gke=20*24*60*60*1e3,K4=2;class vke{constructor(e,n,r){_i(this,"authState",{state:"noAuth"}),_i(this,"configVersion",0),_i(this,"syncState"),_i(this,"authenticate"),_i(this,"stopSocket"),_i(this,"tryRestartSocket"),_i(this,"pauseSocket"),_i(this,"resumeSocket"),_i(this,"clearAuth"),_i(this,"logger"),_i(this,"refreshTokenLeewaySeconds"),_i(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=n.authenticate,this.stopSocket=n.stopSocket,this.tryRestartSocket=n.tryRestartSocket,this.pauseSocket=n.pauseSocket,this.resumeSocket=n.resumeSocket,this.clearAuth=n.clearAuth,this.logger=r.logger,this.refreshTokenLeewaySeconds=r.refreshTokenLeewaySeconds}async setConfig(e,n){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();const r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});r.isFromOutdatedConfig||(r.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:{fetchToken:e,onAuthChange:n},hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:"initialRefetch",config:{fetchToken:e,onAuthChange:n}}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket())}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this.authState.state==="waitingForServerConfirmationOfCachedToken"){this._logVerbose("server confirmed auth token is valid"),this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this._logVerbose("server confirmed new auth token is valid"),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state==="waitingForServerConfirmationOfFreshToken"||this.authState.state==="waitingForServerConfirmationOfCachedToken")){this._logVerbose("ignoring non-auth token expired error");return}const{baseVersion:n}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(n+1)){this._logVerbose("ignoring auth error for previous auth attempt");return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state==="noAuth"||this.authState.state==="waitingForServerConfirmationOfFreshToken"&&this.tokenConfirmationAttempts>=K4){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!=="noAuth"&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}this.authState.state==="waitingForServerConfirmationOfFreshToken"&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${K4-this.tokenConfirmationAttempts} attempts remaining`)),await this.stopSocket();const n=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});n.isFromOutdatedConfig||(n.value&&this.syncState.isNewAuth(n.value)?(this.authenticate(n.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:n.value,hadAuth:this.authState.state==="notRefetching"||this.authState.state==="waitingForScheduledRefetch"})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state==="noAuth")return;this._logVerbose("refetching auth token");const e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e){if(this.authState.state==="noAuth")return;const n=this.decodeToken(e);if(!n){this.logger.error("Auth token is not a valid JWT, cannot refetch the token");return}const{iat:r,exp:s}=n;if(!r||!s){this.logger.error("Auth token does not have required fields, cannot refetch the token");return}const i=s-r;if(i<=2){this.logger.error("Auth token does not live long enough, cannot refetch the token");return}let a=Math.min(gke,(i-this.refreshTokenLeewaySeconds)*1e3);a<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${i}s`),a=0);const l=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},a);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:l,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${a}ms`)}async fetchTokenAndGuardAgainstRace(e,n){const r=++this.configVersion;this._logVerbose(`fetching token with config version ${r}`);const s=await e(n);return this.configVersion!==r?(this._logVerbose(`stale config version, expected ${r}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:s}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.setAuthState({state:"noAuth"})}setAuthState(e){const n=e.state==="waitingForServerConfirmationOfFreshToken"?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(n)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0;break}this.authState.state==="waitingForScheduledRefetch"&&(clearTimeout(this.authState.refetchTokenTimeoutId),this.syncState.markAuthCompletion()),this.authState=e}decodeToken(e){try{return y7(e)}catch(n){return this._logVerbose(`Error decoding token: ${n instanceof Error?n.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}const yke=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function xke(t,e){const n={sessionId:e};typeof performance>"u"||!performance.mark||performance.mark(t,{detail:n})}function bke(t){let e=t.name.slice(6);return e=e.charAt(0).toLowerCase()+e.slice(1),{name:e,startTime:t.startTime}}function _ke(t){if(typeof performance>"u"||!performance.getEntriesByName)return[];const e=[];for(const n of yke){const r=performance.getEntriesByName(n).filter(s=>s.entryType==="mark").filter(s=>s.detail.sessionId===t);e.push(...r)}return e.map(bke)}var wke=Object.defineProperty,Ske=(t,e,n)=>e in t?wke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,pr=(t,e,n)=>Ske(t,typeof e!="symbol"?e+"":e,n);class Eke{constructor(e,n,r){if(pr(this,"address"),pr(this,"state"),pr(this,"requestManager"),pr(this,"webSocketManager"),pr(this,"authenticationManager"),pr(this,"remoteQuerySet"),pr(this,"optimisticQueryResults"),pr(this,"_transitionHandlerCounter",0),pr(this,"_nextRequestId"),pr(this,"_onTransitionFns",new Map),pr(this,"_sessionId"),pr(this,"firstMessageReceived",!1),pr(this,"debug"),pr(this,"logger"),pr(this,"maxObservedTimestamp"),pr(this,"connectionStateSubscribers",new Map),pr(this,"nextConnectionStateSubscriberId",0),pr(this,"_lastPublishedConnectionState"),pr(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{const v=this.connectionState();if(JSON.stringify(v)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=v;for(const x of this.connectionStateSubscribers.values())x(v)}})}),pr(this,"mark",v=>{this.debug&&xke(v,this.sessionId)}),typeof e=="object")throw new Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");r?.skipConvexDeploymentUrlCheck!==!0&&x1e(e),r={...r};const s=r.authRefreshTokenLeewaySeconds??2;let i=r.webSocketConstructor;if(!i&&typeof WebSocket>"u")throw new Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");i=i||WebSocket,this.debug=r.reportDebugInfoToConvex??!1,this.address=e,this.logger=r.logger===!1?m7({verbose:r.verbose??!1}):r.logger!==!0&&r.logger?r.logger:p7({verbose:r.verbose??!1});const a=e.search("://");if(a===-1)throw new Error("Provided address was not an absolute URL.");const l=e.substring(a+3),u=e.substring(0,a);let d;if(u==="http")d="ws";else if(u==="https")d="wss";else throw new Error(`Unknown parent protocol ${u}`);const p=`${d}://${l}/api/${B4}/sync`;this.state=new L1e,this.remoteQuerySet=new G4(v=>this.state.queryPath(v),this.logger),this.requestManager=new F1e(this.logger,this.markConnectionStateDirty);const h=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new vke(this.state,{authenticate:v=>{const x=this.state.setAuth(v);return this.webSocketManager.sendMessage(x),x.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:h,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:s}),this.optimisticQueryResults=new W1e,this.addOnTransitionHandler(v=>{n(v.queries.map(x=>x.token))}),this._nextRequestId=0,this._sessionId=uke();const{unsavedChangesWarning:g}=r;if(typeof window>"u"||typeof window.addEventListener>"u"){if(g===!0)throw new Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else g!==!1&&window.addEventListener("beforeunload",v=>{if(this.requestManager.hasIncompleteRequests()){v.preventDefault();const x="Are you sure you want to leave? Your changes may not be saved.";return(v||window.event).returnValue=x,x}});this.webSocketManager=new cke(p,{onOpen:v=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...v,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp});const x=new Set(this.remoteQuerySet.remoteQueryResults().keys());this.remoteQuerySet=new G4(S=>this.state.queryPath(S),this.logger);const[b,E]=this.state.restart(x);E&&this.webSocketManager.sendMessage(E),this.webSocketManager.sendMessage(b);for(const S of this.requestManager.restart())this.webSocketManager.sendMessage(S)},onResume:()=>{const[v,x]=this.state.resume();x&&this.webSocketManager.sendMessage(x),v&&this.webSocketManager.sendMessage(v);for(const b of this.requestManager.resume())this.webSocketManager.sendMessage(b)},onMessage:v=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),v.type){case"Transition":{this.observedTimestamp(v.endVersion.ts),this.authenticationManager.onTransition(v),this.remoteQuerySet.transition(v),this.state.transition(v);const x=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(x);break}case"MutationResponse":{v.success&&this.observedTimestamp(v.ts);const x=this.requestManager.onResponse(v);x!==null&&this.notifyOnQueryResultChanges(new Map([[x.requestId,x.result]]));break}case"ActionResponse":{this.requestManager.onResponse(v);break}case"AuthError":{this.authenticationManager.onAuthError(v);break}case"FatalError":{const x=P1e(this.logger,v.error);throw this.webSocketManager.terminate(),x}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:r.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),r.expectAuth&&h()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()||this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){const n=this.remoteQuerySet.remoteQueryResults(),r=new Map;for(const[i,a]of n){const l=this.state.queryToken(i);if(l!==null){const u={result:a,udfPath:this.state.queryPath(i),args:this.state.queryArgs(i)};r.set(l,u)}}const s=this.optimisticQueryResults.ingestQueryResultsFromServer(r,new Set(e.keys()));this.handleTransition({queries:s.map(i=>{const a=this.optimisticQueryResults.rawQueryResult(i);return{token:i,modification:{kind:"Updated",result:a.result}}}),reflectedMutations:Array.from(e).map(([i,a])=>({requestId:i,result:a})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(const n of this._onTransitionFns.values())n(e)}addOnTransitionHandler(e){const n=this._transitionHandlerCounter++;return this._onTransitionFns.set(n,e),()=>this._onTransitionFns.delete(n)}getCurrentAuthClaims(){const e=this.state.getAuth();let n={};if(e&&e.tokenType==="User")try{n=e?y7(e.value):{}}catch{n={}}else return;return{token:e.value,decoded:n}}setAuth(e,n){this.authenticationManager.setConfig(e,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,n){const r=this.state.setAdminAuth(e,n);this.webSocketManager.sendMessage(r)}clearAuth(){const e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,n,r){const s=Co(n),{modification:i,queryToken:a,unsubscribe:l}=this.state.subscribe(e,s,r?.journal,r?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{const u=l();u&&this.webSocketManager.sendMessage(u)}}}localQueryResult(e,n){const r=Co(n),s=uu(e,r);return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,n){const r=Co(n),s=uu(e,r);return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,n){const r=Co(n),s=uu(e,r);return this.state.queryJournal(s)}connectionState(){const e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){const n=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(n,e),()=>{this.connectionStateSubscribers.delete(n)}}async mutation(e,n,r){const s=await this.mutationInternal(e,n,r);if(!s.success)throw s.errorData!==void 0?NC(s,new AC(Zd("mutation",e,s))):new Error(Zd("mutation",e,s));return s.value}async mutationInternal(e,n,r,s){const{mutationPromise:i}=this.enqueueMutation(e,n,r,s);return i}enqueueMutation(e,n,r,s){const i=Co(n);this.tryReportLongDisconnect();const a=this.nextRequestId;if(this._nextRequestId++,r!==void 0){const p=r.optimisticUpdate;if(p!==void 0){const h=x=>{p(x,i)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},v=this.optimisticQueryResults.applyOptimisticUpdate(h,a).map(x=>{const b=this.localQueryResultByToken(x);return{token:x,modification:{kind:"Updated",result:b===void 0?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:v,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}const l={type:"Mutation",requestId:a,udfPath:e,componentPath:s,args:[ec(i)]},u=this.webSocketManager.sendMessage(l),d=this.requestManager.request(l,u);return{requestId:a,mutationPromise:d}}async action(e,n){const r=await this.actionInternal(e,n);if(!r.success)throw r.errorData!==void 0?NC(r,new AC(Zd("action",e,r))):new Error(Zd("action",e,r));return r.value}async actionInternal(e,n,r){const s=Co(n),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();const a={type:"Action",requestId:i,udfPath:e,componentPath:r,args:[ec(s)]},l=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,l)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){const e=_ke(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;const e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=60*1e3)return;const n=`${this.address}/api/debug_event`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${B4}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(r=>{r.ok||this.logger.warn("Analytics request failed with response:",r.body)}).catch(r=>{this.logger.warn("Analytics response failed with error:",r)})}}function kke({getCurrentValue:t,subscribe:e}){const[n,r]=w.useState(()=>({getCurrentValue:t,subscribe:e,value:t()}));let s=n.value;return(n.getCurrentValue!==t||n.subscribe!==e)&&(s=t(),r({getCurrentValue:t,subscribe:e,value:s})),w.useEffect(()=>{let i=!1;const a=()=>{i||r(u=>{if(u.getCurrentValue!==t||u.subscribe!==e)return u;const d=t();return u.value===d?u:{...u,value:d}})},l=e(a);return a(),()=>{i=!0,l()}},[t,e]),s}var Tke=Object.defineProperty,Cke=(t,e,n)=>e in t?Tke(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kl=(t,e,n)=>Cke(t,typeof e!="symbol"?e+"":e,n);const Ake=5e3;if(typeof Ee>"u")throw new Error("Required dependency 'react' not found");function x7(t,e,n){function r(s){return Pke(s),e.mutation(t,s,{optimisticUpdate:n})}return r.withOptimisticUpdate=function(i){if(n!==void 0)throw new Error(`Already specified optimistic update for mutation ${Ls(t)}`);return x7(t,e,i)},r}function Nke(t,e){return function(n){return e.action(t,n)}}class Rke{constructor(e,n){if(kl(this,"address"),kl(this,"cachedSync"),kl(this,"listeners"),kl(this,"options"),kl(this,"closed",!1),kl(this,"_logger"),kl(this,"adminAuth"),kl(this,"fakeUserIdentity"),e===void 0)throw new Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if(typeof e!="string")throw new Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw new Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=n?.logger===!1?m7({verbose:n?.verbose??!1}):n?.logger!==!0&&n?.logger?n.logger:p7({verbose:n?.verbose??!1}),this.options={...n,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw new Error("ConvexReactClient has already been closed.");return this.cachedSync?this.cachedSync:(this.cachedSync=new Eke(this.address,e=>this.transition(e),this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedSync)}setAuth(e,n){if(typeof e=="string")throw new Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,n??(()=>{}))}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,n){if(this.adminAuth=e,this.fakeUserIdentity=n,this.closed)throw new Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,n)}watchQuery(e,...n){const[r,s]=n,i=Ls(e);return{onUpdate:a=>{const{queryToken:l,unsubscribe:u}=this.sync.subscribe(i,r,s),d=this.listeners.get(l);return d!==void 0?d.add(a):this.listeners.set(l,new Set([a])),()=>{if(this.closed)return;const p=this.listeners.get(l);p.delete(a),p.size===0&&this.listeners.delete(l),u()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(i,r)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(i,r)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(i,r)}}}prewarmQuery(e){const n=e.extendSubscriptionFor??Ake,s=this.watchQuery(e.query,e.args||{}).onUpdate(()=>{});setTimeout(s,n)}mutation(e,...n){const[r,s]=n,i=Ls(e);return this.sync.mutation(i,r,s)}action(e,...n){const r=Ls(e);return this.sync.action(r,...n)}query(e,...n){const r=this.watchQuery(e,...n),s=r.localQueryResult();return s!==void 0?Promise.resolve(s):new Promise((i,a)=>{const l=r.onUpdate(()=>{l();try{i(r.localQueryResult())}catch(u){a(u)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedSync){const e=this.cachedSync;this.cachedSync=void 0,await e.close()}}transition(e){for(const n of e){const r=this.listeners.get(n);if(r)for(const s of r)s()}}}const Y0=Ee.createContext(void 0);function jke(){return w.useContext(Y0)}const Mke=({client:t,children:e})=>Ee.createElement(Y0.Provider,{value:t},e);function Eb(t,...e){const n=e[0]==="skip",r=e[0]==="skip"?{}:Co(e[0]),s=typeof t=="string"?lj(t):t,i=Ls(s),a=w.useMemo(()=>n?{}:{query:{query:s,args:r}},[JSON.stringify(ec(r)),i,n]),u=$ke(a).query;if(u instanceof Error)throw u;return u}function b7(t){const e=typeof t=="string"?lj(t):t,n=w.useContext(Y0);if(n===void 0)throw new Error("Could not find Convex client! `useMutation` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return w.useMemo(()=>x7(e,n),[n,Ls(e)])}function Oke(t){const e=w.useContext(Y0),n=lj(t);if(e===void 0)throw new Error("Could not find Convex client! `useAction` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");return w.useMemo(()=>Nke(n,e),[e,Ls(n)])}function Pke(t){if(typeof t=="object"&&t!==null&&"bubbles"in t&&"persist"in t&&"isDefaultPrevented"in t)throw new Error("Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like `const handler = () => myMutation();` and using `handler` in the event handler.")}var Ike=Object.defineProperty,Dke=(t,e,n)=>e in t?Ike(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,F1=(t,e,n)=>Dke(t,typeof e!="symbol"?e+"":e,n);class Lke{constructor(e){F1(this,"createWatch"),F1(this,"queries"),F1(this,"listeners"),this.createWatch=e,this.queries={},this.listeners=new Set}setQueries(e){for(const n of Object.keys(e)){const{query:r,args:s}=e[n];if(Ls(r),this.queries[n]===void 0)this.addQuery(n,r,s);else{const i=this.queries[n];(Ls(r)!==Ls(i.query)||JSON.stringify(ec(s))!==JSON.stringify(ec(i.args)))&&(this.removeQuery(n),this.addQuery(n,r,s))}}for(const n of Object.keys(this.queries))e[n]===void 0&&this.removeQuery(n)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getLocalResults(e){const n={};for(const r of Object.keys(e)){const{query:s,args:i}=e[r];Ls(s);const a=this.createWatch(s,i);let l;try{l=a.localQueryResult()}catch(u){if(u instanceof Error)l=u;else throw u}n[r]=l}return n}setCreateWatch(e){this.createWatch=e;for(const n of Object.keys(this.queries)){const{query:r,args:s,watch:i}=this.queries[n],a=i.journal();this.removeQuery(n),this.addQuery(n,r,s,a)}}destroy(){for(const e of Object.keys(this.queries))this.removeQuery(e);this.listeners=new Set}addQuery(e,n,r,s){if(this.queries[e]!==void 0)throw new Error(`Tried to add a new query with identifier ${e} when it already exists.`);const i=this.createWatch(n,r,s),a=i.onUpdate(()=>this.notifyListeners());this.queries[e]={query:n,args:r,watch:i,unsubscribe:a}}removeQuery(e){const n=this.queries[e];if(n===void 0)throw new Error(`No query found with identifier ${e}.`);n.unsubscribe(),delete this.queries[e]}notifyListeners(){for(const e of this.listeners)e()}}function $ke(t){const e=jke();if(e===void 0)throw new Error("Could not find Convex client! `useQuery` must be used in the React component tree under `ConvexProvider`. Did you forget it? See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app");const n=w.useMemo(()=>(r,s,i)=>e.watchQuery(r,s,i?{journal:i}:{}),[e]);return zke(t,n)}function zke(t,e){const[n]=w.useState(()=>new Lke(e));n.createWatch!==e&&n.setCreateWatch(e),w.useEffect(()=>()=>n.destroy(),[n]);const r=w.useMemo(()=>({getCurrentValue:()=>n.getLocalResults(t),subscribe:s=>(n.setQueries(t),n.subscribe(s))}),[n,t]);return kke(r)}const _7=w.createContext(void 0);function pa(){const t=w.useContext(_7);if(t===void 0)throw new Error("Could not find `ConvexProviderWithAuth` (or `ConvexProviderWithClerk` or `ConvexProviderWithAuth0`) as an ancestor component. This component may be missing, or you might have two instances of the `convex/react` module loaded in your project.");return t}function Fke({children:t,client:e,useAuth:n}){const{isLoading:r,isAuthenticated:s,fetchAccessToken:i}=n(),[a,l]=w.useState(null);return r&&a!==null&&l(null),!r&&!s&&a!==!1&&l(!1),Ee.createElement(_7.Provider,{value:{isLoading:a===null,isAuthenticated:s&&(a??!1)}},Ee.createElement(Uke,{authProviderAuthenticated:s,fetchAccessToken:i,authProviderLoading:r,client:e,setIsConvexAuthenticated:l}),Ee.createElement(Mke,{client:e},t),Ee.createElement(Bke,{authProviderAuthenticated:s,fetchAccessToken:i,authProviderLoading:r,client:e,setIsConvexAuthenticated:l}))}function Uke({authProviderAuthenticated:t,fetchAccessToken:e,authProviderLoading:n,client:r,setIsConvexAuthenticated:s}){return w.useEffect(()=>{let i=!0;if(t)return r.setAuth(e,a=>{i&&s(()=>a)}),()=>{i=!1,s(a=>a?!1:null)}},[t,e,n,r,s]),null}function Bke({authProviderAuthenticated:t,fetchAccessToken:e,authProviderLoading:n,client:r,setIsConvexAuthenticated:s}){return w.useEffect(()=>{if(t)return()=>{r.clearAuth(),s(()=>null)}},[t,e,n,r,s]),null}const qke=t=>{const e=new Map;return t.forEach(n=>{const r=e.get(n.provider)||[];e.set(n.provider,[...r,n])}),e},X4=t=>{switch(t){case"anthropic":return"Anthropic";case"openai":return"OpenAI";case"deepseek":return"DeepSeek";case"google":return"Google AI";case"ollama":return"Ollama";case"meta":return"Meta";case"x-ai":return"xAI";default:return t}};function w7({currentModel:t,availableModels:e,onModelChange:n,disabled:r,isLoading:s,hideProvidedModels:i=!1}){const[a,l]=w.useState(!1),u=t,{isAuthenticated:d}=pa(),p=qke(e),h=Array.from(p.keys()).sort(),g=i?[]:h.filter(x=>(p.get(x)||[]).some(E=>ra(E.id))),v=h.filter(x=>(p.get(x)||[]).some(E=>!ra(E.id)));return f.jsxs(m0,{open:a,onOpenChange:l,children:[f.jsx(g0,{asChild:!0,children:f.jsx(Pe,{variant:"ghost",size:"sm",disabled:r||s,className:"h-8 px-2 rounded-full hover:bg-muted/80 transition-colors text-xs cursor-pointer",children:f.jsxs(f.Fragment,{children:[f.jsx(P1,{provider:u.provider}),f.jsx("span",{className:"text-[10px] font-medium",children:u.name})]})})}),f.jsxs(v0,{align:"start",className:"min-w-[200px]",children:[g.length>0&&f.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Provided Models"}),g.map(x=>{const E=(p.get(x)||[]).filter(k=>ra(k.id)),S=E.length;return f.jsxs(vI,{children:[f.jsxs(yI,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[f.jsx(P1,{provider:x}),f.jsxs("div",{className:"flex flex-col flex-1",children:[f.jsx("span",{className:"font-medium",children:X4(x)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:[S," model",S!==1?"s":""]})]})]}),f.jsx(xI,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:E.map(k=>{const T=ra(k.id),R=!!k.disabled||T&&!d,j=T&&!d?"Sign in to use MCPJam provided models":k.disabledReason,A=f.jsxs(Ro,{onSelect:()=>{n(k),l(!1)},className:"flex items-center gap-3 text-sm cursor-pointer",disabled:R,children:[f.jsx("div",{className:"flex flex-col flex-1",children:f.jsx("span",{className:"font-medium",children:k.name})}),k.id===t.id&&f.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},k.id);return R?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx("div",{className:"pointer-events-auto",children:A})}),f.jsx(La,{side:"right",children:j})]},k.id):A})})]},x)}),g.length>0&&v.length>0&&f.jsx("div",{className:"my-1 h-px bg-muted/50"}),v.length>0&&f.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your providers"}),v.map(x=>{const E=(p.get(x)||[]).filter(k=>!ra(k.id)),S=E.length;return f.jsxs(vI,{children:[f.jsxs(yI,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[f.jsx(P1,{provider:x}),f.jsxs("div",{className:"flex flex-col flex-1",children:[f.jsx("span",{className:"font-medium",children:X4(x)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:[S," model",S!==1?"s":""]})]})]}),f.jsx(xI,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:E.map(k=>{const T=!!k.disabled,R=f.jsxs(Ro,{onSelect:()=>{n(k),l(!1)},className:"flex items-center gap-3 text-sm cursor-pointer",disabled:T,children:[f.jsx("div",{className:"flex flex-col flex-1",children:f.jsx("span",{className:"font-medium",children:k.name})}),k.id===t.id&&f.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},k.id);return T?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx("div",{className:"pointer-events-auto",children:R})}),f.jsx(La,{side:"right",children:k.disabledReason})]},k.id):R})})]},x)})]})]})}function Vke({className:t,defaultValue:e,value:n,min:r=0,max:s=100,...i}){const a=w.useMemo(()=>Array.isArray(n)?n:Array.isArray(e)?e:[r,s],[n,e,r,s]);return f.jsxs(hre,{"data-slot":"slider",defaultValue:e,value:n,min:r,max:s,className:Oe("relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",t),...i,children:[f.jsx(pre,{"data-slot":"slider-track",className:Oe("bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"),children:f.jsx(mre,{"data-slot":"slider-range",className:Oe("bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full")})}),Array.from({length:a.length},(l,u)=>f.jsx(gre,{"data-slot":"slider-thumb",className:"border-primary bg-background ring-ring/50 block size-4 shrink-0 rounded-full border shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"},u))]})}function Hke({systemPrompt:t,onSystemPromptChange:e,temperature:n,onTemperatureChange:r,disabled:s,isLoading:i}){const[a,l]=w.useState(!1),[u,d]=w.useState(t),[p,h]=w.useState(n),g=b=>{l(b),b&&(d(t),h(n))},v=()=>{e(u),r(p),l(!1),It.success("System prompt and temperature updated")},x=()=>{d(t),h(n),l(!1)};return f.jsxs(ua,{open:a,onOpenChange:g,children:[f.jsx(gN,{asChild:!0,children:f.jsxs(Pe,{variant:"ghost",size:"sm",disabled:s||i,className:"h-8 px-2 rounded-full hover:bg-muted/80 transition-colors text-xs cursor-pointer",children:[f.jsx(bie,{className:"h-2 w-2 mr-1"}),f.jsx("span",{className:"text-[10px] font-medium",children:"System Prompt & Temperature"})]})}),f.jsxs(da,{className:"sm:max-w-md",children:[f.jsx(fa,{children:f.jsx(ha,{children:"System Prompt & Temperature"})}),f.jsxs("div",{className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("label",{className:"text-sm font-medium",children:"System Prompt"}),f.jsx(Qo,{value:u,onChange:b=>d(b.target.value),placeholder:"You are a helpful assistant with access to MCP tools.",className:"h-[140px] resize-none"})]}),f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("label",{className:"text-sm font-medium",children:"Temperature"}),f.jsx("span",{className:"text-sm text-muted-foreground",children:p.toFixed(1)})]}),f.jsx(Vke,{value:[p],onValueChange:b=>h(b[0]),min:0,max:2,step:.1,className:"w-full"}),f.jsx("p",{className:"text-xs text-muted-foreground",children:"Lower values (0-0.3) for focused tasks, higher values (0.7-2.0) for creative tasks"})]}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx(Pe,{variant:"ghost",onClick:x,className:"cursor-pointer",children:"Cancel"}),f.jsx(Pe,{onClick:v,className:"cursor-pointer",children:"Save"})]})]})]})]})}function Q4({value:t,onChange:e,onSubmit:n,onStop:r,disabled:s=!1,isLoading:i=!1,placeholder:a="Type your message...",className:l,showScrollToBottom:u=!1,onScrollToBottom:d,currentModel:p,availableModels:h,onModelChange:g,systemPrompt:v,onSystemPromptChange:x,temperature:b,onTemperatureChange:E,isSendBlocked:S=!1}){const k=w.useRef(null),T=w.useRef(null),[R,j]=w.useState([]),[A,N]=w.useState([]),M=p;w.useEffect(()=>{I()},[t]);const I=()=>{k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,120)}px`)},O=()=>{k.current&&(k.current.style.height="auto")},L=w.useCallback(()=>{!t.trim()||s||i||A.length>0||S||(n(t.trim(),R.length>0?R:void 0),e(""),j([]),O(),setTimeout(()=>{k.current?.focus()},0))},[t,s,i,A.length,n,R,e,S]),z=X=>{X.key==="Enter"&&!X.shiftKey&&!X.nativeEvent.isComposing&&(X.preventDefault(),L())},H=w.useCallback(async X=>{const F=Array.from(X.target.files||[]);if(F.length!==0){N(F.map(W=>W.name));try{const W=await Promise.all(F.map(async G=>(await new Promise(ee=>setTimeout(ee,1e3)),{id:Math.random().toString(36).substr(2,9),name:G.name,url:URL.createObjectURL(G),contentType:G.type,size:G.size})));j(G=>[...G,...W])}catch(W){console.error("Error uploading files:",W)}finally{N([]),T.current&&(T.current.value="")}}},[]),V=X=>{j(F=>F.filter(W=>W.id!==X))};return f.jsxs("div",{className:"relative w-full",children:[f.jsx(pb,{children:u&&f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},className:"absolute left-1/2 bottom-full mb-4 -translate-x-1/2 z-50",children:f.jsx(Pe,{size:"sm",variant:"outline",className:"rounded-full shadow-lg cursor-pointer",onClick:d,children:f.jsx(Jre,{className:"h-4 w-4"})})})}),f.jsx("input",{ref:T,type:"file",multiple:!0,className:"hidden",onChange:H,accept:"image/*,.pdf,.txt,.json,.csv"}),(R.length>0||A.length>0)&&f.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[R.map(X=>f.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[f.jsx("span",{className:"truncate max-w-[200px]",children:X.name}),f.jsx("button",{onClick:()=>V(X.id),className:"text-muted-foreground hover:text-foreground cursor-pointer",children:"×"})]},X.id)),A.map(X=>f.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 px-3 py-2 rounded-lg text-sm animate-pulse",children:[f.jsx("span",{className:"truncate max-w-[200px]",children:X}),f.jsx("div",{className:"w-3 h-3 border-2 border-current border-t-transparent rounded-full animate-spin"})]},X))]}),f.jsxs("div",{className:"relative",children:[f.jsx(Qo,{ref:k,value:t,onChange:X=>{S||e(X.target.value)},onKeyDown:z,placeholder:a,disabled:s,readOnly:s||S,className:AT("min-h-[56px] max-h-[120px] resize-none pl-16 pr-14 py-4 rounded-3xl","border-border/30 bg-background/50 focus-visible:border-border/50","focus-visible:ring-0 focus-visible:ring-offset-0","transition-all duration-200 ease-in-out overflow-y-auto","text-base placeholder:text-muted-foreground/60",S?"cursor-not-allowed bg-muted/30 text-muted-foreground":"",l),rows:1,autoFocus:!S}),f.jsx("div",{className:"absolute bottom-3 left-4 flex items-center gap-1",children:f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",className:"h-8 w-8 p-0 rounded-full hover:bg-muted/80 transition-colors cursor-pointer",onClick:()=>T.current?.click(),disabled:s||i||S,children:f.jsx(lie,{size:16})})}),f.jsx(La,{children:"Add files"})]})}),f.jsx("div",{className:"absolute bottom-3 right-4 flex items-center gap-1",children:i?f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",size:"sm",variant:"outline",className:"h-8 w-8 p-0 rounded-full border-border/30 hover:border-border/50 transition-colors cursor-pointer",onClick:r,children:f.jsx(Rie,{size:16})})}),f.jsx(La,{children:"Stop generating"})]}):f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",size:"sm",className:AT("h-8 w-8 p-0 rounded-full transition-all duration-200 cursor-pointer",t.trim()&&!s&&A.length===0&&!S?"bg-primary text-primary-foreground hover:bg-primary/90 shadow-sm":"bg-muted text-muted-foreground cursor-not-allowed"),onClick:L,disabled:!t.trim()||s||A.length>0||S,children:f.jsx(bB,{size:16})})}),f.jsx(La,{children:"Send message"})]})})]}),f.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[h.length>0&&M&&f.jsx(w7,{currentModel:M,availableModels:h,onModelChange:g,disabled:!1,isLoading:i}),x&&E&&f.jsx(Hke,{systemPrompt:v||"You are a helpful assistant with access to MCP tools.",onSystemPromptChange:x,temperature:b||0,onTemperatureChange:E,disabled:s,isLoading:i})]})]})}function Gke({serverConfigs:t,connectedServerConfigs:e,systemPrompt:n=""}){const r=w.useRef(null),[s,i]=w.useState(!0),{isAuthenticated:a}=pa(),{signUp:l}=Fi(),u=Qr(),[d,p]=w.useState(n||"You are a helpful assistant with access to MCP tools."),[h,g]=w.useState(1),[v,x]=w.useState({}),E=Object.keys(t||{}).filter(Z=>e?.[Z]?.connectionStatus==="connected"),S=E.length===0,{messages:k,isLoading:T,error:R,input:j,setInput:A,sendMessage:N,stopGeneration:M,regenerateMessage:I,clearChat:O,model:L,availableModels:z,setModel:H,elicitationRequest:V,elicitationLoading:X,handleElicitationResponse:F}=xV({systemPrompt:d,temperature:h,selectedServers:E,onError:Z=>{It.error(Z)}}),G=(L?ra(L.id):!1)&&!a,ee="Sign in to use MCPJam provided models";w.useEffect(()=>{G&&A("")},[G,A]),w.useEffect(()=>{u.capture("chat_tab_viewed",{location:"chat_tab",platform:on(),environment:void 0})},[]),w.useEffect(()=>{const Z=localStorage.getItem("chat-selected-model");if(Z&&z.length>0){const U=z.find(J=>J.id===Z);U&&(!L||L.id!==Z)&&H(U)}},[z]),w.useEffect(()=>{L&&localStorage.setItem("chat-selected-model",L.id)},[L]),w.useEffect(()=>{L&&g(Ide(L))},[L]),w.useEffect(()=>{const Z=async()=>{const U={};for(const J of E)try{const oe=await ON(J);oe.toolsMetadata&&Object.assign(U,oe.toolsMetadata)}catch(oe){console.error(`Failed to fetch tools for server ${J}:`,oe)}x(U)};E&&E.length>0?Z():x({})},[JSON.stringify(E)]);const P=k.length>0,ie=G||S,ue=G?"Sign in to use free chat":"Connect an MCP server to send your first message",D=[{label:"Available tools",value:"What tools are available?",icon:EB}];w.useEffect(()=>{s&&r.current&&(r.current.scrollTop=r.current.scrollHeight)},[k,s]);const ne=()=>{if(!r.current)return;const{scrollTop:Z,scrollHeight:U,clientHeight:J}=r.current,pe=U-Z-J<100;i(pe)},fe=Z=>{navigator.clipboard.writeText(Z)},q=async(Z,U)=>{try{return(await(await fetch("/api/mcp/tools/execute",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({toolName:Z,parameters:U,...E.length===1?{serverId:E[0]}:{}})})).json()).result}catch(J){throw J}},K=Z=>{A(Z),N(Z)},Y=(Z,U)=>f.jsxs("div",{className:"flex flex-col h-screen",children:[f.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center px-4",children:[f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{duration:.35},className:"w-full max-w-xl space-y-6 text-center",children:Z}),f.jsxs(ri.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.35,delay:.05},className:"w-full max-w-2xl pt-10",children:[f.jsx(Q4,{value:j,onChange:A,onSubmit:()=>{u.capture("send_message",{location:"chat_tab",platform:on(),environment:void 0,model_id:L?.id??null,model_name:L?.name??null,model_provider:L?.provider??null}),N(j)},onStop:M,disabled:z.length===0||U.disabled,isLoading:T,placeholder:U.placeholder,className:"border shadow-sm",currentModel:L||null,availableModels:z,onModelChange:H,onClearChat:O,hasMessages:!1,systemPrompt:d,onSystemPromptChange:p,temperature:h,onTemperatureChange:g,isSendBlocked:G}),z.length===0&&f.jsx(ri.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.25},className:"mt-3 text-center text-xs text-muted-foreground",children:"Configure API keys in Settings or start Ollama to enable chat"})]})]}),f.jsx(TT,{elicitationRequest:V,onResponse:F,loading:X})]});if(!P&&ie)return Y(G?f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx("h2",{className:"text-base font-medium",children:"Create an account to use free models"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"or bring your own API key in the settings tab"})]}),f.jsx("div",{className:"flex justify-center gap-2",children:f.jsx(Pe,{onClick:()=>{u.capture("sign_up_button_clicked",{location:"chat_tab",platform:on(),environment:void 0}),l()},className:"hover:opacity-90 cursor-pointer",children:"Create account"})})]}):f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"space-y-1",children:f.jsx("h2",{className:"text-base font-medium",children:"You must connect to an MCP server"})}),f.jsxs("div",{className:"flex justify-center gap-2 text-xs text-muted-foreground",children:[f.jsxs("a",{href:"#servers",className:"inline-flex items-center gap-1 rounded-full border px-3 py-1 transition hover:bg-muted/30",children:[f.jsx(vse,{className:"h-3 w-3"})," Add server"]}),f.jsxs("a",{href:"#settings",className:"inline-flex items-center gap-1 rounded-full border px-3 py-1 transition hover:bg-muted/30",children:[f.jsx(rN,{className:"h-3 w-3"})," Settings"]})]})]}),{placeholder:ue,disabled:!0});if(!P){const Z=f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"space-y-1",children:[f.jsx("h2",{className:"text-base font-medium",children:"Test your servers"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Start typing or choose a quick suggestion to begin."})]}),f.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:D.map(({label:U,value:J,icon:oe})=>f.jsxs("button",{type:"button",onClick:()=>A(J),className:"inline-flex items-center gap-2 rounded-full border border-border/60 px-3 py-1.5 text-xs transition hover:border-border hover:bg-muted/40 cursor-pointer",children:[f.jsx(oe,{className:"h-3.5 w-3.5 text-muted-foreground"}),U]},U))})]});return Y(Z,{placeholder:"Send a message...",disabled:!1})}return f.jsx(p0,{children:f.jsxs(Fa,{direction:"horizontal",className:"h-screen",children:[f.jsx(cr,{defaultSize:70,minSize:40,children:f.jsxs("div",{className:"flex flex-col bg-background h-full overflow-hidden",children:[f.jsx("div",{ref:r,onScroll:ne,className:"flex-1 overflow-y-auto pb-4",children:f.jsx("div",{className:"max-w-4xl mx-auto px-4 pt-8 pb-8",children:f.jsxs(pb,{mode:"popLayout",children:[k.map((Z,U)=>f.jsx(ri.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.3,delay:U*.05},className:"mb-8",children:f.jsx(f1e,{message:Z,model:L||null,isLoading:T&&U===k.length-1,onEdit:()=>{},onRegenerate:I,onCopy:fe,showActions:!0,serverConfigs:t,onCallTool:q,onSendFollowup:K,toolsMetadata:v,serverId:E.length===1?E[0]:void 0})},Z.id)),T&&k.length>0&&k[k.length-1].role==="user"&&f.jsx(ri.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"mb-8",children:f.jsxs("div",{className:"flex gap-4 items-start",children:[f.jsx("div",{className:"w-8 h-8 flex items-center rounded-full justify-center bg-muted/50 shrink-0",children:f.jsx(SB,{className:"h-4 w-4 text-muted-foreground"})}),f.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[f.jsx("span",{className:"text-sm text-muted-foreground",children:"Thinking"}),f.jsxs("div",{className:"flex space-x-1",children:[f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce delay-100"}),f.jsx("div",{className:"w-1.5 h-1.5 bg-muted-foreground/60 rounded-full animate-bounce delay-200"})]})]})]})})]})})}),f.jsx(pb,{children:R&&f.jsx(ri.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:20},className:"px-4 py-3 bg-destructive/5 border-t border-destructive/10",children:f.jsx("div",{className:"max-w-4xl mx-auto",children:f.jsx("p",{className:"text-sm text-destructive",children:R})})})}),f.jsx("div",{className:"border-t border-border/50 bg-background/80 backdrop-blur-sm flex-shrink-0",children:f.jsx("div",{className:"max-w-4xl mx-auto p-4",children:f.jsx("div",{children:f.jsx(Q4,{value:j,onChange:A,onSubmit:(Z,U)=>{u.capture("send_message",{location:"chat_tab",platform:on(),environment:void 0,model_id:L?.id??null,model_name:L?.name??null,model_provider:L?.provider??null}),N(Z,U)},onStop:M,disabled:z.length===0||S||G,isLoading:T,placeholder:G?ee:"Send a message...",className:"border-2 shadow-sm",currentModel:L,availableModels:z,onModelChange:H,onClearChat:O,hasMessages:P,systemPrompt:d,onSystemPromptChange:p,temperature:h,onTemperatureChange:g,isSendBlocked:G})})})}),f.jsx(TT,{elicitationRequest:V,onResponse:F,loading:X})]})}),f.jsx(Ua,{withHandle:!0}),f.jsx(cr,{defaultSize:30,minSize:20,maxSize:50,children:f.jsx(L0,{})})]})})}function S7(t,e,n){const r=n.reduce((i,a)=>(a.status==="pending"||a.status==="running"||a.result==="pending"?i.pending+=1:a.result==="passed"?i.passed+=1:a.result==="failed"?i.failed+=1:a.result==="cancelled"&&(i.cancelled+=1),i.tokens+=a.tokensUsed||0,i),{passed:0,failed:0,cancelled:0,pending:0,tokens:0}),s=new Map;for(const i of n){const a=i.testCaseId;if(!a)continue;if(!s.has(a)){const u=e.find(p=>p._id===a),d=n.filter(p=>p.testCaseId===a).length;s.set(a,{testCaseId:a,title:u?.title||"Untitled",provider:u?.provider||"",model:u?.model||"",runs:d,passed:0,failed:0,cancelled:0,tokens:0})}const l=s.get(a);i.status==="pending"||i.status==="running"||i.result==="pending"||(i.result==="passed"?l.passed+=1:i.result==="failed"?l.failed+=1:i.result==="cancelled"&&(l.cancelled+=1)),l.tokens+=i.tokensUsed||0}return{filteredIterations:n,totals:r,byCase:Array.from(s.values())}}function Wke(t,e,n,r){const s=[];return t>0&&s.push(`${t} passed`),e>0&&s.push(`${e} failed`),n>0&&s.push(`${n} cancelled`),r>0&&s.push(`${r} pending`),s.join(" · ")||"No results"}function Yke({suite:t,onSelectSuite:e}){const{isAuthenticated:n}=pa(),{user:r}=Fi(),s=t.config?.environment.servers,a=Eb("evals:getAllTestCasesAndIterationsBySuite",n&&!!r?{suiteId:t._id}:"skip"),l=w.useMemo(()=>a?S7(t,a.testCases,a.iterations):null,[t,a]),u=Array.isArray(t.config?.tests)?t.config.tests.length:0,d=w.useMemo(()=>{if(!Array.isArray(s))return[];const g=s.filter(x=>typeof x=="string").map(x=>x.trim()).filter(Boolean);if(g.length<=2)return g;const v=g.length-2;return[...g.slice(0,2),`+${v} more`]},[s]),p=l?.filteredIterations.length??0,h=()=>{if(!l)return"bg-zinc-300/50";const{passed:g,failed:v,cancelled:x,pending:b}=l.totals;if(g+v+x+b===0)return"bg-zinc-300/50";const S=g+v;if(S===0)return"bg-zinc-300/50";const k=v/S*100;return k===0?"bg-emerald-500/50":k<=30?"bg-amber-500/50":"bg-red-500/50"};return f.jsxs("button",{onClick:()=>e(t._id),className:"group relative flex w-full items-center gap-4 py-3 pl-4 pr-4 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer",children:[f.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${h()}`}),f.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] items-center gap-4",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm font-medium text-foreground",children:new Date(t._creationTime||0).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}),f.jsx("div",{className:"text-xs text-muted-foreground",children:d.length>0?d.join(", "):"No servers"})]}),f.jsxs("div",{className:"text-sm text-muted-foreground",children:[u," test",u!==1?"s":""," · ",p," ","iteration",p!==1?"s":""]}),f.jsx("div",{className:"text-sm text-muted-foreground",children:l?Wke(l.totals.passed,l.totals.failed,l.totals.cancelled,l.totals.pending):"Loading..."})]})]})}function Kke({suites:t,onSelectSuite:e}){if(t.length===0)return f.jsx("div",{className:"h-[calc(100vh-220px)] flex items-center justify-center rounded-xl border border-dashed",children:f.jsxs("div",{className:"text-center space-y-2",children:[f.jsx("div",{className:"text-lg font-semibold",children:"No evaluation suites yet"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Trigger a test run to see your evaluation history here."})]})});const n=[...t].sort((r,s)=>(s._creationTime||0)-(r._creationTime||0));return f.jsx("div",{className:"space-y-4",children:f.jsxs("div",{className:"overflow-hidden rounded-xl border",children:[f.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] items-center gap-4 border-b bg-muted/50 px-4 py-2 text-xs font-semibold text-muted-foreground",children:[f.jsx("div",{children:"Created"}),f.jsx("div",{children:"Tests"}),f.jsx("div",{children:"Results"})]}),f.jsx("div",{className:"divide-y",children:n.map(r=>f.jsx(Yke,{suite:r,onSelectSuite:e},r._id))})]})})}function Xke({iteration:t,testCase:e}){const n=Oke("evals:getEvalTestBlob"),[r,s]=w.useState(null),[i,a]=w.useState(!1),[l,u]=w.useState(null);return w.useEffect(()=>{let d=!1;async function p(){if(!t.blob){s(null),a(!1),u(null);return}a(!0),u(null);try{const h=await n({blobId:t.blob});d||s(h)}catch(h){d||(u(h?.message||"Failed to load blob"),console.error("Blob load error:",h))}finally{d||a(!1)}}return p(),()=>{d=!0}},[t.blob,n]),f.jsxs("div",{className:"space-y-3 py-2",children:[(e?.expectedToolCalls.length||0)>0&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Expected tools"}),f.jsx("div",{className:"flex flex-wrap gap-1.5",children:e?.expectedToolCalls.map((d,p)=>f.jsx(xr,{variant:"outline",className:"font-mono text-xs",children:d},p))})]}),t.actualToolCalls.length>0&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Actual tools called"}),f.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.actualToolCalls.map((d,p)=>f.jsx(xr,{variant:"outline",className:"font-mono text-xs",children:d},p))})]}),t.blob&&f.jsxs("div",{className:"space-y-1.5",children:[f.jsx("div",{className:"text-xs font-semibold",children:"Trace"}),f.jsx("div",{className:"rounded-md bg-muted/20 p-3",children:i?f.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading trace"}):l?f.jsx("div",{className:"text-xs text-red-600",children:l}):f.jsx("pre",{className:"max-h-[360px] overflow-auto whitespace-pre-wrap break-words text-xs",children:JSON.stringify(r,null,2)})})]})]})}function Qke({suite:t,cases:e,iterations:n,aggregate:r,onBack:s}){const[i,a]=w.useState(null),[l,u]=w.useState(new Set),d=w.useMemo(()=>{const h=new Map,g=b=>{const E={runs:b.length,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null};let S=0,k=0;return b.forEach(T=>{T.result==="passed"?E.passed+=1:T.result==="failed"?E.failed+=1:T.result==="cancelled"?E.cancelled+=1:E.pending+=1,E.tokens+=T.tokensUsed||0;const R=T.startedAt??T.createdAt,j=T.updatedAt??T.createdAt;if(R&&j){const A=Math.max(j-R,0);S+=A,k+=1}}),k>0&&(E.avgDuration=S/k),E};e.forEach(b=>{h.set(b._id,{testCase:b,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})});const v={testCase:null,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}};n.forEach(b=>{const E=b.testCaseId?h.get(b.testCaseId):void 0;E?E.iterations.push(b):v.iterations.push(b)});const x=e.map(b=>{const E=h.get(b._id),S=[...E.iterations].sort((k,T)=>k.iterationNumber!=null&&T.iterationNumber!=null?k.iterationNumber-T.iterationNumber:(k.createdAt??0)-(T.createdAt??0));return{...E,iterations:S,summary:g(S)}});if(v.iterations.length>0){const b=[...v.iterations].sort((E,S)=>E.iterationNumber!=null&&S.iterationNumber!=null?E.iterationNumber-S.iterationNumber:(E.createdAt??0)-(S.createdAt??0));x.push({...v,iterations:b,summary:g(b)})}return x},[e,n]),p=h=>h==="passed"?"bg-emerald-500/50":h==="failed"?"bg-red-500/50":h==="cancelled"?"bg-zinc-300/50":"bg-amber-500/50";return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{children:f.jsx(Pe,{variant:"ghost",size:"sm",onClick:s,children:"← Back to suites"})}),f.jsx("div",{className:"space-y-4",children:d.map((h,g)=>{const{testCase:v,iterations:x}=h,b=x.length>0,E=v?._id??`unassigned-${g}`,S=l.has(E),k=100,T=v?.query&&v.query.length>k,R=T&&!S?v.query.slice(0,k)+"...":v?.query,j=()=>{u(A=>{const N=new Set(A);return N.has(E)?N.delete(E):N.add(E),N})};return f.jsxs("div",{className:"overflow-hidden rounded-xl border",children:[f.jsx("div",{className:"border-b bg-muted/50 px-4 py-2.5",children:f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-semibold pr-2",children:v?v.title:"Unassigned iterations"}),v?.provider?f.jsx(f.Fragment,{children:f.jsx("span",{className:"text-xs text-muted-foreground",children:v.provider})}):null,v?.model?f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"text-muted-foreground",children:"•"}),f.jsx("span",{className:"text-xs text-muted-foreground",children:v.model})]}):null]}),v?.query?f.jsxs("div",{className:"flex items-start gap-2",children:[f.jsxs("p",{className:"text-xs text-muted-foreground italic flex-1",children:['"',R,'"']}),T?f.jsx("button",{onClick:j,className:"text-xs text-primary hover:underline focus:outline-none whitespace-nowrap",children:S?"Show less":"Show more"}):null]}):null]})}),b?f.jsx("div",{className:"divide-y",children:x.map(A=>{const N=i===A._id,M=A.startedAt??A.createdAt,I=A.updatedAt??A.createdAt,O=M&&I?Math.max(I-M,0):null,L=A.result==="pending";return f.jsxs("div",{className:`relative ${L?"opacity-60":""}`,children:[f.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${p(A.result)}`}),f.jsx("button",{onClick:()=>{L||a(z=>z===A._id?null:A._id)},disabled:L,className:`flex w-full items-center gap-4 px-4 py-3 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 ${L?"cursor-not-allowed":"cursor-pointer hover:bg-muted/50"}`,children:f.jsxs("div",{className:"grid min-w-0 flex-1 grid-cols-[auto_1fr_auto_auto] items-center gap-4 pl-3",children:[f.jsx("div",{className:"text-muted-foreground",children:L?f.jsx(la,{className:"h-4 w-4"}):N?f.jsx(cc,{className:"h-4 w-4"}):f.jsx(la,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("span",{className:"text-sm font-medium",children:["Iteration #",A.iterationNumber]}),L?f.jsx(bu,{className:"h-4 w-4 animate-spin text-amber-600"}):null]}),f.jsx("div",{className:"text-sm text-muted-foreground",children:L?"—":`${Number(A.tokensUsed||0).toLocaleString()} tokens`}),f.jsx("div",{className:"text-sm text-muted-foreground",children:L?"—":O!==null?Jke(O):"—"})]})}),N&&!L?f.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:f.jsx(Xke,{iteration:A,testCase:v})}):null]},A._id)})}):f.jsx("div",{className:"px-4 py-6 text-center text-sm text-muted-foreground",children:"No iterations recorded for this test case yet."})]},E)})})]})}function Jke(t){if(t<1e3)return`${t}ms`;const e=Math.round(t/1e3);if(e<60)return`${e}s`;const n=Math.floor(e/60),r=e%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const s=Math.floor(n/60),i=n%60;return i?`${s}h ${i}m`:`${s}h`}function Zke(){const{isAuthenticated:t,isLoading:e}=pa(),{user:n}=Fi(),[r,s]=w.useState(null),i=t&&!!n,a=Eb("evals:getCurrentUserEvalTestSuitesWithMetadata",i?{}:"skip"),l=t&&!!n&&!!r,u=Eb("evals:getAllTestCasesAndIterationsBySuite",l?{suiteId:r}:"skip"),d=a?.testSuites,p=a===void 0,h=l&&u===void 0,g=w.useMemo(()=>!r||!d?null:d.find(b=>b._id===r)??null,[r,d]),v=w.useMemo(()=>u?[...u.iterations].sort((b,E)=>(E.startedAt||E.createdAt)-(b.startedAt||b.createdAt)):[],[u]),x=w.useMemo(()=>!g||!u?null:S7(g,u.testCases,u.iterations),[g,u]);return e?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!n?f.jsx("div",{className:"p-6",children:f.jsx(rh,{icon:wB,title:"Sign in to view your evals",description:"Create an account or sign in to see previous runs and metrics.",className:"h-[calc(100vh-200px)]"})}):p&&i?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading your eval data..."})]})})}):f.jsxs("div",{className:"space-y-6 p-6",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsx("h1",{className:"text-2xl font-semibold",children:"Evaluation results"})}),g?h?f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading suite details..."})]})}):f.jsx(Qke,{suite:g,cases:u?.testCases||[],iterations:v,aggregate:x,onBack:()=>s(null)}):f.jsx(Kke,{suites:d||[],onSelectSuite:s})]})}const eTe="modulepreload",tTe=function(t){return"/"+t},J4={},nTe=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let d=function(p){return Promise.all(p.map(h=>Promise.resolve(h).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};var a=d;document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=l?.nonce||l?.getAttribute("nonce");s=d(n.map(p=>{if(p=tTe(p),p in J4)return;J4[p]=!0;const h=p.endsWith(".css"),g=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${g}`))return;const v=document.createElement("link");if(v.rel=h?"stylesheet":eTe,h||(v.as="script"),v.crossOrigin="",v.href=p,u&&v.setAttribute("nonce",u),document.head.appendChild(v),h)return new Promise((x,b)=>{v.addEventListener("load",x),v.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},RC={servers:{},selectedServer:"none",selectedMultipleServers:[],isMultiSelectMode:!1},Tp=(t,e,n={})=>({...t,connectionStatus:e,...n});function rTe(t,e){switch(e.type){case"HYDRATE_STATE":return e.payload;case"UPSERT_SERVER":return{...t,servers:{...t.servers,[e.name]:e.server}};case"CONNECT_REQUEST":{const n=t.servers[e.name],r=n?Tp(n,"connecting",{enabled:!0}):{name:e.name,config:e.config,lastConnectionTime:new Date,connectionStatus:"connecting",retryCount:0,enabled:!0};return{...t,servers:{...t.servers,[e.name]:{...r,config:e.config}},selectedServer:e.select?e.name:t.selectedServer}}case"CONNECT_SUCCESS":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"connected",{config:e.config,lastConnectionTime:new Date,retryCount:0,lastError:void 0,oauthTokens:e.tokens??n.oauthTokens,enabled:!0})}}:t}case"CONNECT_FAILURE":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"failed",{retryCount:n.retryCount,lastError:e.error})}}:t}case"RECONNECT_REQUEST":{const n=t.servers[e.name];return n?{...t,servers:{...t.servers,[e.name]:Tp(n,"connecting",{enabled:!0})}}:t}case"DISCONNECT":{const n=t.servers[e.name];if(!n)return t;const r=t.selectedServer===e.name?"none":t.selectedServer;return{...t,servers:{...t.servers,[e.name]:Tp(n,"disconnected",{enabled:!1,lastError:e.error??n.lastError})},selectedServer:r,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"REMOVE_SERVER":{const{[e.name]:n,...r}=t.servers;return{...t,servers:r,selectedServer:t.selectedServer===e.name?"none":t.selectedServer,selectedMultipleServers:t.selectedMultipleServers.filter(s=>s!==e.name)}}case"SYNC_AGENT_STATUS":{const n=new Map(e.servers.map(s=>[s.id,s.status])),r={};for(const[s,i]of Object.entries(t.servers)){if(i.connectionStatus==="connecting"||i.connectionStatus==="oauth-flow"){r[s]=i;continue}const l=n.get(s);l?r[s]={...i,connectionStatus:l}:r[s]={...i,connectionStatus:"disconnected"}}return{...t,servers:r}}case"SELECT_SERVER":return{...t,selectedServer:e.name};case"SET_MULTI_SELECTED":return{...t,selectedMultipleServers:e.names};case"SET_MULTI_MODE":return{...t,isMultiSelectMode:e.enabled,selectedMultipleServers:e.enabled?[]:t.selectedMultipleServers};default:return t}}const E7="mcp-inspector-state";function sTe(t){const e=t.config;let n=e;if(e&&typeof e.url=="string")try{n={...e,url:new URL(e.url)}}catch{}return{...t,config:n,connectionStatus:t.connectionStatus||"disconnected",retryCount:t.retryCount||0,lastConnectionTime:t.lastConnectionTime?new Date(t.lastConnectionTime):new Date,enabled:t.enabled!==!1}}function iTe(){try{const t=localStorage.getItem(E7);if(!t)return RC;const e=JSON.parse(t);return{servers:Object.fromEntries(Object.entries(e.servers||{}).map(([r,s])=>[r,sTe(s)])),selectedServer:e.selectedServer||"none",selectedMultipleServers:e.selectedMultipleServers||[],isMultiSelectMode:e.isMultiSelectMode||!1}}catch{return RC}}function aTe(t){const e={...t,servers:Object.fromEntries(Object.entries(t.servers).map(([n,r])=>{const s=r.config,i=s&&s.url instanceof URL?{...s,url:s.url.toString()}:s;return[n,{...r,config:i}]}))};localStorage.setItem(E7,JSON.stringify(e))}async function Ey(t,e){return(await fetch("/api/mcp/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverConfig:t,serverId:e})})).json()}async function oTe(t){return(await fetch(`/api/mcp/servers/${encodeURIComponent(t)}`,{method:"DELETE"})).json()}async function lTe(){return(await fetch("/api/mcp/servers")).json()}async function cTe(t,e){return(await fetch("/api/mcp/servers/reconnect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:t,serverConfig:e})})).json()}async function uTe(t){if(!t.oauthTokens&&!RN(t.name))return{kind:"ready",serverConfig:t.config,tokens:void 0};if(t.oauthTokens){const a=await jN(t.name);if(a.success&&a.serverConfig)return{kind:"ready",serverConfig:a.serverConfig,tokens:si(t.name)}}const e=localStorage.getItem(`mcp-serverUrl-${t.name}`),n=localStorage.getItem(`mcp-client-${t.name}`),r=localStorage.getItem(`mcp-oauth-config-${t.name}`),s=si(t.name),i=t.config?.url?.toString?.()||e;if(i){const a=r?JSON.parse(r):{},l=n?JSON.parse(n):{},u={serverName:t.name,serverUrl:i,clientId:t.oauthTokens?.client_id||s?.client_id||l?.client_id,clientSecret:t.oauthTokens?.client_secret||l?.client_secret,scopes:a.scopes},d=await tb(u);return d.success&&d.serverConfig?{kind:"ready",serverConfig:d.serverConfig,tokens:si(t.name)}:d.success&&!d.serverConfig?{kind:"redirect"}:{kind:"error",error:d.error||"OAuth init failed"}}return{kind:"error",error:"OAuth refresh failed and no URL present"}}function U1(t){return t.type==="stdio"?{command:t.command,args:t.args,env:t.env}:{url:new URL(t.url),requestInit:{headers:t.headers||{}}}}function k7(){const t=QN("Connections"),[e,n]=w.useReducer(rTe,RC),[r,s]=w.useState(!0),i=w.useRef(new Map),a=A=>{const M=(i.current.get(A)??0)+1;return i.current.set(A,M),M},l=(A,N)=>(i.current.get(A)??0)!==N;w.useEffect(()=>{try{const A=iTe();n({type:"HYDRATE_STATE",payload:A})}catch(A){t.error("Failed to load saved state",{error:A instanceof Error?A.message:"Unknown error"})}finally{s(!1)}},[t]),w.useEffect(()=>{r||aTe(e)},[e,r]);const u=A=>{if(A.type==="stdio")return!A.command||A.command.trim()===""?"Command is required for STDIO connections":null;if(!A.url||A.url.trim()==="")return"URL is required for HTTP connections";try{new URL(A.url)}catch(N){return`Invalid URL format: ${A.url} ${N}`}return null},d=w.useCallback(()=>{const A=Object.entries(e.servers).filter(([,N])=>N.connectionStatus==="connected").map(([N])=>N);n({type:"SET_MULTI_SELECTED",names:A})},[e.servers]),p=w.useCallback(async A=>{window.history.replaceState({},document.title,window.location.pathname);try{const N=await dq(A);if(N.success&&N.serverConfig&&N.serverName){const M=N.serverName;n({type:"CONNECT_REQUEST",name:M,config:N.serverConfig,select:!0});try{const I=await Ey(N.serverConfig,M);I.success?(n({type:"CONNECT_SUCCESS",name:M,config:N.serverConfig,tokens:si(M)}),t.info("OAuth connection successful",{serverName:M}),It.success(`OAuth connection successful! Connected to ${M}.`)):(n({type:"CONNECT_FAILURE",name:M,error:I.error||"Connection test failed after OAuth"}),t.error("OAuth connection test failed",{serverName:M,error:I.error}),It.error(`OAuth succeeded but connection test failed: ${I.error}`))}catch(I){const O=I instanceof Error?I.message:"Unknown connection error";n({type:"CONNECT_FAILURE",name:M,error:O}),t.error("OAuth connection test error",{serverName:M,error:O}),It.error(`OAuth succeeded but connection test failed: ${O}`)}}else throw new Error(N.error||"OAuth callback failed")}catch(N){const M=N instanceof Error?N.message:"Unknown error";It.error(`Error completing OAuth flow: ${M}`),t.error("OAuth callback failed",{error:M})}},[t]);w.useEffect(()=>{if(!r){const A=new URLSearchParams(window.location.search),N=A.get("code"),M=A.get("error");N?p(N):M&&(It.error(`OAuth authorization failed: ${M}`),localStorage.removeItem("mcp-oauth-pending"),window.history.replaceState({},document.title,window.location.pathname))}},[r,p]);const h=w.useCallback(async A=>{const N=u(A);if(N){It.error(N);return}const M=U1(A);n({type:"CONNECT_REQUEST",name:A.name,config:M,select:!0});const I=a(A.name);try{if(A.type==="http"&&A.useOAuth&&A.url){n({type:"UPSERT_SERVER",name:A.name,server:{name:A.name,config:M,lastConnectionTime:new Date,connectionStatus:"oauth-flow",retryCount:0,enabled:!0}});const{initiateOAuth:L}=await nTe(async()=>{const{initiateOAuth:V}=await Promise.resolve().then(()=>Gue);return{initiateOAuth:V}},void 0),z={serverName:A.name,serverUrl:A.url,clientId:A.clientId,clientSecret:A.clientSecret};A.oauthScopes&&A.oauthScopes.length>0&&(z.scopes=A.oauthScopes);const H=await L(z);if(H.success){if(H.serverConfig){const V=await Ey(H.serverConfig,A.name);if(l(A.name,I))return;V.success?(n({type:"CONNECT_SUCCESS",name:A.name,config:H.serverConfig,tokens:si(A.name)}),It.success("Connected successfully with OAuth!")):(n({type:"CONNECT_FAILURE",name:A.name,error:V.error||"OAuth connection test failed"}),It.error(`OAuth succeeded but connection failed: ${V.error}`))}else It.success("OAuth flow initiated. You will be redirected to authorize access.");return}else{if(l(A.name,I))return;n({type:"CONNECT_FAILURE",name:A.name,error:H.error||"OAuth initialization failed"}),It.error(`OAuth initialization failed: ${H.error}`);return}}const O=await Ey(M,A.name);if(l(A.name,I))return;O.success?(n({type:"CONNECT_SUCCESS",name:A.name,config:M}),t.info("Connection successful",{serverName:A.name}),It.success("Connected successfully!")):(n({type:"CONNECT_FAILURE",name:A.name,error:O.error||"Connection test failed"}),t.error("Connection failed",{serverName:A.name,error:O.error}),It.error(`Failed to connect to ${A.name}`))}catch(O){const L=O instanceof Error?O.message:"Unknown error";if(l(A.name,I))return;n({type:"CONNECT_FAILURE",name:A.name,error:L}),t.error("Connection failed",{serverName:A.name,error:L}),It.error(`Network error: ${L}`)}},[e.servers,t]),g=w.useRef(!1);w.useEffect(()=>{!r&&!g.current&&(g.current=!0,fetch("/api/mcp-cli-config").then(A=>A.json()).then(A=>{const N=A.config;if(N){if(N.servers&&Array.isArray(N.servers)){const M=N.autoConnectServer;t.info("Processing CLI-provided MCP servers (from config file)",{serverCount:N.servers.length,autoConnectServer:M||"all",cliConfig:N}),N.servers.forEach(I=>{const O={name:I.name||"CLI Server",type:I.type==="sse"?"http":I.type||"stdio",command:I.command,args:I.args||[],url:I.url,env:I.env||{}},L=U1(O);n({type:"UPSERT_SERVER",name:O.name,server:{name:O.name,config:L,lastConnectionTime:new Date,connectionStatus:"disconnected",retryCount:0,enabled:!1}}),!M||I.name===M?(t.info("Auto-connecting to server",{serverName:I.name}),h(O)):t.info("Skipping auto-connect for server",{serverName:I.name,reason:"filtered out"})});return}if(N.command){t.info("Auto-connecting to CLI-provided MCP server",{cliConfig:N});const M={name:N.name||"CLI Server",type:"stdio",command:N.command,args:N.args||[],env:N.env||{}};h(M)}}}).catch(A=>{t.debug("Could not fetch CLI config from API",{error:A})}))},[r,h,t,e.servers]);const v=w.useCallback(async A=>{const N=e.servers[A];return N?.oauthTokens&&N.oauthTokens.access_token||null},[e.servers]),x=w.useCallback(async A=>{t.info("Disconnecting from server",{serverName:A}),n({type:"DISCONNECT",name:A});try{const N=await oTe(A);N.success||n({type:"DISCONNECT",name:A,error:N.error})}catch(N){n({type:"DISCONNECT",name:A,error:N instanceof Error?N.message:"Unknown error"})}},[]),b=w.useCallback(async A=>{t.info("Removing server",{serverName:A}),nb(A),n({type:"REMOVE_SERVER",name:A})},[]),E=w.useCallback(async A=>{t.info("Reconnecting to server",{serverName:A});const N=e.servers[A];if(!N)throw new Error(`Server ${A} not found`);n({type:"RECONNECT_REQUEST",name:A});const M=a(A);try{const I=await uTe(N);if(I.kind==="redirect")return;if(I.kind==="error"){if(l(A,M))return;n({type:"CONNECT_FAILURE",name:A,error:I.error}),It.error(`Failed to connect: ${A}`);return}const O=await cTe(A,I.serverConfig);if(l(A,M))return;if(O.success)return n({type:"CONNECT_SUCCESS",name:A,config:I.serverConfig,tokens:I.tokens}),t.info("Reconnection successful",{serverName:A,result:O}),{success:!0};{n({type:"CONNECT_FAILURE",name:A,error:O.error||"Reconnection failed"}),t.error("Reconnection failed",{serverName:A,result:O});const L=O.error||`Failed to reconnect: ${A}`;It.error(L)}}catch(I){const O=I instanceof Error?I.message:"Unknown error";if(l(A,M))return;throw n({type:"CONNECT_FAILURE",name:A,error:O}),t.error("Reconnection failed",{serverName:A,error:O}),I}},[e.servers]);w.useEffect(()=>{if(r)return;(async()=>{try{const N=await lTe();N?.success&&N.servers&&n({type:"SYNC_AGENT_STATUS",servers:N.servers})}catch(N){t.debug("Failed to sync server status on startup",{error:N instanceof Error?N.message:"Unknown error"})}})()},[r,t]);const S=w.useCallback(A=>{n({type:"SELECT_SERVER",name:A})},[]),k=w.useCallback(A=>{n({type:"SET_MULTI_SELECTED",names:A})},[]),T=w.useCallback(A=>{n({type:"SET_MULTI_MODE",enabled:A})},[]),R=w.useCallback(A=>{const N=e.selectedMultipleServers,M=N.includes(A)?N.filter(I=>I!==A):[...N,A];n({type:"SET_MULTI_SELECTED",names:M})},[e.selectedMultipleServers]),j=w.useCallback(async(A,N)=>{const M=e.servers[A];if(M?.oauthTokens!=null&&N.useOAuth&&N.name===A&&N.type==="http"&&N.url===(M?.config).url?.toString()&&M){const L=U1(N);n({type:"CONNECT_REQUEST",name:A,config:L});try{if((await Ey(M.config,A)).success){n({type:"CONNECT_SUCCESS",name:A,config:L}),It.success("Server configuration updated successfully!");return}else console.warn("OAuth connection test failed, falling back to full reconnect")}catch(z){console.warn("OAuth connection test error, falling back to full reconnect",z)}}await x(A),await h(N),e.selectedServer===A&&N.name!==A&&S(N.name)},[e.servers,e.selectedServer,x,h]);return{appState:e,isLoading:r,connectedServerConfigs:e.servers,selectedServerEntry:e.servers[e.selectedServer],selectedMCPConfig:e.servers[e.selectedServer]?.config,selectedMCPConfigs:e.selectedMultipleServers.map(A=>e.servers[A]).filter(Boolean),selectedMCPConfigsMap:e.selectedMultipleServers.reduce((A,N)=>(e.servers[N]&&(A[N]=e.servers[N].config),A),{}),isMultiSelectMode:e.isMultiSelectMode,handleConnect:h,handleDisconnect:x,handleReconnect:E,handleUpdate:j,handleRemoveServer:b,setSelectedServer:S,setSelectedMCPConfigs:k,toggleMultiSelectMode:T,toggleServerSelection:R,getValidAccessToken:v,setSelectedMultipleServersToAllServers:d}}function dTe({server:t,selected:e,onToggle:n}){const[r,s]=w.useState(null),[i,a]=w.useState(!1),{label:l,Icon:u,iconClassName:d,indicatorColor:p}=TB(t.connectionStatus),h=AB(t.config),g=CB(t.config),v=JSON.stringify(t.config,null,2),x=()=>{n(t.name)},b=k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),x())},E=async(k,T,R)=>{k.stopPropagation();try{await navigator.clipboard.writeText(T),s(R),setTimeout(()=>s(null),2e3)}catch(j){console.error("Failed to copy text:",j)}},S=t.connectionStatus==="failed"?`${l} (${t.retryCount} retries)`:l;return f.jsxs(Ha,{role:"button",tabIndex:0,onClick:x,onKeyDown:b,className:Oe("relative gap-3 p-3 border border-border/40 bg-card/40 transition-colors","hover:border-border cursor-pointer",e&&"border-primary/60 ring-2 ring-primary/30"),children:[f.jsxs("div",{className:"flex items-start justify-between gap-2",children:[f.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[f.jsx("span",{"aria-hidden":!0,className:"h-2 w-2 flex-shrink-0 rounded-full",style:{backgroundColor:p}}),f.jsx("div",{className:"min-w-0",children:f.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[f.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:t.name}),f.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[f.jsx(u,{className:d}),f.jsx("span",{children:S})]})]})})]}),e&&f.jsxs(xr,{variant:"secondary",className:"h-5 px-1 text-[11px]",children:[f.jsx(Ri,{className:"mr-1 h-3 w-3"}),"Selected"]})]}),f.jsx("p",{className:"mt-0.5 text-[11px] uppercase tracking-wide text-muted-foreground",children:h}),f.jsxs("div",{className:"relative break-all rounded border border-border/30 bg-muted/30 p-1.5 font-mono text-[11px] text-muted-foreground",children:[f.jsx("div",{className:"pr-6",children:g}),f.jsx("button",{type:"button",onClick:k=>E(k,g,"command"),className:"absolute right-1 top-1 cursor-pointer p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:r==="command"?f.jsx(Ri,{className:"h-3 w-3 text-green-500"}):f.jsx(zo,{className:"h-3 w-3"})})]}),i&&f.jsxs("div",{className:"relative rounded border border-border/20 bg-muted/20 p-1.5 font-mono text-[11px] text-muted-foreground",children:[f.jsx("pre",{className:"max-h-40 overflow-auto pr-6 whitespace-pre-wrap",children:v}),f.jsx("button",{type:"button",onClick:k=>E(k,v,"config"),className:"absolute right-1 top-1 cursor-pointer p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:r==="config"?f.jsx(Ri,{className:"h-3 w-3 text-green-500"}):f.jsx(zo,{className:"h-3 w-3"})})]}),f.jsx("div",{className:"flex justify-end pt-0.5",children:f.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),a(T=>!T)},"aria-label":i?"Hide config":"Show config",className:"rounded-full border border-border/50 bg-background/70 p-1 text-muted-foreground transition-colors hover:text-foreground",children:i?f.jsx(_B,{className:"h-3 w-3"}):f.jsx(cc,{className:"h-3 w-3"})})})]})}const Z4="mcp-inspector-eval-runner-preferences",Tl=[{key:"servers",title:"Select Servers",description:"Choose the MCP servers to evaluate."},{key:"model",title:"Choose Model",description:"Pick the model and ensure credentials are ready."},{key:"tests",title:"Define Tests",description:"Author the scenarios you want to run or generate them with AI."},{key:"review",title:"Review & Run",description:"Confirm the configuration before launching the run."}],B1=(t,e)=>({title:"",query:"",runs:1,model:e?.id??"",provider:e?.provider??"",expectedToolCalls:[]});function fTe({availableModels:t,inline:e=!1}){const[n,r]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(!1),[u,d]=w.useState(0),[p,h]=w.useState(null),{isAuthenticated:g}=pa(),{getAccessToken:v}=Fi(),{appState:x}=k7(),{getToken:b,hasToken:E}=lR(),[S,k]=w.useState([]),[T,R]=w.useState(null),[j,A]=w.useState([B1(1,null)]),N=w.useMemo(()=>Object.entries(x.servers).filter(([,U])=>U.connectionStatus==="connected"),[x.servers]),M=w.useMemo(()=>new Set(N.map(([U])=>U)),[N]);w.useEffect(()=>{if(!(typeof window>"u"))try{const U=localStorage.getItem(Z4);if(!U)return;const J=JSON.parse(U);h({servers:J.servers??[],modelId:J.modelId??null})}catch(U){console.warn("Failed to load eval runner preferences",U)}},[]),w.useEffect(()=>{if(p&&p.servers?.length){const U=p.servers.filter(J=>M.has(J));U.length&&k(U)}},[p,M]),w.useEffect(()=>{if(t.length===0){R(null);return}if(p?.modelId){const U=t.find(J=>J.id===p.modelId);if(U){R(U);return}}R(U=>U&&t.some(oe=>oe.id===U.id)?U:t[0])},[t,p]),w.useEffect(()=>{if(!(typeof window>"u"))try{const U={servers:S,modelId:T?.id??null};localStorage.setItem(Z4,JSON.stringify(U))}catch(U){console.warn("Failed to persist eval runner preferences",U)}},[S,T]),w.useEffect(()=>{A(U=>T?U.map((J,oe)=>J.model===T.id&&J.provider===T.provider?J:{...J,model:T.id,provider:T.provider}):U)},[T]),w.useEffect(()=>{!e&&!n&&d(0)},[e,n]);const I=T?ra(T.id):!1,O=T?.provider,L=O?E(O):!1,z=w.useMemo(()=>j.filter(U=>U.query.trim().length>0),[j]),H=w.useMemo(()=>({servers:S.length>0,model:!!T&&(I||O&&L),tests:z.length>0}),[z.length,T,I,O,L,S.length]),V=w.useMemo(()=>H.servers?H.model?H.tests?3:2:1:0,[H]),X=w.useMemo(()=>{switch(u){case 0:return H.servers;case 1:return H.model;case 2:return H.tests;case 3:return H.tests&&H.servers&&H.model;default:return!1}},[u,H]),F=U=>{k(J=>J.includes(U)?J.filter(oe=>oe!==U):[...J,U])},W=U=>{A(J=>{const oe=J.length,pe=Array.from({length:U},(ye,je)=>B1(oe+je+1,T));return[...J,...pe]})},G=()=>{W(1)},ee=U=>{A(J=>J.filter((oe,pe)=>pe!==U))},P=(U,J,oe)=>{A(pe=>{const ye=[...pe];return ye[U]={...ye[U],[J]:oe},ye})},ie=async()=>{if(!g){It.error("Please sign in to generate tests");return}if(S.length===0){It.error("Please select at least one server");return}l(!0);try{const U=await v(),J=await fetch("/api/mcp/evals/generate-tests",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:S,convexAuthToken:U})}),oe=await J.json();if(!J.ok)throw new Error(oe.error||"Failed to generate tests");if(oe.tests&&oe.tests.length>0){const pe=oe.tests.map((ye,je)=>({title:ye.title||`Generated test ${je+1}`,query:ye.query||"",runs:Number(ye.runs)>0?Number(ye.runs):1,model:T?.id||"",provider:T?.provider||"",expectedToolCalls:Array.isArray(ye.expectedToolCalls)?ye.expectedToolCalls:[]}));A(pe),d(2),It.success(`Generated ${pe.length} test case(s).`)}}catch(U){console.error("Failed to generate tests:",U),It.error(U instanceof Error?U.message:"Failed to generate test cases")}finally{l(!1)}},ue=()=>{u>=Tl.length-1||X&&d(U=>Math.min(U+1,Tl.length-1))},D=()=>{u!==0&&d(U=>Math.max(U-1,0))},ne=async()=>{if(!g){It.error("Please sign in to run evals");return}if(S.length===0){It.error("Please select at least one server"),d(0);return}if(!T){It.error("Please select a model"),d(1);return}const U=ra(T.id),J=!U&&O?b(O):"";if(!U&&(!O||!J)){It.error(`Please configure your ${T.provider} API key in Settings`),d(1);return}if(z.length===0){It.error("Please add at least one test case with a query"),d(2);return}i(!0);try{const oe=await v(),pe=z.map(Ne=>({...Ne,model:T.id,provider:T.provider})),ye=await fetch("/api/mcp/evals/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tests:pe,serverIds:S,llmConfig:{provider:T.provider,apiKey:U?"router":J||"router"},convexAuthToken:oe})}),je=await ye.json();if(!ye.ok)throw new Error(je.error||"Failed to start evals");It.success(je.message||"Evals started successfully!"),A([B1(1,T)]),d(3),e||r(!1),window.location.hash="eval-results"}catch(oe){It.error(oe instanceof Error?oe.message:"Failed to start evals")}finally{i(!1)}},fe=()=>{switch(Tl[u].key){case"servers":return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Select servers to test"}),f.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Choose at least one connected MCP server. You can evaluate multiple servers in the same run."})]})}),N.length>0?f.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:N.map(([U,J])=>{const oe=S.includes(U);return f.jsx(dTe,{server:J,selected:oe,onToggle:F},U)})}):f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"No connected servers yet"}),f.jsx("p",{className:"mt-2",children:"Launch a server from the Servers tab to make it available here. Once connected, it will appear instantly."})]})]});case"model":return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Choose your evaluation model"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"For example, if you want to simulate using your server with Claude Desktop, select an Anthropic model."})]})}),t.length===0?f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"No models available"}),f.jsx("p",{className:"mt-2",children:"Connect a provider or enable MCPJam provided models in Settings to unlock model selection."})]}):T?f.jsxs("div",{className:"space-y-3",children:[f.jsx("div",{className:"flex items-center gap-3",children:f.jsx(w7,{currentModel:T,availableModels:t,onModelChange:R})}),!I&&!L&&O&&f.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/50 bg-destructive/5 p-3 text-sm",children:[f.jsx(Am,{className:"mt-0.5 h-4 w-4 text-destructive"}),f.jsxs("div",{children:[f.jsxs("p",{className:"font-medium text-destructive",children:["Add your ",T.provider," API key"]}),f.jsx("p",{className:"text-muted-foreground",children:"Configure credentials in Settings to run this model. Keys are stored locally and never sent to our servers."})]})]})]}):null]});case"tests":return f.jsxs("div",{className:"space-y-6",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs("div",{children:[f.jsx("h3",{className:"text-lg pb-2",children:"Define your test cases"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Create testing scenarios that simulate how real users would use your server."})]})}),!H.servers||!H.model?f.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[f.jsx("p",{className:"font-medium text-foreground",children:"Finish previous steps first"}),f.jsx("p",{className:"mt-2",children:"Select at least one server and choose a model to unlock test authoring. That ensures generated tests know which stack to target."})]}):f.jsxs(f.Fragment,{children:[f.jsx("div",{className:"flex flex-wrap items-center justify-between gap-2",children:f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Pe,{type:"button",variant:"outline",size:"lg",onClick:ie,disabled:a,children:[f.jsx("span",{className:"bg-gradient-to-r from-purple-600 via-violet-600 to-indigo-600 bg-clip-text text-transparent",children:a?"Generating...":"Generate tests"}),f.jsx(EB,{className:"h-4 w-4 ml-2 fill-purple-600"})]})})}),a&&f.jsx("div",{className:"flex items-center justify-center rounded-lg border p-6",children:f.jsx("div",{className:"text-center text-sm text-muted-foreground",children:"Generating test cases..."})}),!a&&f.jsxs("div",{className:"space-y-12",children:[j.map((U,J)=>f.jsxs("div",{className:"space-y-3 rounded-lg border bg-background p-4",children:[f.jsxs("div",{className:"flex items-start justify-between gap-3",children:[f.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),f.jsx(Dn,{className:"w-full",value:U.title,onChange:oe=>P(J,"title",oe.target.value),placeholder:"(Paypal) List transactions"})]}),j.length>1&&f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>ee(J),children:f.jsx(uc,{className:"h-4 w-4"})})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Query"}),f.jsx(Qo,{value:U.query,onChange:oe=>P(J,"query",oe.target.value),placeholder:"Can you find the most recent Paypal transactions, then create an invoice?",rows:3})]}),f.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),f.jsx(Dn,{type:"number",min:1,value:U.runs,onChange:oe=>P(J,"runs",Number(oe.target.value)>0?Number(oe.target.value):1)})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Xc,{className:"text-xs uppercase text-muted-foreground",children:"Expected tools (comma separated)"}),f.jsx(Dn,{value:U.expectedToolCalls.join(", "),onChange:oe=>P(J,"expectedToolCalls",oe.target.value.split(",").map(pe=>pe.trim()).filter(Boolean)),placeholder:"paypal_list_transactions, paypal_create_invoice"})]})]})]},J)),f.jsxs(Pe,{type:"button",variant:"outline",onClick:G,"aria-label":"Add test",className:"w-full",children:[f.jsx(Ax,{className:"h-4 w-4 mr-2"}),"Add test case"]})]})]})]});case"review":return f.jsxs("div",{className:"space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h3",{className:"text-lg",children:"Review your tests"}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"After confirming the run, you will see your run begin in the eval results tab."})]}),f.jsxs("div",{className:"space-y-4 rounded-lg border bg-background p-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Servers"}),f.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:S.map(U=>f.jsx(xr,{variant:"outline",children:U},U))})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(0),children:"Edit"})]}),f.jsx(Rk,{}),f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsxs("div",{children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Model"}),T?f.jsx("div",{className:"mt-2 flex items-center gap-2",children:f.jsx(xr,{variant:"outline",children:T.name})}):f.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No model selected"})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(1),children:"Edit"})]}),f.jsx(Rk,{}),f.jsxs("div",{className:"flex items-start justify-between gap-6",children:[f.jsxs("div",{className:"flex-1",children:[f.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Tests"}),f.jsx("div",{className:"mt-3 space-y-3",children:z.map((U,J)=>f.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[f.jsx("p",{className:"text-sm font-semibold text-foreground",children:U.title}),f.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:U.query}),f.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[f.jsxs("span",{children:[U.runs," run",U.runs===1?"":"s"]}),U.expectedToolCalls.length>0&&f.jsxs("span",{children:["Tools: ",U.expectedToolCalls.join(", ")]})]})]},J))})]}),f.jsx(Pe,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(2),children:"Edit"})]})]})]});default:return null}},q=f.jsx("ol",{className:"flex flex-col items-center gap-4 text-center md:flex-row md:gap-6",children:Tl.map((U,J)=>{const oe=u===J,pe=J<u&&J<=V,ye=J<=Math.max(V,u);return f.jsx("li",{className:"flex flex-col items-center gap-2",children:f.jsxs("button",{type:"button",onClick:()=>ye?d(J):void 0,disabled:!ye,className:Oe("flex flex-col items-center gap-2 transition",!ye&&"cursor-not-allowed opacity-60"),children:[f.jsx("span",{className:Oe("flex h-8 w-8 items-center justify-center rounded-full border text-sm font-medium",pe&&"border-primary bg-primary text-primary-foreground",oe&&!pe&&"border-primary bg-primary/10 text-primary",!oe&&!pe&&"border-border text-muted-foreground"),children:J+1}),f.jsx("span",{className:Oe("text-xs leading-tight",oe?"text-foreground":"text-muted-foreground"),children:U.title})]})},U.key)})}),K=u<Tl.length-1?!X:s||!X,Y=K?"secondary":"default",Z=f.jsxs("div",{className:Oe("mx-auto flex w-full flex-col gap-8 pb-10 pt-4",e?"max-w-none px-4 sm:px-6 md:px-12 lg:px-32":"max-w-3xl px-4"),children:[f.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.jsxs(Pe,{type:"button",variant:"outline",onClick:D,disabled:u===0,"aria-label":"Back",className:"justify-center gap-2",children:[f.jsx(ose,{className:"h-4 w-4"}),"Back"]}),f.jsx("div",{className:"flex flex-1 justify-center",children:f.jsx("div",{className:"max-w-xl",children:q})}),f.jsxs(Pe,{type:"button",variant:Y,onClick:()=>{u<Tl.length-1?ue():ne()},disabled:K,"aria-label":u===Tl.length-1?"Start":"Next",className:Oe("justify-center gap-2",!K&&"shadow-sm"),children:[u===Tl.length-1?"Start":"Next",f.jsx(la,{className:"h-4 w-4"})]})]}),f.jsx("div",{className:"space-y-6",children:fe()})]});return e?Z:f.jsxs(ua,{open:n,onOpenChange:r,children:[f.jsx(gN,{asChild:!0,children:f.jsxs(Pe,{children:[f.jsx(Ax,{className:"mr-2 h-4 w-4"}),"New eval run"]})}),f.jsxs(da,{className:"max-h-[80vh] w-full max-w-4xl overflow-y-auto sm:max-w-4xl",children:[f.jsxs(fa,{className:"mx-auto w-full max-w-3xl gap-1 text-left",children:[f.jsx(ha,{children:"Create eval run"}),f.jsx(nh,{children:"Follow the guided steps to configure your evaluation and run it with confidence."})]}),Z]})]})}function hTe(){const{isAuthenticated:t,isLoading:e}=pa(),{user:n}=Fi(),{availableModels:r}=xV({systemPrompt:"",temperature:1,selectedServers:[]});return e?f.jsx("div",{className:"p-6",children:f.jsx("div",{className:"flex h-64 items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!n?f.jsx("div",{className:"p-6",children:f.jsx(rh,{icon:wB,title:"Sign in to run evals",description:"Create an account or sign in to generate and launch evaluation runs.",className:"h-[calc(100vh-200px)]"})}):f.jsxs("div",{className:"space-y-6 p-6",children:[f.jsx("div",{className:"space-y-2",children:f.jsx("h1",{className:"text-2xl font-semibold",children:"Evaluation runner"})}),f.jsx("div",{className:"w-full",children:f.jsx(fTe,{availableModels:r,inline:!0})})]})}function pTe({config:t,isConfigured:e,onEdit:n,onDelete:r}){const s=t.description?.trim();return f.jsxs(Ha,{className:Oe("group h-full gap-4 border bg-card px-6 py-6 transition-all hover:border-primary/40 hover:shadow-md dark:hover:shadow-xl",e?"border-green-200/80 dark:border-green-400/30":"border-border/60"),children:[f.jsxs("div",{className:"flex items-start justify-between gap-6",children:[f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("img",{src:t.logo,alt:t.logoAlt,className:"size-6 object-contain"}),f.jsxs("div",{className:"",children:[f.jsxs("h3",{className:"text-md font-semibold text-foreground pb-1",children:[t.name," ",e&&f.jsx("span",{className:"text-md",children:"✔️"})]}),s?f.jsx("p",{className:"line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})]}),e?f.jsxs(m0,{children:[f.jsx(g0,{asChild:!0,children:f.jsx(Pe,{size:"icon",variant:"ghost",className:"size-8 rounded-md border border-transparent hover:bg-muted/50",children:f.jsx(jse,{className:"size-4"})})}),f.jsx(v0,{align:"end",className:"w-44",children:f.jsx(Ro,{variant:"destructive",onClick:()=>r(t.id),children:"Remove provider"})})]}):null]}),f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{size:"sm",variant:e?"outline":"secondary",className:"w-full",onClick:()=>n(t.id),children:e?"Manage":"Configure"})})]})}function mTe({baseUrl:t,onEdit:e}){const n=!!t;return f.jsxs(Ha,{className:Oe("group h-full gap-4 border bg-card px-6 py-6 transition-all hover:border-primary/40 hover:shadow-md dark:hover:shadow-xl",n?"border-green-200/80 dark:border-green-400/30":"border-border/60"),children:[f.jsx("div",{className:"flex items-start justify-between gap-6",children:f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"size-6 object-contain"}),f.jsxs("div",{className:"",children:[f.jsxs("h3",{className:"text-md font-semibold text-foreground pb-1",children:["Ollama ",n&&f.jsx("span",{className:"text-md",children:"✔️"})]}),f.jsx("p",{className:"line-clamp-2 text-xs leading-relaxed text-muted-foreground",children:n?"Local models available":"Install and connect Ollama locally"})]})]})}),f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{size:"sm",variant:n?"outline":"secondary",className:"w-full",onClick:e,children:n?"Manage":"Configure"})})]})}function gTe({providerConfigs:t,hasToken:e,onEditProvider:n,onDeleteProvider:r,ollamaBaseUrl:s,onEditOllama:i}){return f.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[t.map(a=>{const l=e(a.id);return f.jsx(pTe,{config:a,isConfigured:l,onEdit:n,onDelete:r},a.id)}),f.jsx(mTe,{baseUrl:s,onEdit:i})]})}function vTe({open:t,onOpenChange:e,provider:n,value:r,onValueChange:s,onSave:i,onCancel:a}){const l=Qr();return f.jsx(ua,{open:t,onOpenChange:e,children:f.jsxs(da,{className:"max-w-md",children:[f.jsx(fa,{children:f.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n&&f.jsx("div",{className:"w-12 h-12 rounded-lg bg-white p-2 border",children:f.jsx("img",{src:n.logo,alt:n.logoAlt,className:"w-full h-full object-contain"})}),f.jsxs("div",{children:[f.jsxs(ha,{className:"text-left",children:["Configure ",n?.name]}),f.jsx(nh,{className:"text-left",children:n?.description})]})]})}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{htmlFor:"api-key",className:"text-sm font-medium",children:"API Key"}),f.jsx(Dn,{id:"api-key",type:"password",value:r,onChange:u=>s(u.target.value),placeholder:n?.placeholder,className:"mt-1"})]}),f.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-lg",children:[f.jsx(tN,{className:"w-4 h-4 text-blue-600"}),f.jsxs("span",{className:"text-sm text-blue-600",children:["Need an API key?"," ",f.jsx("button",{onClick:()=>n&&window.open(n.getApiKeyUrl,"_blank"),className:"underline hover:no-underline",children:"Get one here"})]})]})]}),f.jsxs(S0,{children:[f.jsx(Pe,{variant:"outline",onClick:a,children:"Cancel"}),f.jsx(Pe,{onClick:()=>{l.capture("save_api_key",{location:"provider_config_dialog",platform:on(),environment:void 0}),i()},disabled:!r.trim(),children:"Save API Key"})]})]})})}function yTe({open:t,onOpenChange:e,value:n,onValueChange:r,onSave:s,onCancel:i}){return f.jsx(ua,{open:t,onOpenChange:e,children:f.jsxs(da,{className:"max-w-md",children:[f.jsx(fa,{children:f.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[f.jsx("div",{className:"w-12 h-12 rounded-lg bg-white p-2 border",children:f.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"w-full h-full object-contain"})}),f.jsxs("div",{children:[f.jsx(ha,{className:"text-left pb-2",children:"Configure Ollama URL"}),f.jsx(nh,{className:"text-left",children:"Set the base URL for your Ollama instance"})]})]})}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx("label",{htmlFor:"ollama-url",className:"text-sm font-medium",children:"Base URL"}),f.jsx(Dn,{id:"ollama-url",type:"url",value:n,onChange:a=>r(a.target.value),placeholder:"http://localhost:11434/api",className:"mt-1"})]}),f.jsxs("div",{className:"flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-lg",children:[f.jsx(tN,{className:"w-4 h-4 text-blue-600"}),f.jsxs("span",{className:"text-sm text-blue-600",children:["Need help?"," ",f.jsx("button",{onClick:()=>window.open("https://ollama.ai/download","_blank"),className:"underline hover:no-underline",children:"Download Ollama"})]})]})]}),f.jsxs(S0,{children:[f.jsx(Pe,{variant:"outline",onClick:i,children:"Cancel"}),f.jsx(Pe,{onClick:s,disabled:!n.trim(),children:"Save URL"})]})]})})}function xTe({...t}){return f.jsx(IJ,{"data-slot":"alert-dialog",...t})}function bTe({...t}){return f.jsx(DJ,{"data-slot":"alert-dialog-trigger",...t})}function _Te({...t}){return f.jsx(LJ,{"data-slot":"alert-dialog-portal",...t})}function wTe({className:t,...e}){return f.jsx($J,{"data-slot":"alert-dialog-overlay",className:Oe("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",t),...e})}function STe({className:t,...e}){return f.jsxs(_Te,{children:[f.jsx(wTe,{}),f.jsx(zJ,{"data-slot":"alert-dialog-content",className:Oe("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",t),...e})]})}function ETe({className:t,...e}){return f.jsx("div",{"data-slot":"alert-dialog-header",className:Oe("flex flex-col gap-2 text-center sm:text-left",t),...e})}function kTe({className:t,...e}){return f.jsx("div",{"data-slot":"alert-dialog-footer",className:Oe("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",t),...e})}function TTe({className:t,...e}){return f.jsx(BJ,{"data-slot":"alert-dialog-title",className:Oe("text-lg font-semibold",t),...e})}function CTe({className:t,...e}){return f.jsx(qJ,{"data-slot":"alert-dialog-description",className:Oe("text-muted-foreground text-sm",t),...e})}function ATe({className:t,...e}){return f.jsx(FJ,{className:Oe(eN(),t),...e})}function NTe({className:t,...e}){return f.jsx(UJ,{className:Oe(eN({variant:"outline"}),t),...e})}function bn(t){const e=Object.prototype.toString.call(t);return t instanceof Date||typeof t=="object"&&e==="[object Date]"?new t.constructor(+t):typeof t=="number"||e==="[object Number]"||typeof t=="string"||e==="[object String]"?new Date(t):new Date(NaN)}function tc(t,e){return t instanceof Date?new t.constructor(e):new Date(e)}const T7=6048e5,RTe=864e5,C7=6e4,A7=36e5,ky=43200,e$=1440;let jTe={};function Rg(){return jTe}function Zm(t,e){const n=Rg(),r=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??n.weekStartsOn??n.locale?.options?.weekStartsOn??0,s=bn(t),i=s.getDay(),a=(i<r?7:0)+i-r;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function kb(t){return Zm(t,{weekStartsOn:1})}function N7(t){const e=bn(t),n=e.getFullYear(),r=tc(t,0);r.setFullYear(n+1,0,4),r.setHours(0,0,0,0);const s=kb(r),i=tc(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const a=kb(i);return e.getTime()>=s.getTime()?n+1:e.getTime()>=a.getTime()?n:n-1}function t$(t){const e=bn(t);return e.setHours(0,0,0,0),e}function Tb(t){const e=bn(t),n=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return n.setUTCFullYear(e.getFullYear()),+t-+n}function MTe(t,e){const n=t$(t),r=t$(e),s=+n-Tb(n),i=+r-Tb(r);return Math.round((s-i)/RTe)}function OTe(t){const e=N7(t),n=tc(t,0);return n.setFullYear(e,0,4),n.setHours(0,0,0,0),kb(n)}function lx(t,e){const n=bn(t),r=bn(e),s=n.getTime()-r.getTime();return s<0?-1:s>0?1:s}function PTe(t){return tc(t,Date.now())}function ITe(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function DTe(t){if(!ITe(t)&&typeof t!="number")return!1;const e=bn(t);return!isNaN(Number(e))}function LTe(t,e){const n=bn(t),r=bn(e),s=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return s*12+i}function $Te(t){return e=>{const r=(t?Math[t]:Math.trunc)(e);return r===0?0:r}}function zTe(t,e){return+bn(t)-+bn(e)}function FTe(t){const e=bn(t);return e.setHours(23,59,59,999),e}function UTe(t){const e=bn(t),n=e.getMonth();return e.setFullYear(e.getFullYear(),n+1,0),e.setHours(23,59,59,999),e}function BTe(t){const e=bn(t);return+FTe(e)==+UTe(e)}function qTe(t,e){const n=bn(t),r=bn(e),s=lx(n,r),i=Math.abs(LTe(n,r));let a;if(i<1)a=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-s*i);let l=lx(n,r)===-s;BTe(bn(t))&&i===1&&lx(t,r)===1&&(l=!1),a=s*(i-Number(l))}return a===0?0:a}function VTe(t,e,n){const r=zTe(t,e)/1e3;return $Te(n?.roundingMethod)(r)}function HTe(t){const e=bn(t),n=tc(t,0);return n.setFullYear(e.getFullYear(),0,1),n.setHours(0,0,0,0),n}const GTe={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},WTe=(t,e,n)=>{let r;const s=GTe[t];return typeof s=="string"?r=s:e===1?r=s.one:r=s.other.replace("{{count}}",e.toString()),n?.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function q1(t){return(e={})=>{const n=e.width?String(e.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const YTe={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},KTe={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},XTe={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},QTe={date:q1({formats:YTe,defaultWidth:"full"}),time:q1({formats:KTe,defaultWidth:"full"}),dateTime:q1({formats:XTe,defaultWidth:"full"})},JTe={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},ZTe=(t,e,n,r)=>JTe[t];function Cp(t){return(e,n)=>{const r=n?.context?String(n.context):"standalone";let s;if(r==="formatting"&&t.formattingValues){const a=t.defaultFormattingWidth||t.defaultWidth,l=n?.width?String(n.width):a;s=t.formattingValues[l]||t.formattingValues[a]}else{const a=t.defaultWidth,l=n?.width?String(n.width):t.defaultWidth;s=t.values[l]||t.values[a]}const i=t.argumentCallback?t.argumentCallback(e):e;return s[i]}}const eCe={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},tCe={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},nCe={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},rCe={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},sCe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},iCe={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},aCe=(t,e)=>{const n=Number(t),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},oCe={ordinalNumber:aCe,era:Cp({values:eCe,defaultWidth:"wide"}),quarter:Cp({values:tCe,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Cp({values:nCe,defaultWidth:"wide"}),day:Cp({values:rCe,defaultWidth:"wide"}),dayPeriod:Cp({values:sCe,defaultWidth:"wide",formattingValues:iCe,defaultFormattingWidth:"wide"})};function Ap(t){return(e,n={})=>{const r=n.width,s=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],i=e.match(s);if(!i)return null;const a=i[0],l=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],u=Array.isArray(l)?cCe(l,h=>h.test(a)):lCe(l,h=>h.test(a));let d;d=t.valueCallback?t.valueCallback(u):u,d=n.valueCallback?n.valueCallback(d):d;const p=e.slice(a.length);return{value:d,rest:p}}}function lCe(t,e){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return n}function cCe(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n}function uCe(t){return(e,n={})=>{const r=e.match(t.matchPattern);if(!r)return null;const s=r[0],i=e.match(t.parsePattern);if(!i)return null;let a=t.valueCallback?t.valueCallback(i[0]):i[0];a=n.valueCallback?n.valueCallback(a):a;const l=e.slice(s.length);return{value:a,rest:l}}}const dCe=/^(\d+)(th|st|nd|rd)?/i,fCe=/\d+/i,hCe={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},pCe={any:[/^b/i,/^(a|c)/i]},mCe={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},gCe={any:[/1/i,/2/i,/3/i,/4/i]},vCe={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},yCe={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},xCe={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},bCe={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},_Ce={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},wCe={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},SCe={ordinalNumber:uCe({matchPattern:dCe,parsePattern:fCe,valueCallback:t=>parseInt(t,10)}),era:Ap({matchPatterns:hCe,defaultMatchWidth:"wide",parsePatterns:pCe,defaultParseWidth:"any"}),quarter:Ap({matchPatterns:mCe,defaultMatchWidth:"wide",parsePatterns:gCe,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Ap({matchPatterns:vCe,defaultMatchWidth:"wide",parsePatterns:yCe,defaultParseWidth:"any"}),day:Ap({matchPatterns:xCe,defaultMatchWidth:"wide",parsePatterns:bCe,defaultParseWidth:"any"}),dayPeriod:Ap({matchPatterns:_Ce,defaultMatchWidth:"any",parsePatterns:wCe,defaultParseWidth:"any"})},R7={code:"en-US",formatDistance:WTe,formatLong:QTe,formatRelative:ZTe,localize:oCe,match:SCe,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ECe(t){const e=bn(t);return MTe(e,HTe(e))+1}function kCe(t){const e=bn(t),n=+kb(e)-+OTe(e);return Math.round(n/T7)+1}function j7(t,e){const n=bn(t),r=n.getFullYear(),s=Rg(),i=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??s.firstWeekContainsDate??s.locale?.options?.firstWeekContainsDate??1,a=tc(t,0);a.setFullYear(r+1,0,i),a.setHours(0,0,0,0);const l=Zm(a,e),u=tc(t,0);u.setFullYear(r,0,i),u.setHours(0,0,0,0);const d=Zm(u,e);return n.getTime()>=l.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function TCe(t,e){const n=Rg(),r=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??n.firstWeekContainsDate??n.locale?.options?.firstWeekContainsDate??1,s=j7(t,e),i=tc(t,0);return i.setFullYear(s,0,r),i.setHours(0,0,0,0),Zm(i,e)}function CCe(t,e){const n=bn(t),r=+Zm(n,e)-+TCe(n,e);return Math.round(r/T7)+1}function dn(t,e){const n=t<0?"-":"",r=Math.abs(t).toString().padStart(e,"0");return n+r}const Cl={y(t,e){const n=t.getFullYear(),r=n>0?n:1-n;return dn(e==="yy"?r%100:r,e.length)},M(t,e){const n=t.getMonth();return e==="M"?String(n+1):dn(n+1,2)},d(t,e){return dn(t.getDate(),e.length)},a(t,e){const n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(t,e){return dn(t.getHours()%12||12,e.length)},H(t,e){return dn(t.getHours(),e.length)},m(t,e){return dn(t.getMinutes(),e.length)},s(t,e){return dn(t.getSeconds(),e.length)},S(t,e){const n=e.length,r=t.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return dn(s,e.length)}},jd={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},n$={G:function(t,e,n){const r=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(t,e,n){if(e==="yo"){const r=t.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return Cl.y(t,e)},Y:function(t,e,n,r){const s=j7(t,r),i=s>0?s:1-s;if(e==="YY"){const a=i%100;return dn(a,2)}return e==="Yo"?n.ordinalNumber(i,{unit:"year"}):dn(i,e.length)},R:function(t,e){const n=N7(t);return dn(n,e.length)},u:function(t,e){const n=t.getFullYear();return dn(n,e.length)},Q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return dn(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return dn(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(t,e,n){const r=t.getMonth();switch(e){case"M":case"MM":return Cl.M(t,e);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(t,e,n){const r=t.getMonth();switch(e){case"L":return String(r+1);case"LL":return dn(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(t,e,n,r){const s=CCe(t,r);return e==="wo"?n.ordinalNumber(s,{unit:"week"}):dn(s,e.length)},I:function(t,e,n){const r=kCe(t);return e==="Io"?n.ordinalNumber(r,{unit:"week"}):dn(r,e.length)},d:function(t,e,n){return e==="do"?n.ordinalNumber(t.getDate(),{unit:"date"}):Cl.d(t,e)},D:function(t,e,n){const r=ECe(t);return e==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):dn(r,e.length)},E:function(t,e,n){const r=t.getDay();switch(e){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(t,e,n,r){const s=t.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(i);case"ee":return dn(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(t,e,n,r){const s=t.getDay(),i=(s-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(i);case"cc":return dn(i,e.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(t,e,n){const r=t.getDay(),s=r===0?7:r;switch(e){case"i":return String(s);case"ii":return dn(s,e.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(t,e,n){const s=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(t,e,n){const r=t.getHours();let s;switch(r===12?s=jd.noon:r===0?s=jd.midnight:s=r/12>=1?"pm":"am",e){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(t,e,n){const r=t.getHours();let s;switch(r>=17?s=jd.evening:r>=12?s=jd.afternoon:r>=4?s=jd.morning:s=jd.night,e){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(t,e,n){if(e==="ho"){let r=t.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Cl.h(t,e)},H:function(t,e,n){return e==="Ho"?n.ordinalNumber(t.getHours(),{unit:"hour"}):Cl.H(t,e)},K:function(t,e,n){const r=t.getHours()%12;return e==="Ko"?n.ordinalNumber(r,{unit:"hour"}):dn(r,e.length)},k:function(t,e,n){let r=t.getHours();return r===0&&(r=24),e==="ko"?n.ordinalNumber(r,{unit:"hour"}):dn(r,e.length)},m:function(t,e,n){return e==="mo"?n.ordinalNumber(t.getMinutes(),{unit:"minute"}):Cl.m(t,e)},s:function(t,e,n){return e==="so"?n.ordinalNumber(t.getSeconds(),{unit:"second"}):Cl.s(t,e)},S:function(t,e){return Cl.S(t,e)},X:function(t,e,n){const r=t.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return s$(r);case"XXXX":case"XX":return Yc(r);case"XXXXX":case"XXX":default:return Yc(r,":")}},x:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"x":return s$(r);case"xxxx":case"xx":return Yc(r);case"xxxxx":case"xxx":default:return Yc(r,":")}},O:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+r$(r,":");case"OOOO":default:return"GMT"+Yc(r,":")}},z:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+r$(r,":");case"zzzz":default:return"GMT"+Yc(r,":")}},t:function(t,e,n){const r=Math.trunc(t.getTime()/1e3);return dn(r,e.length)},T:function(t,e,n){const r=t.getTime();return dn(r,e.length)}};function r$(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=Math.trunc(r/60),i=r%60;return i===0?n+String(s):n+String(s)+e+dn(i,2)}function s$(t,e){return t%60===0?(t>0?"-":"+")+dn(Math.abs(t)/60,2):Yc(t,e)}function Yc(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=dn(Math.trunc(r/60),2),i=dn(r%60,2);return n+s+e+i}const i$=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},M7=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},ACe=(t,e)=>{const n=t.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return i$(t,e);let i;switch(r){case"P":i=e.dateTime({width:"short"});break;case"PP":i=e.dateTime({width:"medium"});break;case"PPP":i=e.dateTime({width:"long"});break;case"PPPP":default:i=e.dateTime({width:"full"});break}return i.replace("{{date}}",i$(r,e)).replace("{{time}}",M7(s,e))},NCe={p:M7,P:ACe},RCe=/^D+$/,jCe=/^Y+$/,MCe=["D","DD","YY","YYYY"];function OCe(t){return RCe.test(t)}function PCe(t){return jCe.test(t)}function ICe(t,e,n){const r=DCe(t,e,n);if(console.warn(r),MCe.includes(t))throw new RangeError(r)}function DCe(t,e,n){const r=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const LCe=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$Ce=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,zCe=/^'([^]*?)'?$/,FCe=/''/g,UCe=/[a-zA-Z]/;function O7(t,e,n){const r=Rg(),s=r.locale??R7,i=r.firstWeekContainsDate??r.locale?.options?.firstWeekContainsDate??1,a=r.weekStartsOn??r.locale?.options?.weekStartsOn??0,l=bn(t);if(!DTe(l))throw new RangeError("Invalid time value");let u=e.match($Ce).map(p=>{const h=p[0];if(h==="p"||h==="P"){const g=NCe[h];return g(p,s.formatLong)}return p}).join("").match(LCe).map(p=>{if(p==="''")return{isToken:!1,value:"'"};const h=p[0];if(h==="'")return{isToken:!1,value:BCe(p)};if(n$[h])return{isToken:!0,value:p};if(h.match(UCe))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:p}});s.localize.preprocessor&&(u=s.localize.preprocessor(l,u));const d={firstWeekContainsDate:i,weekStartsOn:a,locale:s};return u.map(p=>{if(!p.isToken)return p.value;const h=p.value;(PCe(h)||OCe(h))&&ICe(h,e,String(t));const g=n$[h[0]];return g(l,h,s.localize,d)}).join("")}function BCe(t){const e=t.match(zCe);return e?e[1].replace(FCe,"'"):t}function qCe(t,e,n){const r=Rg(),s=n?.locale??r.locale??R7,i=2520,a=lx(t,e);if(isNaN(a))throw new RangeError("Invalid time value");const l=Object.assign({},n,{addSuffix:n?.addSuffix,comparison:a});let u,d;a>0?(u=bn(e),d=bn(t)):(u=bn(t),d=bn(e));const p=VTe(d,u),h=(Tb(d)-Tb(u))/1e3,g=Math.round((p-h)/60);let v;if(g<2)return n?.includeSeconds?p<5?s.formatDistance("lessThanXSeconds",5,l):p<10?s.formatDistance("lessThanXSeconds",10,l):p<20?s.formatDistance("lessThanXSeconds",20,l):p<40?s.formatDistance("halfAMinute",0,l):p<60?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",1,l):g===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",g,l);if(g<45)return s.formatDistance("xMinutes",g,l);if(g<90)return s.formatDistance("aboutXHours",1,l);if(g<e$){const x=Math.round(g/60);return s.formatDistance("aboutXHours",x,l)}else{if(g<i)return s.formatDistance("xDays",1,l);if(g<ky){const x=Math.round(g/e$);return s.formatDistance("xDays",x,l)}else if(g<ky*2)return v=Math.round(g/ky),s.formatDistance("aboutXMonths",v,l)}if(v=qTe(d,u),v<12){const x=Math.round(g/ky);return s.formatDistance("xMonths",x,l)}else{const x=v%12,b=Math.trunc(v/12);return x<3?s.formatDistance("aboutXYears",b,l):x<9?s.formatDistance("overXYears",b,l):s.formatDistance("almostXYears",b+1,l)}}function VCe(t,e){return qCe(t,PTe(t),e)}function HCe(t,e){const r=KCe(t);let s;if(r.date){const u=XCe(r.date,2);s=QCe(u.restDateString,u.year)}if(!s||isNaN(s.getTime()))return new Date(NaN);const i=s.getTime();let a=0,l;if(r.time&&(a=JCe(r.time),isNaN(a)))return new Date(NaN);if(r.timezone){if(l=ZCe(r.timezone),isNaN(l))return new Date(NaN)}else{const u=new Date(i+a),d=new Date(0);return d.setFullYear(u.getUTCFullYear(),u.getUTCMonth(),u.getUTCDate()),d.setHours(u.getUTCHours(),u.getUTCMinutes(),u.getUTCSeconds(),u.getUTCMilliseconds()),d}return new Date(i+a+l)}const Ty={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},GCe=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,WCe=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,YCe=/^([+-])(\d{2})(?::?(\d{2}))?$/;function KCe(t){const e={},n=t.split(Ty.dateTimeDelimiter);let r;if(n.length>2)return e;if(/:/.test(n[0])?r=n[0]:(e.date=n[0],r=n[1],Ty.timeZoneDelimiter.test(e.date)&&(e.date=t.split(Ty.timeZoneDelimiter)[0],r=t.substr(e.date.length,t.length))),r){const s=Ty.timezone.exec(r);s?(e.time=r.replace(s[1],""),e.timezone=s[1]):e.time=r}return e}function XCe(t,e){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+e)+"})|(\\d{2}|[+-]\\d{"+(2+e)+"})$)"),r=t.match(n);if(!r)return{year:NaN,restDateString:""};const s=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?s:i*100,restDateString:t.slice((r[1]||r[2]).length)}}function QCe(t,e){if(e===null)return new Date(NaN);const n=t.match(GCe);if(!n)return new Date(NaN);const r=!!n[4],s=Np(n[1]),i=Np(n[2])-1,a=Np(n[3]),l=Np(n[4]),u=Np(n[5])-1;if(r)return sAe(e,l,u)?eAe(e,l,u):new Date(NaN);{const d=new Date(0);return!nAe(e,i,a)||!rAe(e,s)?new Date(NaN):(d.setUTCFullYear(e,i,Math.max(s,a)),d)}}function Np(t){return t?parseInt(t):1}function JCe(t){const e=t.match(WCe);if(!e)return NaN;const n=V1(e[1]),r=V1(e[2]),s=V1(e[3]);return iAe(n,r,s)?n*A7+r*C7+s*1e3:NaN}function V1(t){return t&&parseFloat(t.replace(",","."))||0}function ZCe(t){if(t==="Z")return 0;const e=t.match(YCe);if(!e)return 0;const n=e[1]==="+"?-1:1,r=parseInt(e[2]),s=e[3]&&parseInt(e[3])||0;return aAe(r,s)?n*(r*A7+s*C7):NaN}function eAe(t,e,n){const r=new Date(0);r.setUTCFullYear(t,0,4);const s=r.getUTCDay()||7,i=(e-1)*7+n+1-s;return r.setUTCDate(r.getUTCDate()+i),r}const tAe=[31,null,31,30,31,30,31,31,30,31,30,31];function P7(t){return t%400===0||t%4===0&&t%100!==0}function nAe(t,e,n){return e>=0&&e<=11&&n>=1&&n<=(tAe[e]||(P7(t)?29:28))}function rAe(t,e){return e>=1&&e<=(P7(t)?366:365)}function sAe(t,e,n){return e>=1&&e<=53&&n>=0&&n<=6}function iAe(t,e,n){return t===24?e===0&&n===0:n>=0&&n<60&&e>=0&&e<60&&t>=0&&t<25}function aAe(t,e){return e>=0&&e<=59}function a$({value:t,isCopied:e,onCopy:n,copyLabel:r,tooltip:s="Copy to clipboard"}){return f.jsxs("div",{className:"relative w-full",children:[f.jsx(Dn,{readOnly:!0,value:t,className:"h-12 w-full rounded-lg border border-border/40 bg-background/50 font-mono text-sm tracking-wide text-foreground pr-16 shadow-sm focus-visible:border-primary focus-visible:ring-1 focus-visible:ring-primary/20",style:{fontFamily:'ui-monospace, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace'}}),f.jsxs(Ia,{children:[f.jsx(Da,{asChild:!0,children:f.jsx(Pe,{type:"button",variant:"ghost",onClick:n,className:"absolute right-3 top-3 h-6 w-6 p-0 rounded-md border-0 bg-transparent text-foreground/60 hover:text-foreground hover:bg-foreground/10 transition-all duration-200",children:e?f.jsx(Ri,{className:"h-4 w-4"}):f.jsx(zo,{className:"h-4 w-4"})})}),f.jsx(La,{side:"bottom",children:s})]})]})}function oAe(){const[t,e]=w.useState(null),[n,r]=w.useState(!1),[s,i]=w.useState(!1),[a,l]=w.useState(!1),[u,d]=w.useState(!1),{isAuthenticated:p,isLoading:h}=pa(),{signIn:g}=Fi(),v=Qr(),x=Eb("apiKeys:list"),b=b7("apiKeys:regenerateAndGet"),E=async()=>{if(t)try{await navigator.clipboard.writeText(t),i(!0),setTimeout(()=>i(!1),2e3)}catch(R){console.error("Clipboard error",R)}},S=async()=>{if(!p)return!1;try{r(!0),i(!1);const R=await b();return e(R.apiKey),d(!0),!0}catch(R){return console.error("Failed to generate key",R),!1}finally{r(!1)}};if(h)return f.jsx("div",{className:"rounded-md border p-3 text-sm text-muted-foreground",children:"Checking authentication…"});if(!p)return f.jsxs("div",{className:"space-y-3 rounded-md border p-4",children:[f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("h3",{className:"text-lg font-semibold",children:"MCPJam API Key"})}),f.jsx("p",{className:"text-sm text-muted-foreground",children:"Sign in to view and manage your API key."}),f.jsx(Pe,{type:"button",onClick:()=>{v.capture("login_button_clicked",{location:"account_api_key_section",platform:on(),environment:void 0}),g()},size:"sm",children:"Sign in"})]});const k=x&&x.length>0?x[0]:null,T=(R,j="Never")=>{if(!R)return j;const A=new Date(R),N=VCe(A,{addSuffix:!0});return`${O7(A,"PP p")} · ${N}`};return f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("h3",{className:"text-lg font-semibold",children:"MCPJam API Key"})}),x===void 0?f.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading API key status…"}):t?f.jsxs("div",{className:"space-y-4",children:[f.jsx("p",{className:"text-sm text-muted-foreground leading-relaxed",children:"Copy and save this key now. You won't be able to view it again later."}),f.jsx(a$,{value:t,isCopied:s,onCopy:E,copyLabel:"Copy key"})]}):(x?.length??0)===0?f.jsx("div",{className:"space-y-4",children:f.jsx(Pe,{type:"button",onClick:()=>{S()},disabled:n,children:n?"Generating…":"Generate API key"})}):f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{className:"flex items-center justify-between",children:f.jsxs(xTe,{open:a,onOpenChange:l,children:[f.jsx(bTe,{asChild:!0,children:f.jsxs(Pe,{type:"button",variant:"outline",disabled:n,className:"inline-flex items-center gap-2.5 rounded-lg border border-border/50 bg-background px-4 py-2.5 text-sm font-medium text-foreground/80 hover:border-border hover:bg-background/80 hover:text-foreground transition-all duration-200",children:[f.jsx(or,{className:`h-4 w-4 ${n?"animate-spin":""} text-foreground/60`}),f.jsx("span",{children:n?"Regenerating…":"Regenerate"})]})}),f.jsxs(STe,{children:[f.jsxs(ETe,{children:[f.jsx(TTe,{className:"text-lg font-semibold",children:"Confirm"}),f.jsx(CTe,{className:"text-sm text-muted-foreground leading-relaxed",children:"Regenerating an API key will replace your previous API key."})]}),f.jsxs(kTe,{className:"gap-3",children:[f.jsx(NTe,{disabled:n,className:"font-medium",children:"Cancel"}),f.jsx(ATe,{onClick:async R=>{R.preventDefault(),await S()&&l(!1)},disabled:n,className:"font-medium",children:n?"Regenerating…":"Regenerate"})]})]})]})}),k?f.jsx("div",{className:"rounded-lg border border-border/30 bg-background/50 p-4",children:f.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[f.jsxs("div",{className:"flex flex-col gap-0.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground/50 uppercase tracking-wide",children:"Created"}),f.jsx("span",{className:"text-xs text-foreground/70",children:T(k.createdAt)})]}),f.jsxs("div",{className:"flex flex-col gap-0.5",children:[f.jsx("span",{className:"text-xs font-medium text-foreground/50 uppercase tracking-wide",children:"Last Used"}),f.jsx("span",{className:"text-xs text-foreground/70",children:T(k.lastUsedAt,"Never used")})]})]})}):null]}),f.jsx(ua,{open:!!t&&u,onOpenChange:R=>{R||i(!1),d(R)},children:f.jsxs(da,{children:[f.jsxs(fa,{children:[f.jsx(ha,{children:"API Key"}),f.jsx(nh,{children:"Copy and store this key securely. You will not be able to view it again."})]}),f.jsx(a$,{value:t??"",isCopied:s,onCopy:E,copyLabel:"Copy"})]})})]})}function lAe(){const{tokens:t,setToken:e,clearToken:n,hasToken:r,getOllamaBaseUrl:s,setOllamaBaseUrl:i}=lR(),[a,l]=w.useState(""),[u,d]=w.useState(!1),[p,h]=w.useState(null),[g,v]=w.useState(!1),[x,b]=w.useState(""),E=[{id:"openai",name:"OpenAI",logo:"/openai_logo.png",logoAlt:"OpenAI",description:"GPT-4, GPT-4o, GPT-4o-mini, GPT-4.1, GPT-5, etc.",placeholder:"sk-...",getApiKeyUrl:"https://platform.openai.com/api-keys"},{id:"anthropic",name:"Anthropic",logo:"/claude_logo.png",logoAlt:"Claude",description:"Claude 3.5, Claude 3.7, Claude Opus 4, etc.",placeholder:"sk-ant-...",getApiKeyUrl:"https://console.anthropic.com/"},{id:"deepseek",name:"DeepSeek",logo:"/deepseek_logo.svg",logoAlt:"DeepSeek",description:"DeepSeek Chat, DeepSeek Reasoner, etc.",placeholder:"sk-...",getApiKeyUrl:"https://platform.deepseek.com/api_keys"},{id:"google",name:"Google AI",logo:"/google_logo.png",logoAlt:"Google AI",description:"Gemini 2.5, Gemini 2.5 Flash, Gemini 2.5 Flash Lite",placeholder:"AI...",getApiKeyUrl:"https://aistudio.google.com/app/apikey"}],S=M=>{const I=E.find(O=>O.id===M);I&&(h(I),l(t[M]||""),d(!0))},k=()=>{p&&(e(p.id,a),d(!1),h(null),l(""))},T=()=>{d(!1),h(null),l("")},R=M=>{n(M)},j=()=>{b(s()),v(!0)},A=()=>{i(x),v(!1),b("")},N=()=>{v(!1),b("")};return f.jsxs("div",{className:"container mx-auto p-6 max-w-6xl space-y-8",children:[f.jsx("div",{className:"flex items-center gap-3 mb-6",children:f.jsx("h1",{className:"text-2xl font-bold",children:"Settings"})}),f.jsx(oAe,{}),f.jsxs("div",{className:"space-y-4",children:[f.jsx("div",{children:f.jsx("h3",{className:"text-lg font-semibold",children:"LLM Provider API Keys"})}),f.jsx(gTe,{providerConfigs:E,hasToken:M=>r(M),onEditProvider:S,onDeleteProvider:R,ollamaBaseUrl:s(),onEditOllama:j})]}),f.jsx(vTe,{open:u,onOpenChange:d,provider:p,value:a,onValueChange:l,onSave:k,onCancel:T}),f.jsx(yTe,{open:g,onOpenChange:v,value:x,onValueChange:b,onSave:A,onCancel:N})]})}const cAe=(t,e="HH:mm:ss.SSS")=>{const n=typeof t=="string"?HCe(t):t;return O7(n,e)},uAe={error:"bg-red-500/10 text-red-700 border-red-200 dark:text-red-400 dark:border-red-800",warn:"bg-yellow-500/10 text-yellow-700 border-yellow-200 dark:text-yellow-400 dark:border-yellow-800",info:"bg-blue-500/10 text-blue-700 border-blue-200 dark:text-blue-400 dark:border-blue-800",debug:"bg-purple-500/10 text-purple-700 border-purple-200 dark:text-purple-400 dark:border-purple-800",trace:"bg-gray-500/10 text-gray-700 border-gray-200 dark:text-gray-400 dark:border-gray-800"};function I7({level:t}){return f.jsx(xr,{variant:"outline",className:Oe("font-mono",uAe[t]),children:t.toUpperCase()})}function dAe({entry:t,isExpanded:e,onToggleExpand:n}){const r=t.data!==void 0||t.error!==void 0;return f.jsxs("div",{className:"border rounded-lg font-mono",children:[f.jsx("div",{className:`p-3 cursor-pointer hover:bg-muted/50 ${r?"":"cursor-default"}`,onClick:r?n:void 0,children:f.jsxs("div",{className:"flex items-start gap-3",children:[r&&f.jsx("div",{className:"mt-0.5",children:e?f.jsx(cc,{className:"h-4 w-4 text-muted-foreground"}):f.jsx(la,{className:"h-4 w-4 text-muted-foreground"})}),f.jsx("div",{className:"flex-1 min-w-0",children:f.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:`[${cAe(t.timestamp)}]`}),f.jsx(I7,{level:t.level}),f.jsx(xr,{variant:"secondary",children:t.context}),f.jsx("span",{className:"flex-1 break-words",children:t.message})]})})]})}),e&&r&&f.jsxs("div",{className:"border-t bg-muted/20 p-3 space-y-3",children:[t.data!==void 0&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:"DATA:"}),f.jsx("div",{className:"text-xs bg-background border rounded overflow-auto max-h-60",children:f.jsx(Mo,{src:t.data,dark:!0,theme:"atom",enableClipboard:!0,displaySize:!1,collapseStringsAfterLength:100,style:{fontSize:"12px",fontFamily:"ui-monospace, SFMono-Regular, 'SF Mono', monospace",backgroundColor:"hsl(var(--background))",padding:"0",borderRadius:"0",border:"none"}})})]}),t.error&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:"ERROR:"}),f.jsxs("pre",{className:"text-xs bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded p-2 overflow-auto max-h-40 text-red-700 dark:text-red-400",children:[t.error.message,t.error.stack&&`
1824
1824
 
1825
1825
  ${t.error.stack}`]})]})]})]})}const fAe=["error","warn","info","debug","trace"];function hAe(){const{entries:t}=che(),e=QN("JSON-RPC"),[n,r]=w.useState(new Set),[s,i]=w.useState("all"),[a,l]=w.useState("all"),[u,d]=w.useState(""),[p,h]=w.useState(!1),g=w.useRef(null),v=w.useRef(null),x=w.useMemo(()=>{const k=new Set;for(const T of t){const R=T?.data?.serverId;typeof R=="string"&&R.length>0&&k.add(R)}return Array.from(k).sort()},[t]),b=w.useMemo(()=>{let k=s==="all"?t:t.filter(R=>R.level===s);if(a!=="all"&&(k=k.filter(R=>R?.data?.serverId===a)),!u.trim())return k;const T=u.toLowerCase();return k.filter(R=>R.message.toLowerCase().includes(T)||R.context.toLowerCase().includes(T)||R.data&&JSON.stringify(R.data).toLowerCase().includes(T))},[t,s,a,u]);w.useEffect(()=>{const k=()=>{if(g.current){const{scrollTop:R}=g.current;h(R>200)}},T=g.current;if(T)return T.addEventListener("scroll",k),()=>T.removeEventListener("scroll",k)},[]);const E=()=>{g.current&&g.current.scrollTo({top:0,behavior:"smooth"})};w.useEffect(()=>{let k=null;try{const T=new URLSearchParams;T.set("replay","200"),k=new EventSource(`/api/mcp/servers/rpc/stream?${T.toString()}`),k.onmessage=R=>{try{const j=JSON.parse(R.data);if(j&&j.type==="rpc"){const A=j.serverId,N=j.direction,M=j.message,I=j.timestamp,O=typeof N=="string"?N.toUpperCase():"",L=M,z=typeof L?.method=="string"?L.method:L?.result!==void 0?"result":L?.error!==void 0?"error":"unknown",H=`[${A}] ${O} - ${z}`;e.info(H,{serverId:A,direction:N,method:z,timestamp:I,message:M})}}catch{}},k.onerror=()=>{try{k?.close()}catch{}}}catch{}return()=>{try{k?.close()}catch{}}},[e]);const S=k=>{const T=new Set(n);T.has(k)?T.delete(k):T.add(k),r(T)};return f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"border-b bg-background p-4 space-y-4 flex-shrink-0 sticky top-0 z-10",children:[f.jsx("h2",{className:"text-lg font-semibold",children:"Tracing"}),f.jsxs("div",{className:"flex items-center gap-4",children:[f.jsxs(nu,{value:s,onValueChange:k=>i(k),children:[f.jsx(su,{className:"w-32",children:f.jsx(ru,{})}),f.jsxs(iu,{children:[f.jsx(ei,{value:"all",children:"All Levels"}),fAe.map(k=>f.jsx(ei,{value:k,children:f.jsx(I7,{level:k})},k))]})]}),f.jsxs(nu,{value:a,onValueChange:k=>l(k),children:[f.jsx(su,{className:"w-56",children:f.jsx(ru,{placeholder:"All Servers"})}),f.jsxs(iu,{children:[f.jsx(ei,{value:"all",children:"All Servers"}),x.map(k=>f.jsx(ei,{value:k,children:k},k))]})]}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx(nN,{className:"h-4 w-4"}),f.jsx(Dn,{placeholder:"Search logs...",value:u,onChange:k=>d(k.target.value),className:"h-8"})]})]}),f.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[f.jsxs("span",{children:["Total: ",t.length]}),f.jsxs("span",{children:["Filtered: ",b.length]})]})]}),f.jsxs("div",{ref:g,className:"flex-1 overflow-y-auto p-4 space-y-2 font-mono text-sm min-h-0",children:[b.length===0?f.jsx("div",{className:"text-center text-muted-foreground py-8",children:t.length===0?"No logs yet":"No logs match current filters"}):b.map((k,T)=>{const R=n.has(T);return f.jsx(dAe,{entry:k,isExpanded:R,onToggleExpand:()=>S(T)},`${k.timestamp}-${T}`)}),f.jsx("div",{ref:v})]}),p&&f.jsxs(Pe,{onClick:E,size:"sm",className:"fixed bottom-4 right-4 z-20 shadow-lg",variant:"secondary",children:[f.jsx(bB,{className:"h-4 w-4 mr-1"}),"Top"]})]})}const o$="mcpjam-interceptor-proxies";function pAe({connectedServerConfigs:t,selectedServer:e}){const[n,r]=w.useState({}),s=w.useRef({}),[i,a]=w.useState(!1),l=e&&e!=="none"?n[e]:null,u=k=>{try{localStorage.setItem(o$,JSON.stringify(k))}catch(T){console.error("Failed to save proxy state to localStorage:",T)}},d=w.useMemo(()=>`${new URL(window.location.href).origin}/api/mcp/interceptor`,[]),p=(k,T)=>{s.current[T]&&(s.current[T].close(),delete s.current[T]);const R=new EventSource(`${d}/${k}/stream`);R.onmessage=j=>{try{if(j.data==="[DONE]")return;const A=JSON.parse(j.data);console.log(`Stream message for ${T}:`,A),A.type==="log"&&A.log?r(N=>{const M={...N,[T]:{...N[T],logs:[...N[T]?.logs||[],A.log]}};return u(M),M}):A.type==="cleared"&&r(N=>{const M={...N,[T]:{...N[T],logs:[]}};return u(M),M})}catch(A){console.error("Error parsing stream message:",A)}},R.onopen=()=>{console.log(`Stream connected for ${T} interceptor:`,k)},R.onerror=j=>{console.error(`Stream error for ${T}:`,j)},s.current[T]=R};w.useEffect(()=>{let k=!1;return(async()=>{try{const T=localStorage.getItem(o$);if(!T)return;const R=JSON.parse(T),j=Object.entries(R).filter(([N])=>t[N]?.connectionStatus==="connected"),A={};await Promise.all(j.map(async([N,M])=>{try{const I=await fetch(`${d}/${M.interceptorId}`);!k&&I.ok&&(A[N]=M,p(M.interceptorId,N))}catch{}})),k||(r(A),u(A))}catch(T){console.error("Failed to load proxy state from localStorage:",T)}})(),()=>{k=!0,Object.values(s.current).forEach(T=>T.close()),s.current={}}},[t,d]),w.useEffect(()=>{const k=Object.keys(n).filter(T=>{const R=t[T];return!R||R.connectionStatus!=="connected"});if(k.length>0){const T={...n};let R=!1;k.forEach(j=>{console.log(`Server ${j} disconnected, cleaning up proxy`),T[j]?.interceptorId&&fetch(`${d}/${T[j].interceptorId}`,{method:"DELETE"}).catch(()=>{}),s.current[j]&&(s.current[j].close(),delete s.current[j]),delete T[j],R=!0}),R&&(r(T),u(T))}},[t,n,d]);const h=async()=>{if(!e||e==="none"){alert("Please select a connected server");return}const k=e;if(!t[k]){alert("Selected server is not connected");return}a(!0);try{const R=await(await fetch(`${d}/create`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({serverId:k})})).json();if(!R.success){alert(R.error||"Failed to create interceptor");return}const j=R.id,A=R.publicProxyUrl||R.proxyUrl,N={...n,[k]:{interceptorId:j,proxyUrl:A||`${d}/${j}/proxy`,logs:[]}};r(N),u(N),p(j,k)}catch(T){console.error("Failed to create proxy:",T),alert("Failed to create interceptor")}finally{a(!1)}},g=async()=>{if(!e||e==="none"||!l)return;try{await fetch(`${d}/${l.interceptorId}`,{method:"DELETE"})}catch{}s.current[e]&&(s.current[e].close(),delete s.current[e]);const k={...n};delete k[e],r(k),u(k)},v=async()=>{if(!e||e==="none"||!l)return;try{await fetch(`${d}/${l.interceptorId}/clear`,{method:"POST"})}catch{}const k={...n,[e]:{...n[e],logs:[]}};r(k),u(k)},[x,b]=w.useState(!1),E=()=>{const k=t[e]?.name||e||"server",T=l?.proxyUrl||"";return[`"${k}": {`,' "type": "http",',` "url": "${T}",`,' "headers": {}',"}"].join(`
1826
1826
  `)},S=async()=>{try{await navigator.clipboard.writeText(E()),b(!0),setTimeout(()=>b(!1),1e3)}catch(k){console.error("Failed to copy config JSON:",k)}};return f.jsxs("div",{className:"p-4 space-y-4",children:[f.jsxs(Ha,{className:"p-4",children:[f.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Proxy Configuration"}),f.jsx("div",{className:"space-y-3",children:l?f.jsxs("div",{className:"p-3 rounded border",children:[f.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"text-sm font-medium",children:["Active Proxy for"," ",t[e]?.name||e]}),f.jsx("span",{className:"mr-1 inline-block size-1.5 rounded-full bg-orange-500"})]}),f.jsx("div",{className:"flex gap-2 ml-auto",children:f.jsx(Pe,{variant:"outline",size:"sm",onClick:g,children:"Stop Proxy"})})]}),f.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 items-start",children:[f.jsxs("div",{className:"text-sm text-muted-foreground leading-relaxed",children:[f.jsx("div",{className:"mb-2 font-medium text-foreground",children:"How this proxy works"}),f.jsx("p",{children:"This creates a HTTP proxy that forwards requests to your connected MCP server. Add the JSON entry on the right in your client’s configuration. Auth credentials are the same as your server's and are injected automatically."})]}),f.jsxs("div",{className:"sm:col-start-2",children:[f.jsx("label",{className:"text-xs font-medium mb-1 block text-muted-foreground",children:"MCP HTTP config entry (no outer braces)"}),f.jsxs("div",{className:"relative",children:[f.jsx("pre",{className:"block p-2 pr-10 bg-transparent border rounded text-xs whitespace-pre leading-relaxed font-mono",children:E()}),f.jsx("button",{onClick:S,title:"Copy config entry",className:`absolute top-2 right-2 p-1 rounded transition-all duration-200 ${x?"text-foreground scale-110":"text-muted-foreground hover:text-foreground hover:bg-muted"}`,children:x?f.jsx(Ri,{className:"h-3 w-3"}):f.jsx(zo,{className:"h-3 w-3"})})]})]})]})]}):f.jsx("div",{className:"p-3 bg-muted rounded border",children:f.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[f.jsxs("div",{className:"min-w-0",children:[f.jsx("div",{className:"text-sm font-medium mb-1 truncate",children:e!=="none"?`Create proxy for ${t[e]?.name}`:"No server selected"}),f.jsx("div",{className:"text-xs text-muted-foreground",children:e?"Create a local HTTP proxy URL to your connected server":"Select a server above to create a proxy"})]}),f.jsx("div",{className:"shrink-0 self-start sm:self-auto",children:f.jsx(Pe,{onClick:h,disabled:!e||e==="none"||i,children:i?f.jsxs(f.Fragment,{children:[f.jsx(bu,{className:"animate-spin"}),"Creating..."]}):f.jsx(f.Fragment,{children:"Create Proxy"})})})]})})})]}),f.jsxs(Ha,{className:"p-4",children:[f.jsxs("div",{className:"flex items-center justify-between mb-3",children:[f.jsx("h2",{className:"text-lg font-semibold",children:"Request Logs"}),f.jsx(Pe,{variant:"outline",size:"sm",onClick:v,disabled:!l,children:"Clear Logs"})]}),f.jsx("div",{className:"border rounded-md bg-muted/30 max-h-[60vh] overflow-auto",children:!l?.logs||l.logs.length===0?f.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"No requests logged yet"}):f.jsx("div",{className:"divide-y",children:l.logs.map(k=>f.jsxs("div",{className:"p-3 text-sm",children:[f.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[f.jsx("span",{className:`text-xs px-2 py-0.5 rounded font-mono ${k.direction==="request"?"bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-300":"bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300"}`,children:k.direction}),"method"in k?f.jsxs("span",{className:"font-mono",children:[f.jsx("span",{className:"font-semibold text-orange-600 dark:text-orange-400",children:k.method}),(()=>{try{const T=JSON.parse(k.body||"{}");return T.method?f.jsxs("span",{className:"font-semibold text-foreground",children:[" ",T.method]}):null}catch{return null}})()]}):f.jsxs("span",{className:"font-mono font-semibold text-gray-600 dark:text-gray-400",children:[k.status," ",k.statusText]}),f.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:new Date(k.timestamp).toLocaleTimeString()})]}),"url"in k&&f.jsx("div",{className:"text-xs text-muted-foreground font-mono mb-1",children:k.url}),k.body&&(()=>{let T=null;try{const R=k.body.trim();(R.startsWith("{")||R.startsWith("["))&&(T=JSON.parse(R))}catch{}return T?f.jsxs("div",{className:"text-xs bg-background p-2 rounded border mt-1 overflow-auto",children:[f.jsx("style",{children:`
@@ -1876,5 +1876,5 @@ Error:`,s)}}function JMe(){return OMe(t=>{gh("cls",{metric:t}),GG=t},{reportAllC
1876
1876
  now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
1877
1877
  or you can use record.mirror to access the mirror instance during recording.`;let uz={map:{},getId(){return console.error(qd),-1},getNode(){return console.error(qd),null},removeNodeFromMap(){console.error(qd)},has(){return console.error(qd),!1},reset(){console.error(qd)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(uz=new Proxy(uz,{get(t,e,n){return e==="map"&&console.error(qd),Reflect.get(t,e,n)}}));function sg(t,e,n={}){let r=null,s=0;return function(...i){const a=Date.now();!s&&n.leading===!1&&(s=a);const l=e-(a-s),u=this;l<=0||l>e?(r&&(NPe(r),r=null),s=a,t.apply(u,i)):!r&&n.trailing!==!1&&(r=a_(()=>{s=n.leading===!1?0:Date.now(),r=null,t.apply(u,i)},l))}}function vW(t,e,n,r,s=window){const i=s.Object.getOwnPropertyDescriptor(t,e);return s.Object.defineProperty(t,e,r?n:{set(a){a_(()=>{n.set.call(this,a)},0),i&&i.set&&i.set.call(this,a)}}),()=>vW(t,e,i||{},!0)}function Oj(t,e,n){try{if(!(e in t))return()=>{};const r=t[e],s=n(r);return typeof s=="function"&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:r}})),t[e]=s,()=>{t[e]=r}}catch{return()=>{}}}let Lb=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(Lb=()=>new Date().getTime());function yW(t){const e=t.document;return{left:e.scrollingElement?e.scrollingElement.scrollLeft:t.pageXOffset!==void 0?t.pageXOffset:Il([e,"optionalAccess",n=>n.documentElement,"access",n=>n.scrollLeft])||Il([e,"optionalAccess",n=>n.body,"optionalAccess",n=>n.parentElement,"optionalAccess",n=>n.scrollLeft])||Il([e,"optionalAccess",n=>n.body,"optionalAccess",n=>n.scrollLeft])||0,top:e.scrollingElement?e.scrollingElement.scrollTop:t.pageYOffset!==void 0?t.pageYOffset:Il([e,"optionalAccess",n=>n.documentElement,"access",n=>n.scrollTop])||Il([e,"optionalAccess",n=>n.body,"optionalAccess",n=>n.parentElement,"optionalAccess",n=>n.scrollTop])||Il([e,"optionalAccess",n=>n.body,"optionalAccess",n=>n.scrollTop])||0}}function xW(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function bW(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function _W(t){return t?t.nodeType===t.ELEMENT_NODE?t:t.parentElement:null}function ti(t,e,n,r,s){if(!t)return!1;const i=_W(t);if(!i)return!1;const a=tf(e,n);if(!s){const d=r&&i.matches(r);return a(i)&&!d}const l=tu(i,a);let u=-1;return l<0?!1:(r&&(u=tu(i,tf(null,r))),l>-1&&u<0?!0:l<u)}function SPe(t,e){return e.getId(t)!==-1}function nk(t,e){return e.getId(t)===rg}function wW(t,e){if(xm(t))return!1;const n=e.getId(t);return e.has(n)?t.parentNode&&t.parentNode.nodeType===t.DOCUMENT_NODE?!1:t.parentNode?wW(t.parentNode,e):!0:!0}function rA(t){return!!t.changedTouches}function EPe(t=window){"NodeList"in t&&!t.NodeList.prototype.forEach&&(t.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in t&&!t.DOMTokenList.prototype.forEach&&(t.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...e)=>{let n=e[0];if(!(0 in e))throw new TypeError("1 argument is required");do if(this===n)return!0;while(n=n&&n.parentNode);return!1})}function SW(t,e){return!!(t.nodeName==="IFRAME"&&e.getMeta(t))}function EW(t,e){return!!(t.nodeName==="LINK"&&t.nodeType===t.ELEMENT_NODE&&t.getAttribute&&t.getAttribute("rel")==="stylesheet"&&e.getMeta(t))}function sA(t){return!!Il([t,"optionalAccess",e=>e.shadowRoot])}class kPe{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(e){return cMe(this.styleIDMap.get(e),()=>-1)}has(e){return this.styleIDMap.has(e)}add(e,n){if(this.has(e))return this.getId(e);let r;return n===void 0?r=this.id++:r=n,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function kW(t){let e=null;return Il([t,"access",n=>n.getRootNode,"optionalCall",n=>n(),"optionalAccess",n=>n.nodeType])===Node.DOCUMENT_FRAGMENT_NODE&&t.getRootNode().host&&(e=t.getRootNode().host),e}function TPe(t){let e=t,n;for(;n=kW(e);)e=n;return e}function CPe(t){const e=t.ownerDocument;if(!e)return!1;const n=TPe(t);return e.contains(n)}function TW(t){const e=t.ownerDocument;return e?e.contains(t)||CPe(t):!1}const dz={};function Pj(t){const e=dz[t];if(e)return e;const n=window.document;let r=window[t];if(n&&typeof n.createElement=="function")try{const s=n.createElement("iframe");s.hidden=!0,n.head.appendChild(s);const i=s.contentWindow;i&&i[t]&&(r=i[t]),n.head.removeChild(s)}catch{}return dz[t]=r.bind(window)}function APe(...t){return Pj("requestAnimationFrame")(...t)}function a_(...t){return Pj("setTimeout")(...t)}function NPe(...t){return Pj("clearTimeout")(...t)}var Ut=(t=>(t[t.DomContentLoaded=0]="DomContentLoaded",t[t.Load=1]="Load",t[t.FullSnapshot=2]="FullSnapshot",t[t.IncrementalSnapshot=3]="IncrementalSnapshot",t[t.Meta=4]="Meta",t[t.Custom=5]="Custom",t[t.Plugin=6]="Plugin",t))(Ut||{}),Ct=(t=>(t[t.Mutation=0]="Mutation",t[t.MouseMove=1]="MouseMove",t[t.MouseInteraction=2]="MouseInteraction",t[t.Scroll=3]="Scroll",t[t.ViewportResize=4]="ViewportResize",t[t.Input=5]="Input",t[t.TouchMove=6]="TouchMove",t[t.MediaInteraction=7]="MediaInteraction",t[t.StyleSheetRule=8]="StyleSheetRule",t[t.CanvasMutation=9]="CanvasMutation",t[t.Font=10]="Font",t[t.Log=11]="Log",t[t.Drag=12]="Drag",t[t.StyleDeclaration=13]="StyleDeclaration",t[t.Selection=14]="Selection",t[t.AdoptedStyleSheet=15]="AdoptedStyleSheet",t[t.CustomElement=16]="CustomElement",t))(Ct||{}),ps=(t=>(t[t.MouseUp=0]="MouseUp",t[t.MouseDown=1]="MouseDown",t[t.Click=2]="Click",t[t.ContextMenu=3]="ContextMenu",t[t.DblClick=4]="DblClick",t[t.Focus=5]="Focus",t[t.Blur=6]="Blur",t[t.TouchStart=7]="TouchStart",t[t.TouchMove_Departed=8]="TouchMove_Departed",t[t.TouchEnd=9]="TouchEnd",t[t.TouchCancel=10]="TouchCancel",t))(ps||{}),_o=(t=>(t[t.Mouse=0]="Mouse",t[t.Pen=1]="Pen",t[t.Touch=2]="Touch",t))(_o||{}),fz;(function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"})(fz||(fz={}));var hz;(function(t){t[t.PLACEHOLDER=0]="PLACEHOLDER",t[t.ELEMENT_NODE=1]="ELEMENT_NODE",t[t.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",t[t.TEXT_NODE=3]="TEXT_NODE",t[t.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",t[t.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",t[t.ENTITY_NODE=6]="ENTITY_NODE",t[t.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",t[t.COMMENT_NODE=8]="COMMENT_NODE",t[t.DOCUMENT_NODE=9]="DOCUMENT_NODE",t[t.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",t[t.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE"})(hz||(hz={}));function Ij(t){try{return t.contentDocument}catch{}}function RPe(t){try{return t.contentWindow}catch{}}function jPe(t){let e,n=t[0],r=1;for(;r<t.length;){const s=t[r],i=t[r+1];if(r+=2,(s==="optionalAccess"||s==="optionalCall")&&n==null)return;s==="access"||s==="optionalAccess"?(e=n,n=i(n)):(s==="call"||s==="optionalCall")&&(n=i((...a)=>n.call(e,...a)),e=void 0)}return n}function pz(t){return"__ln"in t}class MPe{constructor(){this.length=0,this.head=null,this.tail=null}get(e){if(e>=this.length)throw new Error("Position outside of list range");let n=this.head;for(let r=0;r<e;r++)n=jPe([n,"optionalAccess",s=>s.next])||null;return n}addNode(e){const n={value:e,previous:null,next:null};if(e.__ln=n,e.previousSibling&&pz(e.previousSibling)){const r=e.previousSibling.__ln.next;n.next=r,n.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=n,r&&(r.previous=n)}else if(e.nextSibling&&pz(e.nextSibling)&&e.nextSibling.__ln.previous){const r=e.nextSibling.__ln.previous;n.previous=r,n.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=n,r&&(r.next=n)}else this.head&&(this.head.previous=n),n.next=this.head,this.head=n;n.next===null&&(this.tail=n),this.length++}removeNode(e){const n=e.__ln;this.head&&(n.previous?(n.previous.next=n.next,n.next?n.next.previous=n.previous:this.tail=n.previous):(this.head=n.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}}const mz=(t,e)=>`${t}@${e}`;class OPe{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=e=>{e.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const e=[],n=new Set,r=new MPe,s=u=>{let d=u,p=rg;for(;p===rg;)d=d&&d.nextSibling,p=d&&this.mirror.getId(d);return p},i=u=>{if(!u.parentNode||!TW(u))return;const d=xm(u.parentNode)?this.mirror.getId(kW(u)):this.mirror.getId(u.parentNode),p=s(u);if(d===-1||p===-1)return r.addNode(u);const h=nf(u,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskAllText:this.maskAllText,unblockSelector:this.unblockSelector,maskTextClass:this.maskTextClass,unmaskTextClass:this.unmaskTextClass,maskTextSelector:this.maskTextSelector,unmaskTextSelector:this.unmaskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskAttributeFn:this.maskAttributeFn,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:g=>{SW(g,this.mirror)&&!ti(g,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&this.iframeManager.addIframe(g),EW(g,this.mirror)&&this.stylesheetManager.trackLinkElement(g),sA(u)&&this.shadowDomManager.addShadowRoot(u.shadowRoot,this.doc)},onIframeLoad:(g,v)=>{ti(g,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(this.iframeManager.attachIframe(g,v),g.contentWindow&&this.canvasManager.addWindow(g.contentWindow),this.shadowDomManager.observeAttachShadow(g))},onStylesheetLoad:(g,v)=>{this.stylesheetManager.attachLinkElement(g,v)}});h&&(e.push({parentId:d,nextId:p,node:h}),n.add(h.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const u of this.movedSet)gz(this.removes,u,this.mirror)&&!this.movedSet.has(u.parentNode)||i(u);for(const u of this.addedSet)!vz(this.droppedSet,u)&&!gz(this.removes,u,this.mirror)||vz(this.movedSet,u)?i(u):this.droppedSet.add(u);let a=null;for(;r.length;){let u=null;if(a){const d=this.mirror.getId(a.value.parentNode),p=s(a.value);d!==-1&&p!==-1&&(u=a)}if(!u){let d=r.tail;for(;d;){const p=d;if(d=d.previous,p){const h=this.mirror.getId(p.value.parentNode);if(s(p.value)===-1)continue;if(h!==-1){u=p;break}else{const v=p.value;if(v.parentNode&&v.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const x=v.parentNode.host;if(this.mirror.getId(x)!==-1){u=p;break}}}}}}if(!u){for(;r.head;)r.removeNode(r.head.value);break}a=u.previous,r.removeNode(u.value),i(u.value)}const l={texts:this.texts.map(u=>({id:this.mirror.getId(u.node),value:u.value})).filter(u=>!n.has(u.id)).filter(u=>this.mirror.has(u.id)),attributes:this.attributes.map(u=>{const{attributes:d}=u;if(typeof d.style=="string"){const p=JSON.stringify(u.styleDiff),h=JSON.stringify(u._unchangedStyles);p.length<d.style.length&&(p+h).split("var(").length===d.style.split("var(").length&&(d.style=u.styleDiff)}return{id:this.mirror.getId(u.node),attributes:d}}).filter(u=>!n.has(u.id)).filter(u=>this.mirror.has(u.id)),removes:this.removes,adds:e};!l.texts.length&&!l.attributes.length&&!l.removes.length&&!l.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(l))},this.processMutation=e=>{if(!nk(e.target,this.mirror))switch(e.type){case"characterData":{const n=e.target.textContent;!ti(e.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&n!==e.oldValue&&this.texts.push({value:Vf(e.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,this.maskAllText)&&n?this.maskTextFn?this.maskTextFn(n,_W(e.target)):n.replace(/[\S]/g,"*"):n,node:e.target});break}case"attributes":{const n=e.target;let r=e.attributeName,s=e.target.getAttribute(r);if(r==="value"){const a=jj(n),l=n.tagName;s=Ib(n,l,a);const u=s_({maskInputOptions:this.maskInputOptions,tagName:l,type:a}),d=Vf(e.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,u);s=ng({isMasked:d,element:n,value:s,maskInputFn:this.maskInputFn})}if(ti(e.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||s===e.oldValue)return;let i=this.attributeMap.get(e.target);if(n.tagName==="IFRAME"&&r==="src"&&!this.keepIframeSrcFn(s))if(!Ij(n))r="rr_src";else return;if(i||(i={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(i),this.attributeMap.set(e.target,i)),r==="type"&&n.tagName==="INPUT"&&(e.oldValue||"").toLowerCase()==="password"&&n.setAttribute("data-rr-is-password","true"),!gW(n.tagName,r)&&(i.attributes[r]=mW(this.doc,qf(n.tagName),qf(r),s,n,this.maskAttributeFn),r==="style")){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch{this.unattachedDoc=this.doc}const a=this.unattachedDoc.createElement("span");e.oldValue&&a.setAttribute("style",e.oldValue);for(const l of Array.from(n.style)){const u=n.style.getPropertyValue(l),d=n.style.getPropertyPriority(l);u!==a.style.getPropertyValue(l)||d!==a.style.getPropertyPriority(l)?d===""?i.styleDiff[l]=u:i.styleDiff[l]=[u,d]:i._unchangedStyles[l]=[u,d]}for(const l of Array.from(a.style))n.style.getPropertyValue(l)===""&&(i.styleDiff[l]=!1)}break}case"childList":{if(ti(e.target,this.blockClass,this.blockSelector,this.unblockSelector,!0))return;e.addedNodes.forEach(n=>this.genAdds(n,e.target)),e.removedNodes.forEach(n=>{const r=this.mirror.getId(n),s=xm(e.target)?this.mirror.getId(e.target.host):this.mirror.getId(e.target);ti(e.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||nk(n,this.mirror)||!SPe(n,this.mirror)||(this.addedSet.has(n)?(iA(this.addedSet,n),this.droppedSet.add(n)):this.addedSet.has(e.target)&&r===-1||wW(e.target,this.mirror)||(this.movedSet.has(n)&&this.movedMap[mz(r,s)]?iA(this.movedSet,n):this.removes.push({parentId:s,id:r,isShadow:xm(e.target)&&bm(e.target)?!0:void 0})),this.mapRemoves.push(n))});break}}},this.genAdds=(e,n)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!(this.addedSet.has(e)||this.movedSet.has(e))){if(this.mirror.hasNode(e)){if(nk(e,this.mirror))return;this.movedSet.add(e);let r=null;n&&this.mirror.hasNode(n)&&(r=this.mirror.getId(n)),r&&r!==-1&&(this.movedMap[mz(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);ti(e,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(e.childNodes.forEach(r=>this.genAdds(r)),sA(e)&&e.shadowRoot.childNodes.forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,e)}))}}}init(e){["mutationCb","blockClass","blockSelector","unblockSelector","maskAllText","maskTextClass","unmaskTextClass","maskTextSelector","unmaskTextSelector","inlineStylesheet","maskInputOptions","maskAttributeFn","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(n=>{this[n]=e[n]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function iA(t,e){t.delete(e),e.childNodes.forEach(n=>iA(t,n))}function gz(t,e,n){return t.length===0?!1:PPe(t,e,n)}function PPe(t,e,n){let r=e.parentNode;for(;r;){const s=n.getId(r);if(t.some(i=>i.id===s))return!0;r=r.parentNode}return!1}function vz(t,e){return t.size===0?!1:CW(t,e)}function CW(t,e){const{parentNode:n}=e;return n?t.has(n)?!0:CW(t,n):!1}let _m;function IPe(t){_m=t}function DPe(){_m=void 0}const Jt=t=>_m?(...n)=>{try{return t(...n)}catch(r){if(_m&&_m(r)===!0)return()=>{};throw r}}:t;function ta(t){let e,n=t[0],r=1;for(;r<t.length;){const s=t[r],i=t[r+1];if(r+=2,(s==="optionalAccess"||s==="optionalCall")&&n==null)return;s==="access"||s==="optionalAccess"?(e=n,n=i(n)):(s==="call"||s==="optionalCall")&&(n=i((...a)=>n.call(e,...a)),e=void 0)}return n}const rf=[];function $g(t){try{if("composedPath"in t){const e=t.composedPath();if(e.length)return e[0]}else if("path"in t&&t.path.length)return t.path[0]}catch{}return t&&t.target}function AW(t,e){const n=new OPe;rf.push(n),n.init(t);let r=window.MutationObserver||window.__rrMutationObserver;const s=ta([window,"optionalAccess",a=>a.Zone,"optionalAccess",a=>a.__symbol__,"optionalCall",a=>a("MutationObserver")]);s&&window[s]&&(r=window[s]);const i=new r(Jt(a=>{t.onMutation&&t.onMutation(a)===!1||n.processMutations.bind(n)(a)}));return i.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),i}function LPe({mousemoveCb:t,sampling:e,doc:n,mirror:r}){if(e.mousemove===!1)return()=>{};const s=typeof e.mousemove=="number"?e.mousemove:50,i=typeof e.mousemoveCallback=="number"?e.mousemoveCallback:500;let a=[],l;const u=sg(Jt(h=>{const g=Date.now()-l;t(a.map(v=>(v.timeOffset-=g,v)),h),a=[],l=null}),i),d=Jt(sg(Jt(h=>{const g=$g(h),{clientX:v,clientY:x}=rA(h)?h.changedTouches[0]:h;l||(l=Lb()),a.push({x:v,y:x,id:r.getId(g),timeOffset:Lb()-l}),u(typeof DragEvent<"u"&&h instanceof DragEvent?Ct.Drag:h instanceof MouseEvent?Ct.MouseMove:Ct.TouchMove)}),s,{trailing:!1})),p=[gs("mousemove",d,n),gs("touchmove",d,n),gs("drag",d,n)];return Jt(()=>{p.forEach(h=>h())})}function $Pe({mouseInteractionCb:t,doc:e,mirror:n,blockClass:r,blockSelector:s,unblockSelector:i,sampling:a}){if(a.mouseInteraction===!1)return()=>{};const l=a.mouseInteraction===!0||a.mouseInteraction===void 0?{}:a.mouseInteraction,u=[];let d=null;const p=h=>g=>{const v=$g(g);if(ti(v,r,s,i,!0))return;let x=null,b=h;if("pointerType"in g){switch(g.pointerType){case"mouse":x=_o.Mouse;break;case"touch":x=_o.Touch;break;case"pen":x=_o.Pen;break}x===_o.Touch?ps[h]===ps.MouseDown?b="TouchStart":ps[h]===ps.MouseUp&&(b="TouchEnd"):_o.Pen}else rA(g)&&(x=_o.Touch);x!==null?(d=x,(b.startsWith("Touch")&&x===_o.Touch||b.startsWith("Mouse")&&x===_o.Mouse)&&(x=null)):ps[h]===ps.Click&&(x=d,d=null);const E=rA(g)?g.changedTouches[0]:g;if(!E)return;const S=n.getId(v),{clientX:k,clientY:T}=E;Jt(t)({type:ps[b],id:S,x:k,y:T,...x!==null&&{pointerType:x}})};return Object.keys(ps).filter(h=>Number.isNaN(Number(h))&&!h.endsWith("_Departed")&&l[h]!==!1).forEach(h=>{let g=qf(h);const v=p(h);if(window.PointerEvent)switch(ps[h]){case ps.MouseDown:case ps.MouseUp:g=g.replace("mouse","pointer");break;case ps.TouchStart:case ps.TouchEnd:return}u.push(gs(g,v,e))}),Jt(()=>{u.forEach(h=>h())})}function NW({scrollCb:t,doc:e,mirror:n,blockClass:r,blockSelector:s,unblockSelector:i,sampling:a}){const l=Jt(sg(Jt(u=>{const d=$g(u);if(!d||ti(d,r,s,i,!0))return;const p=n.getId(d);if(d===e&&e.defaultView){const h=yW(e.defaultView);t({id:p,x:h.left,y:h.top})}else t({id:p,x:d.scrollLeft,y:d.scrollTop})}),a.scroll||100));return gs("scroll",l,e)}function zPe({viewportResizeCb:t},{win:e}){let n=-1,r=-1;const s=Jt(sg(Jt(()=>{const i=xW(),a=bW();(n!==i||r!==a)&&(t({width:Number(a),height:Number(i)}),n=i,r=a)}),200));return gs("resize",s,e)}const FPe=["INPUT","TEXTAREA","SELECT"],yz=new WeakMap;function UPe({inputCb:t,doc:e,mirror:n,blockClass:r,blockSelector:s,unblockSelector:i,ignoreClass:a,ignoreSelector:l,maskInputOptions:u,maskInputFn:d,sampling:p,userTriggeredOnInput:h,maskTextClass:g,unmaskTextClass:v,maskTextSelector:x,unmaskTextSelector:b}){function E(N){let M=$g(N);const I=N.isTrusted,O=M&&tA(M.tagName);if(O==="OPTION"&&(M=M.parentElement),!M||!O||FPe.indexOf(O)<0||ti(M,r,s,i,!0))return;const L=M;if(L.classList.contains(a)||l&&L.matches(l))return;const z=jj(M);let H=Ib(L,O,z),V=!1;const X=s_({maskInputOptions:u,tagName:O,type:z}),F=Vf(M,g,x,v,b,X);(z==="radio"||z==="checkbox")&&(V=M.checked),H=ng({isMasked:F,element:M,value:H,maskInputFn:d}),S(M,h?{text:H,isChecked:V,userTriggered:I}:{text:H,isChecked:V});const W=M.name;z==="radio"&&W&&V&&e.querySelectorAll(`input[type="radio"][name="${W}"]`).forEach(G=>{if(G!==M){const ee=ng({isMasked:F,element:G,value:Ib(G,O,z),maskInputFn:d});S(G,h?{text:ee,isChecked:!V,userTriggered:!1}:{text:ee,isChecked:!V})}})}function S(N,M){const I=yz.get(N);if(!I||I.text!==M.text||I.isChecked!==M.isChecked){yz.set(N,M);const O=n.getId(N);Jt(t)({...M,id:O})}}const T=(p.input==="last"?["change"]:["input","change"]).map(N=>gs(N,Jt(E),e)),R=e.defaultView;if(!R)return()=>{T.forEach(N=>N())};const j=R.Object.getOwnPropertyDescriptor(R.HTMLInputElement.prototype,"value"),A=[[R.HTMLInputElement.prototype,"value"],[R.HTMLInputElement.prototype,"checked"],[R.HTMLSelectElement.prototype,"value"],[R.HTMLTextAreaElement.prototype,"value"],[R.HTMLSelectElement.prototype,"selectedIndex"],[R.HTMLOptionElement.prototype,"selected"]];return j&&j.set&&T.push(...A.map(N=>vW(N[0],N[1],{set(){Jt(E)({target:this,isTrusted:!1})}},!1,R))),Jt(()=>{T.forEach(N=>N())})}function $b(t){const e=[];function n(r,s){if(Fy("CSSGroupingRule")&&r.parentRule instanceof CSSGroupingRule||Fy("CSSMediaRule")&&r.parentRule instanceof CSSMediaRule||Fy("CSSSupportsRule")&&r.parentRule instanceof CSSSupportsRule||Fy("CSSConditionRule")&&r.parentRule instanceof CSSConditionRule){const a=Array.from(r.parentRule.cssRules).indexOf(r);s.unshift(a)}else if(r.parentStyleSheet){const a=Array.from(r.parentStyleSheet.cssRules).indexOf(r);s.unshift(a)}return s}return n(t,e)}function Dl(t,e,n){let r,s;return t?(t.ownerNode?r=e.getId(t.ownerNode):s=n.getId(t),{styleId:s,id:r}):{}}function BPe({styleSheetRuleCb:t,mirror:e,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const s=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(s,{apply:Jt((p,h,g)=>{const[v,x]=g,{id:b,styleId:E}=Dl(h,e,n.styleMirror);return(b&&b!==-1||E&&E!==-1)&&t({id:b,styleId:E,adds:[{rule:v,index:x}]}),p.apply(h,g)})});const i=r.CSSStyleSheet.prototype.deleteRule;r.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:Jt((p,h,g)=>{const[v]=g,{id:x,styleId:b}=Dl(h,e,n.styleMirror);return(x&&x!==-1||b&&b!==-1)&&t({id:x,styleId:b,removes:[{index:v}]}),p.apply(h,g)})});let a;r.CSSStyleSheet.prototype.replace&&(a=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(a,{apply:Jt((p,h,g)=>{const[v]=g,{id:x,styleId:b}=Dl(h,e,n.styleMirror);return(x&&x!==-1||b&&b!==-1)&&t({id:x,styleId:b,replace:v}),p.apply(h,g)})}));let l;r.CSSStyleSheet.prototype.replaceSync&&(l=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(l,{apply:Jt((p,h,g)=>{const[v]=g,{id:x,styleId:b}=Dl(h,e,n.styleMirror);return(x&&x!==-1||b&&b!==-1)&&t({id:x,styleId:b,replaceSync:v}),p.apply(h,g)})}));const u={};Uy("CSSGroupingRule")?u.CSSGroupingRule=r.CSSGroupingRule:(Uy("CSSMediaRule")&&(u.CSSMediaRule=r.CSSMediaRule),Uy("CSSConditionRule")&&(u.CSSConditionRule=r.CSSConditionRule),Uy("CSSSupportsRule")&&(u.CSSSupportsRule=r.CSSSupportsRule));const d={};return Object.entries(u).forEach(([p,h])=>{d[p]={insertRule:h.prototype.insertRule,deleteRule:h.prototype.deleteRule},h.prototype.insertRule=new Proxy(d[p].insertRule,{apply:Jt((g,v,x)=>{const[b,E]=x,{id:S,styleId:k}=Dl(v.parentStyleSheet,e,n.styleMirror);return(S&&S!==-1||k&&k!==-1)&&t({id:S,styleId:k,adds:[{rule:b,index:[...$b(v),E||0]}]}),g.apply(v,x)})}),h.prototype.deleteRule=new Proxy(d[p].deleteRule,{apply:Jt((g,v,x)=>{const[b]=x,{id:E,styleId:S}=Dl(v.parentStyleSheet,e,n.styleMirror);return(E&&E!==-1||S&&S!==-1)&&t({id:E,styleId:S,removes:[{index:[...$b(v),b]}]}),g.apply(v,x)})})}),Jt(()=>{r.CSSStyleSheet.prototype.insertRule=s,r.CSSStyleSheet.prototype.deleteRule=i,a&&(r.CSSStyleSheet.prototype.replace=a),l&&(r.CSSStyleSheet.prototype.replaceSync=l),Object.entries(u).forEach(([p,h])=>{h.prototype.insertRule=d[p].insertRule,h.prototype.deleteRule=d[p].deleteRule})})}function RW({mirror:t,stylesheetManager:e},n){let r=null;n.nodeName==="#document"?r=t.getId(n):r=t.getId(n.host);const s=n.nodeName==="#document"?ta([n,"access",a=>a.defaultView,"optionalAccess",a=>a.Document]):ta([n,"access",a=>a.ownerDocument,"optionalAccess",a=>a.defaultView,"optionalAccess",a=>a.ShadowRoot]),i=ta([s,"optionalAccess",a=>a.prototype])?Object.getOwnPropertyDescriptor(ta([s,"optionalAccess",a=>a.prototype]),"adoptedStyleSheets"):void 0;return r===null||r===-1||!s||!i?()=>{}:(Object.defineProperty(n,"adoptedStyleSheets",{configurable:i.configurable,enumerable:i.enumerable,get(){return ta([i,"access",a=>a.get,"optionalAccess",a=>a.call,"call",a=>a(this)])},set(a){const l=ta([i,"access",u=>u.set,"optionalAccess",u=>u.call,"call",u=>u(this,a)]);if(r!==null&&r!==-1)try{e.adoptStyleSheets(a,r)}catch{}return l}}),Jt(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:i.configurable,enumerable:i.enumerable,get:i.get,set:i.set})}))}function qPe({styleDeclarationCb:t,mirror:e,ignoreCSSAttributes:n,stylesheetManager:r},{win:s}){const i=s.CSSStyleDeclaration.prototype.setProperty;s.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:Jt((l,u,d)=>{const[p,h,g]=d;if(n.has(p))return i.apply(u,[p,h,g]);const{id:v,styleId:x}=Dl(ta([u,"access",b=>b.parentRule,"optionalAccess",b=>b.parentStyleSheet]),e,r.styleMirror);return(v&&v!==-1||x&&x!==-1)&&t({id:v,styleId:x,set:{property:p,value:h,priority:g},index:$b(u.parentRule)}),l.apply(u,d)})});const a=s.CSSStyleDeclaration.prototype.removeProperty;return s.CSSStyleDeclaration.prototype.removeProperty=new Proxy(a,{apply:Jt((l,u,d)=>{const[p]=d;if(n.has(p))return a.apply(u,[p]);const{id:h,styleId:g}=Dl(ta([u,"access",v=>v.parentRule,"optionalAccess",v=>v.parentStyleSheet]),e,r.styleMirror);return(h&&h!==-1||g&&g!==-1)&&t({id:h,styleId:g,remove:{property:p},index:$b(u.parentRule)}),l.apply(u,d)})}),Jt(()=>{s.CSSStyleDeclaration.prototype.setProperty=i,s.CSSStyleDeclaration.prototype.removeProperty=a})}function VPe({mediaInteractionCb:t,blockClass:e,blockSelector:n,unblockSelector:r,mirror:s,sampling:i,doc:a}){const l=Jt(d=>sg(Jt(p=>{const h=$g(p);if(!h||ti(h,e,n,r,!0))return;const{currentTime:g,volume:v,muted:x,playbackRate:b}=h;t({type:d,id:s.getId(h),currentTime:g,volume:v,muted:x,playbackRate:b})}),i.media||500)),u=[gs("play",l(0),a),gs("pause",l(1),a),gs("seeked",l(2),a),gs("volumechange",l(3),a),gs("ratechange",l(4),a)];return Jt(()=>{u.forEach(d=>d())})}function HPe({fontCb:t,doc:e}){const n=e.defaultView;if(!n)return()=>{};const r=[],s=new WeakMap,i=n.FontFace;n.FontFace=function(u,d,p){const h=new i(u,d,p);return s.set(h,{family:u,buffer:typeof d!="string",descriptors:p,fontSource:typeof d=="string"?d:JSON.stringify(Array.from(new Uint8Array(d)))}),h};const a=Oj(e.fonts,"add",function(l){return function(u){return a_(Jt(()=>{const d=s.get(u);d&&(t(d),s.delete(u))}),0),l.apply(this,[u])}});return r.push(()=>{n.FontFace=i}),r.push(a),Jt(()=>{r.forEach(l=>l())})}function GPe(t){const{doc:e,mirror:n,blockClass:r,blockSelector:s,unblockSelector:i,selectionCb:a}=t;let l=!0;const u=Jt(()=>{const d=e.getSelection();if(!d||l&&ta([d,"optionalAccess",g=>g.isCollapsed]))return;l=d.isCollapsed||!1;const p=[],h=d.rangeCount||0;for(let g=0;g<h;g++){const v=d.getRangeAt(g),{startContainer:x,startOffset:b,endContainer:E,endOffset:S}=v;ti(x,r,s,i,!0)||ti(E,r,s,i,!0)||p.push({start:n.getId(x),startOffset:b,end:n.getId(E),endOffset:S})}a({ranges:p})});return u(),gs("selectionchange",u)}function WPe({doc:t,customElementCb:e}){const n=t.defaultView;return!n||!n.customElements?()=>{}:Oj(n.customElements,"define",function(s){return function(i,a,l){try{e({define:{name:i}})}catch{}return s.apply(this,[i,a,l])}})}function YPe(t,e={}){const n=t.doc.defaultView;if(!n)return()=>{};let r;t.recordDOM&&(r=AW(t,t.doc));const s=LPe(t),i=$Pe(t),a=NW(t),l=zPe(t,{win:n}),u=UPe(t),d=VPe(t);let p=()=>{},h=()=>{},g=()=>{},v=()=>{};t.recordDOM&&(p=BPe(t,{win:n}),h=RW(t,t.doc),g=qPe(t,{win:n}),t.collectFonts&&(v=HPe(t)));const x=GPe(t),b=WPe(t),E=[];for(const S of t.plugins)E.push(S.observer(S.callback,n,S.options));return Jt(()=>{rf.forEach(S=>S.reset()),ta([r,"optionalAccess",S=>S.disconnect,"call",S=>S()]),s(),i(),a(),l(),u(),d(),p(),h(),g(),v(),x(),b(),E.forEach(S=>S())})}function Fy(t){return typeof window[t]<"u"}function Uy(t){return!!(typeof window[t]<"u"&&window[t].prototype&&"insertRule"in window[t].prototype&&"deleteRule"in window[t].prototype)}class aA{constructor(e){this.generateIdFn=e,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(e,n,r,s){const i=r||this.getIdToRemoteIdMap(e),a=s||this.getRemoteIdToIdMap(e);let l=i.get(n);return l||(l=this.generateIdFn(),i.set(n,l),a.set(l,n)),l}getIds(e,n){const r=this.getIdToRemoteIdMap(e),s=this.getRemoteIdToIdMap(e);return n.map(i=>this.getId(e,i,r,s))}getRemoteId(e,n,r){const s=r||this.getRemoteIdToIdMap(e);if(typeof n!="number")return n;const i=s.get(n);return i||-1}getRemoteIds(e,n){const r=this.getRemoteIdToIdMap(e);return n.map(s=>this.getRemoteId(e,s,r))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let n=this.iframeIdToRemoteIdMap.get(e);return n||(n=new Map,this.iframeIdToRemoteIdMap.set(e,n)),n}getRemoteIdToIdMap(e){let n=this.iframeRemoteIdToIdMap.get(e);return n||(n=new Map,this.iframeRemoteIdToIdMap.set(e,n)),n}}function xz(t){let e,n=t[0],r=1;for(;r<t.length;){const s=t[r],i=t[r+1];if(r+=2,(s==="optionalAccess"||s==="optionalCall")&&n==null)return;s==="access"||s==="optionalAccess"?(e=n,n=i(n)):(s==="call"||s==="optionalCall")&&(n=i((...a)=>n.call(e,...a)),e=void 0)}return n}class KPe{constructor(){this.crossOriginIframeMirror=new aA(Mj),this.crossOriginIframeRootIdMap=new WeakMap}addIframe(){}addLoadListener(){}attachIframe(){}}class XPe{constructor(e){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new aA(Mj),this.crossOriginIframeRootIdMap=new WeakMap,this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new aA(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,n){this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:n}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),xz([this,"access",s=>s.loadListener,"optionalCall",s=>s(e)]);const r=Ij(e);r&&r.adoptedStyleSheets&&r.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(r.adoptedStyleSheets,this.mirror.getId(r))}handleMessage(e){const n=e;if(n.data.type!=="rrweb"||n.origin!==n.data.origin||!e.source)return;const s=this.crossOriginIframeMap.get(e.source);if(!s)return;const i=this.transformCrossOriginEvent(s,n.data.event);i&&this.wrappedEmit(i,n.data.isCheckout)}transformCrossOriginEvent(e,n){switch(n.type){case Ut.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(n.data.node,e);const r=n.data.node.id;return this.crossOriginIframeRootIdMap.set(e,r),this.patchRootIdOnNode(n.data.node,r),{timestamp:n.timestamp,type:Ut.IncrementalSnapshot,data:{source:Ct.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:n.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Ut.Meta:case Ut.Load:case Ut.DomContentLoaded:return!1;case Ut.Plugin:return n;case Ut.Custom:return this.replaceIds(n.data.payload,e,["id","parentId","previousId","nextId"]),n;case Ut.IncrementalSnapshot:switch(n.data.source){case Ct.Mutation:return n.data.adds.forEach(r=>{this.replaceIds(r,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,e);const s=this.crossOriginIframeRootIdMap.get(e);s&&this.patchRootIdOnNode(r.node,s)}),n.data.removes.forEach(r=>{this.replaceIds(r,e,["parentId","id"])}),n.data.attributes.forEach(r=>{this.replaceIds(r,e,["id"])}),n.data.texts.forEach(r=>{this.replaceIds(r,e,["id"])}),n;case Ct.Drag:case Ct.TouchMove:case Ct.MouseMove:return n.data.positions.forEach(r=>{this.replaceIds(r,e,["id"])}),n;case Ct.ViewportResize:return!1;case Ct.MediaInteraction:case Ct.MouseInteraction:case Ct.Scroll:case Ct.CanvasMutation:case Ct.Input:return this.replaceIds(n.data,e,["id"]),n;case Ct.StyleSheetRule:case Ct.StyleDeclaration:return this.replaceIds(n.data,e,["id"]),this.replaceStyleIds(n.data,e,["styleId"]),n;case Ct.Font:return n;case Ct.Selection:return n.data.ranges.forEach(r=>{this.replaceIds(r,e,["start","end"])}),n;case Ct.AdoptedStyleSheet:return this.replaceIds(n.data,e,["id"]),this.replaceStyleIds(n.data,e,["styleIds"]),xz([n,"access",r=>r.data,"access",r=>r.styles,"optionalAccess",r=>r.forEach,"call",r=>r(s=>{this.replaceStyleIds(s,e,["styleId"])})]),n}}return!1}replace(e,n,r,s){for(const i of s)!Array.isArray(n[i])&&typeof n[i]!="number"||(Array.isArray(n[i])?n[i]=e.getIds(r,n[i]):n[i]=e.getId(r,n[i]));return n}replaceIds(e,n,r){return this.replace(this.crossOriginIframeMirror,e,n,r)}replaceStyleIds(e,n,r){return this.replace(this.crossOriginIframeStyleMirror,e,n,r)}replaceIdOnNode(e,n){this.replaceIds(e,n,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(r=>{this.replaceIdOnNode(r,n)})}patchRootIdOnNode(e,n){e.type!==kr.Document&&!e.rootId&&(e.rootId=n),"childNodes"in e&&e.childNodes.forEach(r=>{this.patchRootIdOnNode(r,n)})}}class QPe{init(){}addShadowRoot(){}observeAttachShadow(){}reset(){}}class JPe{constructor(e){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,n){if(!bm(e)||this.shadowDoms.has(e))return;this.shadowDoms.add(e),this.bypassOptions.canvasManager.addShadowRoot(e);const r=AW({...this.bypassOptions,doc:n,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(NW({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),a_(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(e.host)),this.restoreHandlers.push(RW({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){const n=Ij(e),r=RPe(e);!n||!r||this.patchAttachShadow(r.Element,n)}patchAttachShadow(e,n){const r=this;this.restoreHandlers.push(Oj(e.prototype,"attachShadow",function(s){return function(i){const a=s.call(this,i);return this.shadowRoot&&TW(this)&&r.addShadowRoot(this.shadowRoot,n),a}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch{}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet,this.bypassOptions.canvasManager.resetShadowRoots()}}class bz{reset(){}freeze(){}unfreeze(){}lock(){}unlock(){}snapshot(){}addWindow(){}addShadowRoot(){}resetShadowRoots(){}}class ZPe{constructor(e){this.trackedLinkElements=new WeakSet,this.styleMirror=new kPe,this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,n){"_cssText"in n.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:n.id,attributes:n.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,n){if(e.length===0)return;const r={id:n,styleIds:[]},s=[];for(const i of e){let a;this.styleMirror.has(i)?a=this.styleMirror.getId(i):(a=this.styleMirror.add(i),s.push({styleId:a,rules:Array.from(i.rules||CSSRule,(l,u)=>({rule:cW(l),index:u}))})),r.styleIds.push(a)}s.length>0&&(r.styles=s),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}class eIe{constructor(){this.nodeMap=new WeakMap,this.active=!1}inOtherBuffer(e,n){const r=this.nodeMap.get(e);return r&&Array.from(r).some(s=>s!==n)}add(e,n){this.active||(this.active=!0,APe(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(n))}destroy(){}}let Xn,zb;try{if(Array.from([1],t=>t*2)[0]!==2){const t=document.createElement("iframe");document.body.appendChild(t),Array.from=fx([t,"access",e=>e.contentWindow,"optionalAccess",e=>e.Array,"access",e=>e.from])||Array.from,document.body.removeChild(t)}}catch(t){console.debug("Unable to override Array.from",t)}const Ki=Z2e();function Io(t={}){const{emit:e,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:s="rr-block",blockSelector:i=null,unblockSelector:a=null,ignoreClass:l="rr-ignore",ignoreSelector:u=null,maskAllText:d=!1,maskTextClass:p="rr-mask",unmaskTextClass:h=null,maskTextSelector:g=null,unmaskTextSelector:v=null,inlineStylesheet:x=!0,maskAllInputs:b,maskInputOptions:E,slimDOMOptions:S,maskAttributeFn:k,maskInputFn:T,maskTextFn:R,maxCanvasSize:j=null,packFn:A,sampling:N={},dataURLOptions:M={},mousemoveWait:I,recordDOM:O=!0,recordCanvas:L=!1,recordCrossOriginIframes:z=!1,recordAfter:H=t.recordAfter==="DOMContentLoaded"?t.recordAfter:"load",userTriggeredOnInput:V=!1,collectFonts:X=!1,inlineImages:F=!1,plugins:W,keepIframeSrcFn:G=()=>!1,ignoreCSSAttributes:ee=new Set([]),errorHandler:P,onMutation:ie,getCanvasManager:ue}=t;IPe(P);const D=z?window.parent===window:!0;let ne=!1;if(!D)try{window.parent.document&&(ne=!1)}catch{ne=!0}if(D&&!e)throw new Error("emit function is required");if(!D&&!ne)return()=>{};I!==void 0&&N.mousemove===void 0&&(N.mousemove=I),Ki.reset();const fe=b===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:E!==void 0?E:{},q=S===!0||S==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:S==="all",headMetaDescKeywords:S==="all"}:S||{};EPe();let K,Y=0;const Z=Fe=>{for(const ct of W||[])ct.eventProcessor&&(Fe=ct.eventProcessor(Fe));return A&&!ne&&(Fe=A(Fe)),Fe};Xn=(Fe,ct)=>{const Ie=Fe;if(Ie.timestamp=Lb(),fx([rf,"access",et=>et[0],"optionalAccess",et=>et.isFrozen,"call",et=>et()])&&Ie.type!==Ut.FullSnapshot&&!(Ie.type===Ut.IncrementalSnapshot&&Ie.data.source===Ct.Mutation)&&rf.forEach(et=>et.unfreeze()),D)fx([e,"optionalCall",et=>et(Z(Ie),ct)]);else if(ne){const et={type:"rrweb",event:Z(Ie),origin:window.location.origin,isCheckout:ct};window.parent.postMessage(et,"*")}if(Ie.type===Ut.FullSnapshot)K=Ie,Y=0;else if(Ie.type===Ut.IncrementalSnapshot){if(Ie.data.source===Ct.Mutation&&Ie.data.isAttachIframe)return;Y++;const et=r&&Y>=r,ot=n&&K&&Ie.timestamp-K.timestamp>n;(et||ot)&&lt(!0)}};const U=Fe=>{Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.Mutation,...Fe}})},J=Fe=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.Scroll,...Fe}}),oe=Fe=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.CanvasMutation,...Fe}}),pe=Fe=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.AdoptedStyleSheet,...Fe}}),ye=new ZPe({mutationCb:U,adoptedStyleSheetCb:pe}),je=typeof __RRWEB_EXCLUDE_IFRAME__=="boolean"&&__RRWEB_EXCLUDE_IFRAME__?new KPe:new XPe({mirror:Ki,mutationCb:U,stylesheetManager:ye,recordCrossOriginIframes:z,wrappedEmit:Xn});for(const Fe of W||[])Fe.getMirror&&Fe.getMirror({nodeMirror:Ki,crossOriginIframeMirror:je.crossOriginIframeMirror,crossOriginIframeStyleMirror:je.crossOriginIframeStyleMirror});const Ne=new eIe,Ae=nIe(ue,{mirror:Ki,win:window,mutationCb:Fe=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.CanvasMutation,...Fe}}),recordCanvas:L,blockClass:s,blockSelector:i,unblockSelector:a,maxCanvasSize:j,sampling:N.canvas,dataURLOptions:M,errorHandler:P}),He=typeof __RRWEB_EXCLUDE_SHADOW_DOM__=="boolean"&&__RRWEB_EXCLUDE_SHADOW_DOM__?new QPe:new JPe({mutationCb:U,scrollCb:J,bypassOptions:{onMutation:ie,blockClass:s,blockSelector:i,unblockSelector:a,maskAllText:d,maskTextClass:p,unmaskTextClass:h,maskTextSelector:g,unmaskTextSelector:v,inlineStylesheet:x,maskInputOptions:fe,dataURLOptions:M,maskAttributeFn:k,maskTextFn:R,maskInputFn:T,recordCanvas:L,inlineImages:F,sampling:N,slimDOMOptions:q,iframeManager:je,stylesheetManager:ye,canvasManager:Ae,keepIframeSrcFn:G,processedNodeManager:Ne},mirror:Ki}),lt=(Fe=!1)=>{if(!O)return;Xn({type:Ut.Meta,data:{href:window.location.href,width:bW(),height:xW()}},Fe),ye.reset(),He.init(),rf.forEach(Ie=>Ie.lock());const ct=wPe(document,{mirror:Ki,blockClass:s,blockSelector:i,unblockSelector:a,maskAllText:d,maskTextClass:p,unmaskTextClass:h,maskTextSelector:g,unmaskTextSelector:v,inlineStylesheet:x,maskAllInputs:fe,maskAttributeFn:k,maskInputFn:T,maskTextFn:R,slimDOM:q,dataURLOptions:M,recordCanvas:L,inlineImages:F,onSerialize:Ie=>{SW(Ie,Ki)&&je.addIframe(Ie),EW(Ie,Ki)&&ye.trackLinkElement(Ie),sA(Ie)&&He.addShadowRoot(Ie.shadowRoot,document)},onIframeLoad:(Ie,et)=>{je.attachIframe(Ie,et),Ie.contentWindow&&Ae.addWindow(Ie.contentWindow),He.observeAttachShadow(Ie)},onStylesheetLoad:(Ie,et)=>{ye.attachLinkElement(Ie,et)},keepIframeSrcFn:G});if(!ct)return console.warn("Failed to snapshot the document");Xn({type:Ut.FullSnapshot,data:{node:ct,initialOffset:yW(window)}}),rf.forEach(Ie=>Ie.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&ye.adoptStyleSheets(document.adoptedStyleSheets,Ki.getId(document))};zb=lt;try{const Fe=[],ct=et=>Jt(YPe)({onMutation:ie,mutationCb:U,mousemoveCb:(ot,dr)=>Xn({type:Ut.IncrementalSnapshot,data:{source:dr,positions:ot}}),mouseInteractionCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.MouseInteraction,...ot}}),scrollCb:J,viewportResizeCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.ViewportResize,...ot}}),inputCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.Input,...ot}}),mediaInteractionCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.MediaInteraction,...ot}}),styleSheetRuleCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.StyleSheetRule,...ot}}),styleDeclarationCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.StyleDeclaration,...ot}}),canvasMutationCb:oe,fontCb:ot=>Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.Font,...ot}}),selectionCb:ot=>{Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.Selection,...ot}})},customElementCb:ot=>{Xn({type:Ut.IncrementalSnapshot,data:{source:Ct.CustomElement,...ot}})},blockClass:s,ignoreClass:l,ignoreSelector:u,maskAllText:d,maskTextClass:p,unmaskTextClass:h,maskTextSelector:g,unmaskTextSelector:v,maskInputOptions:fe,inlineStylesheet:x,sampling:N,recordDOM:O,recordCanvas:L,inlineImages:F,userTriggeredOnInput:V,collectFonts:X,doc:et,maskAttributeFn:k,maskInputFn:T,maskTextFn:R,keepIframeSrcFn:G,blockSelector:i,unblockSelector:a,slimDOMOptions:q,dataURLOptions:M,mirror:Ki,iframeManager:je,stylesheetManager:ye,shadowDomManager:He,processedNodeManager:Ne,canvasManager:Ae,ignoreCSSAttributes:ee,plugins:fx([W,"optionalAccess",ot=>ot.filter,"call",ot=>ot(dr=>dr.observer),"optionalAccess",ot=>ot.map,"call",ot=>ot(dr=>({observer:dr.observer,options:dr.options,callback:be=>Xn({type:Ut.Plugin,data:{plugin:dr.name,payload:be}})}))])||[]},{});je.addLoadListener(et=>{try{Fe.push(ct(et.contentDocument))}catch(ot){console.warn(ot)}});const Ie=()=>{lt(),Fe.push(ct(document))};return document.readyState==="interactive"||document.readyState==="complete"?Ie():(Fe.push(gs("DOMContentLoaded",()=>{Xn({type:Ut.DomContentLoaded,data:{}}),H==="DOMContentLoaded"&&Ie()})),Fe.push(gs("load",()=>{Xn({type:Ut.Load,data:{}}),H==="load"&&Ie()},window))),()=>{Fe.forEach(et=>et()),Ne.destroy(),zb=void 0,DPe()}}catch(Fe){console.warn(Fe)}}function tIe(t){if(!zb)throw new Error("please take full snapshot after start recording");zb(t)}Io.mirror=Ki;Io.takeFullSnapshot=tIe;function nIe(t,e){try{return t?t(e):new bz}catch{return console.warn("Unable to initialize CanvasManager"),new bz}}const rIe=3,sIe=5;function Dj(t){return t>9999999999?t:t*1e3}function rk(t){return t>9999999999?t/1e3:t}function zg(t,e){e.category!=="sentry.transaction"&&(["ui.click","ui.input"].includes(e.category)?t.triggerUserActivity():t.checkAndHandleExpiredSession(),t.addUpdate(()=>(t.throttledAddEvent({type:Ut.Custom,timestamp:(e.timestamp||0)*1e3,data:{tag:"breadcrumb",payload:Zi(e,10,1e3)}}),e.category==="console")))}const iIe="button,a";function jW(t){return t.closest(iIe)||t}function MW(t){const e=OW(t);return!e||!(e instanceof Element)?e:jW(e)}function OW(t){return aIe(t)?t.target:t}function aIe(t){return typeof t=="object"&&!!t&&"target"in t}let Ll;function oIe(t){return Ll||(Ll=[],lIe()),Ll.push(t),()=>{const e=Ll?Ll.indexOf(t):-1;e>-1&&Ll.splice(e,1)}}function lIe(){$s(Tn,"open",function(t){return function(...e){if(Ll)try{Ll.forEach(n=>n())}catch{}return t.apply(Tn,e)}})}const cIe=new Set([Ct.Mutation,Ct.StyleSheetRule,Ct.StyleDeclaration,Ct.AdoptedStyleSheet,Ct.CanvasMutation,Ct.Selection,Ct.MediaInteraction]);function uIe(t,e,n){t.handleClick(e,n)}class dIe{constructor(e,n,r=zg){this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=n.timeout/1e3,this._threshold=n.threshold/1e3,this._scrollTimeout=n.scrollTimeout/1e3,this._replay=e,this._ignoreSelector=n.ignoreSelector,this._addBreadcrumbEvent=r}addListeners(){const e=oIe(()=>{this._lastMutation=_z()});this._teardown=()=>{e(),this._clicks=[],this._lastMutation=0,this._lastScroll=0}}removeListeners(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)}handleClick(e,n){if(hIe(n,this._ignoreSelector)||!pIe(e))return;const r={timestamp:rk(e.timestamp),clickBreadcrumb:e,clickCount:0,node:n};this._clicks.some(s=>s.node===r.node&&Math.abs(s.timestamp-r.timestamp)<1)||(this._clicks.push(r),this._clicks.length===1&&this._scheduleCheckClicks())}registerMutation(e=Date.now()){this._lastMutation=rk(e)}registerScroll(e=Date.now()){this._lastScroll=rk(e)}registerClick(e){const n=jW(e);this._handleMultiClick(n)}_handleMultiClick(e){this._getClicks(e).forEach(n=>{n.clickCount++})}_getClicks(e){return this._clicks.filter(n=>n.node===e)}_checkClicks(){const e=[],n=_z();this._clicks.forEach(r=>{!r.mutationAfter&&this._lastMutation&&(r.mutationAfter=r.timestamp<=this._lastMutation?this._lastMutation-r.timestamp:void 0),!r.scrollAfter&&this._lastScroll&&(r.scrollAfter=r.timestamp<=this._lastScroll?this._lastScroll-r.timestamp:void 0),r.timestamp+this._timeout<=n&&e.push(r)});for(const r of e){const s=this._clicks.indexOf(r);s>-1&&(this._generateBreadcrumbs(r),this._clicks.splice(s,1))}this._clicks.length&&this._scheduleCheckClicks()}_generateBreadcrumbs(e){const n=this._replay,r=e.scrollAfter&&e.scrollAfter<=this._scrollTimeout,s=e.mutationAfter&&e.mutationAfter<=this._threshold,i=!r&&!s,{clickCount:a,clickBreadcrumb:l}=e;if(i){const u=Math.min(e.mutationAfter||this._timeout,this._timeout)*1e3,d=u<this._timeout*1e3?"mutation":"timeout",p={type:"default",message:l.message,timestamp:l.timestamp,category:"ui.slowClickDetected",data:{...l.data,url:Tn.location.href,route:n.getCurrentRoute(),timeAfterClickMs:u,endReason:d,clickCount:a||1}};this._addBreadcrumbEvent(n,p);return}if(a>1){const u={type:"default",message:l.message,timestamp:l.timestamp,category:"ui.multiClick",data:{...l.data,url:Tn.location.href,route:n.getCurrentRoute(),clickCount:a,metric:!0}};this._addBreadcrumbEvent(n,u)}}_scheduleCheckClicks(){this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=Bf(()=>this._checkClicks(),1e3)}}const fIe=["A","BUTTON","INPUT"];function hIe(t,e){return!!(!fIe.includes(t.tagName)||t.tagName==="INPUT"&&!["submit","button"].includes(t.getAttribute("type")||"")||t.tagName==="A"&&(t.hasAttribute("download")||t.hasAttribute("target")&&t.getAttribute("target")!=="_self")||e&&t.matches(e))}function pIe(t){return!!(t.data&&typeof t.data.nodeId=="number"&&t.timestamp)}function _z(){return Date.now()/1e3}function mIe(t,e){try{if(!gIe(e))return;const{source:n}=e.data;if(cIe.has(n)&&t.registerMutation(e.timestamp),n===Ct.Scroll&&t.registerScroll(e.timestamp),vIe(e)){const{type:r,id:s}=e.data,i=Io.mirror.getNode(s);i instanceof HTMLElement&&r===ps.Click&&t.registerClick(i)}}catch{}}function gIe(t){return t.type===rIe}function vIe(t){return t.data.source===Ct.MouseInteraction}function Oa(t){return{timestamp:Date.now()/1e3,type:"default",...t}}var Fb;(function(t){t[t.Document=0]="Document",t[t.DocumentType=1]="DocumentType",t[t.Element=2]="Element",t[t.Text=3]="Text",t[t.CDATA=4]="CDATA",t[t.Comment=5]="Comment"})(Fb||(Fb={}));const yIe=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function xIe(t){const e={};!t["data-sentry-component"]&&t["data-sentry-element"]&&(t["data-sentry-component"]=t["data-sentry-element"]);for(const n in t)if(yIe.has(n)){let r=n;(n==="data-testid"||n==="data-test-id")&&(r="testId"),e[r]=t[n]}return e}const bIe=t=>e=>{if(!t.isEnabled())return;const n=_Ie(e);if(!n)return;const r=e.name==="click",s=r?e.event:void 0;r&&t.clickDetector&&s&&s.target&&!s.altKey&&!s.metaKey&&!s.ctrlKey&&!s.shiftKey&&uIe(t.clickDetector,n,MW(e.event)),zg(t,n)};function PW(t,e){const n=Io.mirror.getId(t),r=n&&Io.mirror.getNode(n),s=r&&Io.mirror.getMeta(r),i=s&&SIe(s)?s:null;return{message:e,data:i?{nodeId:n,node:{id:n,tagName:i.tagName,textContent:Array.from(i.childNodes).map(a=>a.type===Fb.Text&&a.textContent).filter(Boolean).map(a=>a.trim()).join(""),attributes:xIe(i.attributes)}}:{}}}function _Ie(t){const{target:e,message:n}=wIe(t);return Oa({category:`ui.${t.name}`,...PW(e,n)})}function wIe(t){const e=t.name==="click";let n,r=null;try{r=e?MW(t.event):OW(t.event),n=Go(r,{maxStringLength:200})||"<unknown>"}catch{n="<unknown>"}return{target:r,message:n}}function SIe(t){return t.type===Fb.Element}function EIe(t,e){if(!t.isEnabled())return;t.updateUserActivity();const n=kIe(e);n&&zg(t,n)}function kIe(t){const{metaKey:e,shiftKey:n,ctrlKey:r,altKey:s,key:i,target:a}=t;if(!a||TIe(a)||!i)return null;const l=e||r||s,u=i.length===1;if(!l&&u)return null;const d=Go(a,{maxStringLength:200})||"<unknown>",p=PW(a,d);return Oa({category:"ui.keyDown",message:d,data:{...p.data,metaKey:e,shiftKey:n,ctrlKey:r,altKey:s,key:i}})}function TIe(t){return t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable}const CIe={resource:MIe,paint:RIe,navigation:jIe};function By(t,e){return({metric:n})=>void e.replayPerformanceEntries.push(t(n))}function AIe(t){return t.map(NIe).filter(Boolean)}function NIe(t){const e=CIe[t.entryType];return e?e(t):null}function Hf(t){return((bs||Tn.performance.timeOrigin)+t)/1e3}function RIe(t){const{duration:e,entryType:n,name:r,startTime:s}=t,i=Hf(s);return{type:n,name:r,start:i,end:i+e,data:void 0}}function jIe(t){const{entryType:e,name:n,decodedBodySize:r,duration:s,domComplete:i,encodedBodySize:a,domContentLoadedEventStart:l,domContentLoadedEventEnd:u,domInteractive:d,loadEventStart:p,loadEventEnd:h,redirectCount:g,startTime:v,transferSize:x,type:b}=t;return s===0?null:{type:`${e}.${b}`,start:Hf(v),end:Hf(i),name:n,data:{size:x,decodedBodySize:r,encodedBodySize:a,duration:s,domInteractive:d,domContentLoadedEventStart:l,domContentLoadedEventEnd:u,loadEventStart:p,loadEventEnd:h,domComplete:i,redirectCount:g}}}function MIe(t){const{entryType:e,initiatorType:n,name:r,responseEnd:s,startTime:i,decodedBodySize:a,encodedBodySize:l,responseStatus:u,transferSize:d}=t;return["fetch","xmlhttprequest"].includes(n)?null:{type:`${e}.${n}`,start:Hf(i),end:Hf(s),name:r,data:{size:d,statusCode:u,decodedBodySize:a,encodedBodySize:l}}}function OIe(t){const e=t.entries[t.entries.length-1],n=e&&e.element?[e.element]:void 0;return o_(t,"largest-contentful-paint",n)}function PIe(t){return t.sources!==void 0}function IIe(t){const e=[],n=[];for(const r of t.entries)if(PIe(r)){const s=[];for(const i of r.sources)if(i.node){n.push(i.node);const a=Io.mirror.getId(i.node);a&&s.push(a)}e.push({value:r.value,nodeIds:s.length?s:void 0})}return o_(t,"cumulative-layout-shift",n,e)}function DIe(t){const e=t.entries[t.entries.length-1],n=e&&e.target?[e.target]:void 0;return o_(t,"first-input-delay",n)}function LIe(t){const e=t.entries[t.entries.length-1],n=e&&e.target?[e.target]:void 0;return o_(t,"interaction-to-next-paint",n)}function o_(t,e,n,r){const s=t.value,i=t.rating,a=Hf(s);return{type:"web-vital",name:e,start:a,end:a,data:{value:s,size:s,rating:i,nodeIds:n?n.map(l=>Io.mirror.getId(l)):void 0,attributions:r}}}function $Ie(t){function e(s){t.performanceEntries.includes(s)||t.performanceEntries.push(s)}function n({entries:s}){s.forEach(e)}const r=[];return["navigation","paint","resource"].forEach(s=>{r.push(Uf(s,n))}),r.push(QG(By(OIe,t)),Tj(By(IIe,t)),JG(By(DIe,t)),ZG(By(LIe,t))),()=>{r.forEach(s=>s())}}const xt=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,zIe='var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([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]),i=new t([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]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<<t[a-1];var s=new r(i[30]);for(a=1;a<30;++a)for(var o=i[a];o<i[a+1];++o)s[o]=o-i[a]<<5|a;return{b:i,r:s}},o=s(e,2),f=o.b,h=o.r;f[28]=258,h[258]=28;for(var l=s(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a<i;++a)t[a]&&++s[t[a]-1];var o,f=new n(r);for(a=1;a<r;++a)f[a]=f[a-1]+s[a-1]<<1;if(e){o=new n(1<<r);var h=15-r;for(a=0;a<i;++a)if(t[a])for(var l=a<<4|t[a],c=r-t[a],v=f[t[a]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>h]=l}else for(o=new n(i),a=0;a<i;++a)t[a]&&(o[a]=u[f[t[a]-1]++]>>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],a=0;a<r.length;++a)r[a]&&i.push({s:a,f:r[a]});var s=i.length,o=i.slice();if(!s)return{t:F,l:0};if(1==s){var f=new t(i[0].s+1);return f[i[0].s]=1,{t:f,l:1}}i.sort((function(t,n){return t.f-n.f})),i.push({s:-1,f:25001});var h=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:h.f+l.f,l:h,r:l};c!=s-1;)h=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:h.f+l.f,l:h,r:l};var d=o[0].s;for(a=1;a<s;++a)o[a].s>d&&(d=o[a].s);var g=new n(d+1),w=A(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<<y;for(o.sort((function(t,n){return g[n.s]-g[t.s]||t.f-n.f}));a<s;++a){var b=o[a].s;if(!(g[b]>e))break;p+=m-(1<<w-g[b]),g[b]=e}for(p>>=y;p>0;){var M=o[a].s;g[M]<e?p-=1<<e-g[M]++-1:++a}for(;a>=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&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(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a<e;++a)t[i+a+4]=r[a];return 8*(i+4+e)},U=function(t,r,s,o,f,h,l,u,c,v,m){z(r,m++,s),++f[256];for(var b=x(f,15),M=b.t,E=b.l,A=x(h,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[a[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s<o;++s)i+=e+=r[s];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=C[s-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(a[t]^a[t+1]<<A^a[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!w)){p=U(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$<Z&&a[j+$]==a[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=a[j],++I[a[j]];p=U(a,g,w,F,I,S,O,q,G,j-G,p),w||(c.r=7&p|g[p/8|0]<<3,p-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+w;j+=65535){var st=j+65535;st>=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),J="undefined"!=typeof TextEncoder&&new TextEncoder,K="undefined"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),a=0,s=function(t){i[a++]=t},o=0;o<e;++o){if(a+5>i.length){var f=new t(a+8+(e-o<<1));f.set(i),i=f}var h=n.charCodeAt(o);h<128||r?s(h):h<2048?(s(192|h>>6),s(128|63&h)):h>55295&&h<57344?(s(240|(h=65536+(1047552&h)|1023&n.charCodeAt(++o))>>18),s(128|h>>12&63),s(128|h>>6&63),s(128|63&h)):(s(224|h>>12),s(128|h>>6&63),s(128|63&h))}return b(i,0,a)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),a=i.length;return q(i,n),j(i,a-8,r.d()),j(i,a-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new H,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&"function"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});';function FIe(){const t=new Blob([zIe]);return URL.createObjectURL(t)}const wz=["info","warn","error","log"],mx="[Replay] ";function sk(t,e="info"){ic({category:"console",data:{logger:"replay"},level:e,message:`${mx}${t}`},{level:e})}function UIe(){let t=!1,e=!1;const n={exception:()=>{},infoTick:()=>{},setConfig:r=>{t=r.captureExceptions,e=r.traceInternals}};return xt?(wz.forEach(r=>{n[r]=(...s)=>{ze[r](mx,...s),e&&sk(s.join(""),IG(r))}}),n.exception=(r,...s)=>{s.length&&n.error&&n.error(...s),ze.error(mx,r),t?SG(r):e&&sk(r,"error")},n.infoTick=(...r)=>{ze.info(mx,...r),e&&setTimeout(()=>sk(r[0]),0)}):wz.forEach(r=>{n[r]=()=>{}}),n}const St=UIe();class Lj extends Error{constructor(){super(`Event buffer exceeded maximum size of ${Rj}.`)}}class IW{constructor(){this.events=[],this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return this.events.length>0}get type(){return"sync"}destroy(){this.events=[]}async addEvent(e){const n=JSON.stringify(e).length;if(this._totalSize+=n,this._totalSize>Rj)throw new Lj;this.events.push(e)}finish(){return new Promise(e=>{const n=this.events;this.clear(),e(JSON.stringify(n))})}clear(){this.events=[],this._totalSize=0,this.hasCheckout=!1}getEarliestTimestamp(){const e=this.events.map(n=>n.timestamp).sort()[0];return e?Dj(e):null}}class BIe{constructor(e){this._worker=e,this._id=0}ensureReady(){return this._ensureReadyPromise?this._ensureReadyPromise:(this._ensureReadyPromise=new Promise((e,n)=>{this._worker.addEventListener("message",({data:r})=>{r.success?e():n()},{once:!0}),this._worker.addEventListener("error",r=>{n(r)},{once:!0})}),this._ensureReadyPromise)}destroy(){xt&&St.info("Destroying compression worker"),this._worker.terminate()}postMessage(e,n){const r=this._getAndIncrementId();return new Promise((s,i)=>{const a=({data:l})=>{const u=l;if(u.method===e&&u.id===r){if(this._worker.removeEventListener("message",a),!u.success){xt&&St.error("Error in compression worker: ",u.response),i(new Error("Error in compression worker"));return}s(u.response)}};this._worker.addEventListener("message",a),this._worker.postMessage({id:r,method:e,arg:n})})}_getAndIncrementId(){return this._id++}}class qIe{constructor(e){this._worker=new BIe(e),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return!!this._earliestTimestamp}get type(){return"worker"}ensureReady(){return this._worker.ensureReady()}destroy(){this._worker.destroy()}addEvent(e){const n=Dj(e.timestamp);(!this._earliestTimestamp||n<this._earliestTimestamp)&&(this._earliestTimestamp=n);const r=JSON.stringify(e);return this._totalSize+=r.length,this._totalSize>Rj?Promise.reject(new Lj):this._sendEventToWorker(r)}finish(){return this._finishRequest()}clear(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,e=>{xt&&St.exception(e,'Sending "clear" message to worker failed',e)})}getEarliestTimestamp(){return this._earliestTimestamp}_sendEventToWorker(e){return this._worker.postMessage("addEvent",e)}async _finishRequest(){const e=await this._worker.postMessage("finish");return this._earliestTimestamp=null,this._totalSize=0,e}}class VIe{constructor(e){this._fallback=new IW,this._compression=new qIe(e),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}get waitForCheckout(){return this._used.waitForCheckout}get type(){return this._used.type}get hasEvents(){return this._used.hasEvents}get hasCheckout(){return this._used.hasCheckout}set hasCheckout(e){this._used.hasCheckout=e}set waitForCheckout(e){this._used.waitForCheckout=e}destroy(){this._fallback.destroy(),this._compression.destroy()}clear(){return this._used.clear()}getEarliestTimestamp(){return this._used.getEarliestTimestamp()}addEvent(e){return this._used.addEvent(e)}async finish(){return await this.ensureWorkerIsLoaded(),this._used.finish()}ensureWorkerIsLoaded(){return this._ensureWorkerIsLoadedPromise}async _ensureWorkerIsLoaded(){try{await this._compression.ensureReady()}catch(e){xt&&St.exception(e,"Failed to load the compression worker, falling back to simple buffer");return}await this._switchToCompressionWorker()}async _switchToCompressionWorker(){const{events:e,hasCheckout:n,waitForCheckout:r}=this._fallback,s=[];for(const i of e)s.push(this._compression.addEvent(i));this._compression.hasCheckout=n,this._compression.waitForCheckout=r,this._used=this._compression;try{await Promise.all(s),this._fallback.clear()}catch(i){xt&&St.exception(i,"Failed to add events when switching buffers.")}}}function HIe({useCompression:t,workerUrl:e}){if(t&&window.Worker){const n=GIe(e);if(n)return n}return xt&&St.info("Using simple buffer"),new IW}function GIe(t){try{const e=t||WIe();if(!e)return;xt&&St.info(`Using compression worker${t?` from ${t}`:""}`);const n=new Worker(e);return new VIe(n)}catch(e){xt&&St.exception(e,"Failed to create compression worker")}}function WIe(){return typeof __SENTRY_EXCLUDE_REPLAY_WORKER__>"u"||!__SENTRY_EXCLUDE_REPLAY_WORKER__?FIe():""}function $j(){try{return"sessionStorage"in Tn&&!!Tn.sessionStorage}catch{return!1}}function YIe(t){KIe(),t.session=void 0}function KIe(){if($j())try{Tn.sessionStorage.removeItem(Aj)}catch{}}function DW(t){return t===void 0?!1:Math.random()<t}function LW(t){const e=Date.now(),n=t.id||li(),r=t.started||e,s=t.lastActivity||e,i=t.segmentId||0,a=t.sampled,l=t.previousSessionId;return{id:n,started:r,lastActivity:s,segmentId:i,sampled:a,previousSessionId:l}}function zj(t){if($j())try{Tn.sessionStorage.setItem(Aj,JSON.stringify(t))}catch{}}function XIe(t,e){return DW(t)?"session":e?"buffer":!1}function Sz({sessionSampleRate:t,allowBuffering:e,stickySession:n=!1},{previousSessionId:r}={}){const s=XIe(t,e),i=LW({sampled:s,previousSessionId:r});return n&&zj(i),i}function QIe(){if(!$j())return null;try{const t=Tn.sessionStorage.getItem(Aj);if(!t)return null;const e=JSON.parse(t);return xt&&St.infoTick("Loading existing session"),LW(e)}catch{return null}}function oA(t,e,n=+new Date){return t===null||e===void 0||e<0?!0:e===0?!1:t+e<=n}function $W(t,{maxReplayDuration:e,sessionIdleExpire:n,targetTime:r=Date.now()}){return oA(t.started,e,r)||oA(t.lastActivity,n,r)}function zW(t,{sessionIdleExpire:e,maxReplayDuration:n}){return!(!$W(t,{sessionIdleExpire:e,maxReplayDuration:n})||t.sampled==="buffer"&&t.segmentId===0)}function ik({sessionIdleExpire:t,maxReplayDuration:e,previousSessionId:n},r){const s=r.stickySession&&QIe();return s?zW(s,{sessionIdleExpire:t,maxReplayDuration:e})?(xt&&St.infoTick("Session in sessionStorage is expired, creating new one..."),Sz(r,{previousSessionId:s.id})):s:(xt&&St.infoTick("Creating new session"),Sz(r,{previousSessionId:n}))}function JIe(t){return t.type===Ut.Custom}function Fj(t,e,n){return UW(t,e)?(FW(t,e,n),!0):!1}function ZIe(t,e,n){return UW(t,e)?FW(t,e,n):Promise.resolve(null)}async function FW(t,e,n){const{eventBuffer:r}=t;if(!r||r.waitForCheckout&&!n)return null;const s=t.recordingMode==="buffer";try{n&&s&&r.clear(),n&&(r.hasCheckout=!0,r.waitForCheckout=!1);const i=t.getOptions(),a=eDe(e,i.beforeAddRecordingEvent);return a?await r.addEvent(a):void 0}catch(i){const a=i&&i instanceof Lj,l=a?"addEventSizeExceeded":"addEvent";if(a&&s)return r.clear(),r.waitForCheckout=!0,null;t.handleException(i),await t.stop({reason:l});const u=Kt();u&&u.recordDroppedEvent("internal_sdk_error","replay")}}function UW(t,e){if(!t.eventBuffer||t.isPaused()||!t.isEnabled())return!1;const n=Dj(e.timestamp);return n+t.timeouts.sessionIdlePause<Date.now()?!1:n>t.getContext().initialTimestamp+t.getOptions().maxReplayDuration?(xt&&St.infoTick(`Skipping event with timestamp ${n} because it is after maxReplayDuration`),!1):!0}function eDe(t,e){try{if(typeof e=="function"&&JIe(t))return e(t)}catch(n){return xt&&St.exception(n,"An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."),null}return t}function Uj(t){return!t.type}function lA(t){return t.type==="transaction"}function tDe(t){return t.type==="replay_event"}function Ez(t){return t.type==="feedback"}function nDe(t){return(e,n)=>{if(!t.isEnabled()||!Uj(e)&&!lA(e))return;const r=n&&n.statusCode;if(!(!r||r<200||r>=300)){if(lA(e)){rDe(t,e);return}sDe(t,e)}}}function rDe(t,e){const n=t.getContext();e.contexts&&e.contexts.trace&&e.contexts.trace.trace_id&&n.traceIds.size<100&&n.traceIds.add(e.contexts.trace.trace_id)}function sDe(t,e){const n=t.getContext();if(e.event_id&&n.errorIds.size<100&&n.errorIds.add(e.event_id),t.recordingMode!=="buffer"||!e.tags||!e.tags.replayId)return;const{beforeErrorSampling:r}=t.getOptions();typeof r=="function"&&!r(e)||Bf(async()=>{try{await t.sendBufferedReplayOrFlush()}catch(s){t.handleException(s)}})}function iDe(t){return e=>{!t.isEnabled()||!Uj(e)||aDe(t,e)}}function aDe(t,e){const n=e.exception&&e.exception.values&&e.exception.values[0]&&e.exception.values[0].value;if(typeof n=="string"&&(n.match(/(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/)||n.match(/(does not match server-rendered HTML|Hydration failed because)/i))){const r=Oa({category:"replay.hydrate-error",data:{url:W7()}});zg(t,r)}}function oDe(t){const e=Kt();e&&e.on("beforeAddBreadcrumb",n=>lDe(t,n))}function lDe(t,e){if(!t.isEnabled()||!BW(e))return;const n=cDe(e);n&&zg(t,n)}function cDe(t){return!BW(t)||["fetch","xhr","sentry.event","sentry.transaction"].includes(t.category)||t.category.startsWith("ui.")?null:t.category==="console"?uDe(t):Oa(t)}function uDe(t){const e=t.data&&t.data.arguments;if(!Array.isArray(e)||e.length===0)return Oa(t);let n=!1;const r=e.map(s=>{if(!s)return s;if(typeof s=="string")return s.length>zy?(n=!0,`${s.slice(0,zy)}…`):s;if(typeof s=="object")try{const i=Zi(s,7);return JSON.stringify(i).length>zy?(n=!0,`${JSON.stringify(i,null,2).slice(0,zy)}…`):i}catch{}return s});return Oa({...t,data:{...t.data,arguments:r,...n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{}}})}function BW(t){return!!t.category}function dDe(t,e){return t.type||!t.exception||!t.exception.values||!t.exception.values.length?!1:!!(e.originalException&&e.originalException.__rrweb__)}function qW(){const t=Nn().getPropagationContext().dsc;t&&delete t.replay_id;const e=$r();if(e){const n=Du(e);delete n.replay_id}}function fDe(t,e){t.triggerUserActivity(),t.addUpdate(()=>e.timestamp?(t.throttledAddEvent({type:Ut.Custom,timestamp:e.timestamp*1e3,data:{tag:"breadcrumb",payload:{timestamp:e.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:e.event_id}}}}),!1):!0)}function hDe(t,e){return t.recordingMode!=="buffer"||e.message===Nj||!e.exception||e.type?!1:DW(t.getOptions().errorSampleRate)}function pDe(t){return Object.assign((e,n)=>!t.isEnabled()||t.isPaused()?e:tDe(e)?(delete e.breadcrumbs,e):!Uj(e)&&!lA(e)&&!Ez(e)?e:t.checkAndHandleExpiredSession()?Ez(e)?(t.flush(),e.contexts.feedback.replay_id=t.getSessionId(),fDe(t,e),e):dDe(e,n)&&!t.getOptions()._experiments.captureExceptions?(xt&&St.log("Ignoring error from rrweb internals",e),null):((hDe(t,e)||t.recordingMode==="session")&&(e.tags={...e.tags,replayId:t.getSessionId()}),e):(qW(),e),{id:"Replay"})}function l_(t,e){return e.map(({type:n,start:r,end:s,name:i,data:a})=>{const l=t.throttledAddEvent({type:Ut.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:i,startTimestamp:r,endTimestamp:s,data:a}}});return typeof l=="string"?Promise.resolve(null):l})}function mDe(t){const{from:e,to:n}=t,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:e}}}function gDe(t){return e=>{if(!t.isEnabled())return;const n=mDe(e);n!==null&&(t.getContext().urls.push(n.name),t.triggerUserActivity(),t.addUpdate(()=>(l_(t,[n]),!1)))}}function vDe(t,e){return xt&&t.getOptions()._experiments.traceInternals?!1:mje(e,Kt())}function VW(t,e){t.isEnabled()&&e!==null&&(vDe(t,e.name)||t.addUpdate(()=>(l_(t,[e]),!0)))}function c_(t){if(!t)return;const e=new TextEncoder;try{if(typeof t=="string")return e.encode(t).length;if(t instanceof URLSearchParams)return e.encode(t.toString()).length;if(t instanceof FormData){const n=YW(t);return e.encode(n).length}if(t instanceof Blob)return t.size;if(t instanceof ArrayBuffer)return t.byteLength}catch{}}function HW(t){if(!t)return;const e=parseInt(t,10);return isNaN(e)?void 0:e}function GW(t){try{if(typeof t=="string")return[t];if(t instanceof URLSearchParams)return[t.toString()];if(t instanceof FormData)return[YW(t)];if(!t)return[void 0]}catch(e){return xt&&St.exception(e,"Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return xt&&St.info("Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}function Ub(t,e){if(!t)return{headers:{},size:void 0,_meta:{warnings:[e]}};const n={...t._meta},r=n.warnings||[];return n.warnings=[...r,e],t._meta=n,t}function WW(t,e){if(!e)return null;const{startTimestamp:n,endTimestamp:r,url:s,method:i,statusCode:a,request:l,response:u}=e;return{type:t,start:n/1e3,end:r/1e3,name:s,data:Rr({method:i,statusCode:a,request:l,response:u})}}function ig(t){return{headers:{},size:t,_meta:{warnings:["URL_SKIPPED"]}}}function Yl(t,e,n){if(!e&&Object.keys(t).length===0)return;if(!e)return{headers:t};if(!n)return{headers:t,size:e};const r={headers:t,size:e},{body:s,warnings:i}=yDe(n);return r.body=s,i&&i.length>0&&(r._meta={warnings:i}),r}function cA(t,e){return Object.entries(t).reduce((n,[r,s])=>{const i=r.toLowerCase();return e.includes(i)&&t[r]&&(n[i]=s),n},{})}function YW(t){return new URLSearchParams(t).toString()}function yDe(t){if(!t||typeof t!="string")return{body:t};const e=t.length>sz,n=xDe(t);if(e){const r=t.slice(0,sz);return n?{body:r,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:`${r}…`,warnings:["TEXT_TRUNCATED"]}}if(n)try{return{body:JSON.parse(t)}}catch{}return{body:t}}function xDe(t){const e=t[0],n=t[t.length-1];return e==="["&&n==="]"||e==="{"&&n==="}"}function Bb(t,e){const n=bDe(t);return Wl(n,e)}function bDe(t,e=Tn.document.baseURI){if(t.startsWith("http://")||t.startsWith("https://")||t.startsWith(Tn.location.origin))return t;const n=new URL(t,e);if(n.origin!==new URL(e).origin)return t;const r=n.href;return!t.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}async function _De(t,e,n){try{const r=await SDe(t,e,n),s=WW("resource.fetch",r);VW(n.replay,s)}catch(r){xt&&St.exception(r,"Failed to capture fetch breadcrumb")}}function wDe(t,e){const{input:n,response:r}=e,s=n?KW(n):void 0,i=c_(s),a=r?HW(r.headers.get("content-length")):void 0;i!==void 0&&(t.data.request_body_size=i),a!==void 0&&(t.data.response_body_size=a)}async function SDe(t,e,n){const r=Date.now(),{startTimestamp:s=r,endTimestamp:i=r}=e,{url:a,method:l,status_code:u=0,request_body_size:d,response_body_size:p}=t.data,h=Bb(a,n.networkDetailAllowUrls)&&!Bb(a,n.networkDetailDenyUrls),g=h?EDe(n,e.input,d):ig(d),v=await kDe(h,n,e.response,p);return{startTimestamp:s,endTimestamp:i,url:a,method:l,statusCode:u,request:g,response:v}}function EDe({networkCaptureBodies:t,networkRequestHeaders:e},n,r){const s=n?ADe(n,e):{};if(!t)return Yl(s,r,void 0);const i=KW(n),[a,l]=GW(i),u=Yl(s,r,a);return l?Ub(u,l):u}async function kDe(t,{networkCaptureBodies:e,networkResponseHeaders:n},r,s){if(!t&&s!==void 0)return ig(s);const i=r?XW(r.headers,n):{};if(!r||!e&&s!==void 0)return Yl(i,s,void 0);const[a,l]=await CDe(r),u=TDe(a,{networkCaptureBodies:e,responseBodySize:s,captureDetails:t,headers:i});return l?Ub(u,l):u}function TDe(t,{networkCaptureBodies:e,responseBodySize:n,captureDetails:r,headers:s}){try{const i=t&&t.length&&n===void 0?c_(t):n;return r?e?Yl(s,i,t):Yl(s,i,void 0):ig(i)}catch(i){return xt&&St.exception(i,"Failed to serialize response body"),Yl(s,n,void 0)}}async function CDe(t){const e=NDe(t);if(!e)return[void 0,"BODY_PARSE_ERROR"];try{return[await RDe(e)]}catch(n){return n instanceof Error&&n.message.indexOf("Timeout")>-1?(xt&&St.warn("Parsing text body from response timed out"),[void 0,"BODY_PARSE_TIMEOUT"]):(xt&&St.exception(n,"Failed to get text body from response"),[void 0,"BODY_PARSE_ERROR"])}}function KW(t=[]){if(!(t.length!==2||typeof t[1]!="object"))return t[1].body}function XW(t,e){const n={};return e.forEach(r=>{t.get(r)&&(n[r]=t.get(r))}),n}function ADe(t,e){return t.length===1&&typeof t[0]!="string"?kz(t[0],e):t.length===2?kz(t[1],e):{}}function kz(t,e){if(!t)return{};const n=t.headers;return n?n instanceof Headers?XW(n,e):Array.isArray(n)?{}:cA(n,e):{}}function NDe(t){try{return t.clone()}catch(e){xt&&St.exception(e,"Failed to clone response body")}}function RDe(t){return new Promise((e,n)=>{const r=Bf(()=>n(new Error("Timeout while trying to read response body")),500);jDe(t).then(s=>e(s),s=>n(s)).finally(()=>clearTimeout(r))})}async function jDe(t){return await t.text()}async function MDe(t,e,n){try{const r=PDe(t,e,n),s=WW("resource.xhr",r);VW(n.replay,s)}catch(r){xt&&St.exception(r,"Failed to capture xhr breadcrumb")}}function ODe(t,e){const{xhr:n,input:r}=e;if(!n)return;const s=c_(r),i=n.getResponseHeader("content-length")?HW(n.getResponseHeader("content-length")):$De(n.response,n.responseType);s!==void 0&&(t.data.request_body_size=s),i!==void 0&&(t.data.response_body_size=i)}function PDe(t,e,n){const r=Date.now(),{startTimestamp:s=r,endTimestamp:i=r,input:a,xhr:l}=e,{url:u,method:d,status_code:p=0,request_body_size:h,response_body_size:g}=t.data;if(!u)return null;if(!l||!Bb(u,n.networkDetailAllowUrls)||Bb(u,n.networkDetailDenyUrls)){const A=ig(h),N=ig(g);return{startTimestamp:s,endTimestamp:i,url:u,method:d,statusCode:p,request:A,response:N}}const v=l[eu],x=v?cA(v.request_headers,n.networkRequestHeaders):{},b=cA(IDe(l),n.networkResponseHeaders),[E,S]=n.networkCaptureBodies?GW(a):[void 0],[k,T]=n.networkCaptureBodies?DDe(l):[void 0],R=Yl(x,h,E),j=Yl(b,g,k);return{startTimestamp:s,endTimestamp:i,url:u,method:d,statusCode:p,request:S?Ub(R,S):R,response:T?Ub(j,T):j}}function IDe(t){const e=t.getAllResponseHeaders();return e?e.split(`\r
1878
1878
  `).reduce((n,r)=>{const[s,i]=r.split(": ");return i&&(n[s.toLowerCase()]=i),n},{}):{}}function DDe(t){const e=[];try{return[t.responseText]}catch(n){e.push(n)}try{return LDe(t.response,t.responseType)}catch(n){e.push(n)}return xt&&St.warn("Failed to get xhr response body",...e),[void 0]}function LDe(t,e){try{if(typeof t=="string")return[t];if(t instanceof Document)return[t.body.outerHTML];if(e==="json"&&t&&typeof t=="object")return[JSON.stringify(t)];if(!t)return[void 0]}catch(n){return xt&&St.exception(n,"Failed to serialize body",t),[void 0,"BODY_PARSE_ERROR"]}return xt&&St.info("Skipping network body because of body type",t),[void 0,"UNPARSEABLE_BODY_TYPE"]}function $De(t,e){try{const n=e==="json"&&t&&typeof t=="object"?JSON.stringify(t):t;return c_(n)}catch{return}}function zDe(t){const e=Kt();try{const{networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:s,networkRequestHeaders:i,networkResponseHeaders:a}=t.getOptions(),l={replay:t,networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:s,networkRequestHeaders:i,networkResponseHeaders:a};e&&e.on("beforeAddBreadcrumb",(u,d)=>FDe(l,u,d))}catch{}}function FDe(t,e,n){if(e.data)try{UDe(e)&&qDe(n)&&(ODe(e,n),MDe(e,n,t)),BDe(e)&&VDe(n)&&(wDe(e,n),_De(e,n,t))}catch(r){xt&&St.exception(r,"Error when enriching network breadcrumb")}}function UDe(t){return t.category==="xhr"}function BDe(t){return t.category==="fetch"}function qDe(t){return t&&t.xhr}function VDe(t){return t&&t.response}function HDe(t){const e=Kt();sW(bIe(t)),r_(gDe(t)),oDe(t),zDe(t);const n=pDe(t);YRe(n),e&&(e.on("beforeSendEvent",iDe(t)),e.on("afterSendEvent",nDe(t)),e.on("createDsc",r=>{const s=t.getSessionId();s&&t.isEnabled()&&t.recordingMode==="session"&&t.checkAndHandleExpiredSession()&&(r.replay_id=s)}),e.on("spanStart",r=>{t.lastActiveSpan=r}),e.on("spanEnd",r=>{t.lastActiveSpan=r}),e.on("beforeSendFeedback",(r,s)=>{const i=t.getSessionId();s&&s.includeReplay&&t.isEnabled()&&i&&r.contexts&&r.contexts.feedback&&(r.contexts.feedback.replay_id=i)}))}async function GDe(t){try{return Promise.all(l_(t,[WDe(Tn.performance.memory)]))}catch{return[]}}function WDe(t){const{jsHeapSizeLimit:e,totalJSHeapSize:n,usedJSHeapSize:r}=t,s=Date.now()/1e3;return{type:"memory",name:"memory",start:s,end:s,data:{memory:{jsHeapSizeLimit:e,totalJSHeapSize:n,usedJSHeapSize:r}}}}function YDe(t,e,n){let r,s,i;const a=n&&n.maxWait?Math.max(n.maxWait,e):0;function l(){return u(),r=t(),r}function u(){s!==void 0&&clearTimeout(s),i!==void 0&&clearTimeout(i),s=i=void 0}function d(){return s!==void 0||i!==void 0?l():r}function p(){return s&&clearTimeout(s),s=Bf(l,e),a&&i===void 0&&(i=Bf(l,a)),r}return p.cancel=u,p.flush=d,p}const Vc=Xt.navigator;function KDe(){return/iPhone|iPad|iPod/i.test(Vc&&Vc.userAgent||"")||/Macintosh/i.test(Vc&&Vc.userAgent||"")&&Vc&&Vc.maxTouchPoints&&Vc.maxTouchPoints>1?{sampling:{mousemove:!1}}:{}}function XDe(t){let e=!1;return(n,r)=>{if(!t.checkAndHandleExpiredSession()){xt&&St.warn("Received replay event after session expired.");return}const s=r||!e;e=!0,t.clickDetector&&mIe(t.clickDetector,n),t.addUpdate(()=>{if(t.recordingMode==="buffer"&&s&&t.setInitialState(),!Fj(t,n,s))return!0;if(!s)return!1;const i=t.session;if(JDe(t,s),t.recordingMode==="buffer"&&i&&t.eventBuffer){const a=t.eventBuffer.getEarliestTimestamp();a&&(xt&&St.info(`Updating session start time to earliest event in buffer to ${new Date(a)}`),i.started=a,t.getOptions().stickySession&&zj(i))}return i&&i.previousSessionId||t.recordingMode==="session"&&t.flush(),!0})}}function QDe(t){const e=t.getOptions();return{type:Ut.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:t.isRecordingCanvas(),sessionSampleRate:e.sessionSampleRate,errorSampleRate:e.errorSampleRate,useCompressionOption:e.useCompression,blockAllMedia:e.blockAllMedia,maskAllText:e.maskAllText,maskAllInputs:e.maskAllInputs,useCompression:t.eventBuffer?t.eventBuffer.type==="worker":!1,networkDetailHasUrls:e.networkDetailAllowUrls.length>0,networkCaptureBodies:e.networkCaptureBodies,networkRequestHasHeaders:e.networkRequestHeaders.length>0,networkResponseHasHeaders:e.networkResponseHeaders.length>0}}}}function JDe(t,e){!e||!t.session||t.session.segmentId!==0||Fj(t,QDe(t),!1)}function ZDe(t,e,n,r){return Lu(vG(t,bj(t),r,n),[[{type:"replay_event"},t],[{type:"replay_recording",length:typeof e=="string"?new TextEncoder().encode(e).length:e.length},e]])}function eLe({recordingData:t,headers:e}){let n;const r=`${JSON.stringify(e)}
1879
- `;if(typeof t=="string")n=`${r}${t}`;else{const i=new TextEncoder().encode(r);n=new Uint8Array(i.length+t.length),n.set(i),n.set(t,i.length)}return n}async function tLe({client:t,scope:e,replayId:n,event:r}){const s=typeof t._integrations=="object"&&t._integrations!==null&&!Array.isArray(t._integrations)?Object.keys(t._integrations):void 0,i={event_id:n,integrations:s};t.emit("preprocessEvent",r,i);const a=await wG(t.getOptions(),r,i,e,t,Ui());if(!a)return null;a.platform=a.platform||"javascript";const l=t.getSdkMetadata(),{name:u,version:d}=l&&l.sdk||{};return a.sdk={...a.sdk,name:u||"sentry.javascript.unknown",version:d||"0.0.0"},a}async function nLe({recordingData:t,replayId:e,segmentId:n,eventContext:r,timestamp:s,session:i}){const a=eLe({recordingData:t,headers:{segment_id:n}}),{urls:l,errorIds:u,traceIds:d,initialTimestamp:p}=r,h=Kt(),g=Nn(),v=h&&h.getTransport(),x=h&&h.getDsn();if(!h||!v||!x||!i.sampled)return Wo({});const b={type:P2e,replay_start_timestamp:p/1e3,timestamp:s/1e3,error_ids:u,trace_ids:d,urls:l,replay_id:e,segment_id:n,replay_type:i.sampled},E=await tLe({scope:g,client:h,replayId:e,event:b});if(!E)return h.recordDroppedEvent("event_processor","replay",b),xt&&St.info("An event processor returned `null`, will not send event."),Wo({});delete E.sdkProcessingMetadata;const S=ZDe(E,a,x,h.getOptions().tunnel);let k;try{k=await v.send(S)}catch(R){const j=new Error(Nj);try{j.cause=R}catch{}throw j}if(typeof k.statusCode=="number"&&(k.statusCode<200||k.statusCode>=300))throw new QW(k.statusCode);const T=MG({},k);if(jG(T,"replay"))throw new Bj(T);return k}class QW extends Error{constructor(e){super(`Transport returned status code ${e}`)}}class Bj extends Error{constructor(e){super("Rate limit hit"),this.rateLimits=e}}async function JW(t,e={count:0,interval:F2e}){const{recordingData:n,onError:r}=t;if(n.length)try{return await nLe(t),!0}catch(s){if(s instanceof QW||s instanceof Bj)throw s;if(kG("Replays",{_retryCount:e.count}),r&&r(s),e.count>=U2e){const i=new Error(`${Nj} - max retries exceeded`);try{i.cause=s}catch{}throw i}return e.interval*=++e.count,new Promise((i,a)=>{Bf(async()=>{try{await JW(t,e),i(!0)}catch(l){a(l)}},e.interval)})}}const ZW="__THROTTLED",rLe="__SKIPPED";function sLe(t,e,n){const r=new Map,s=l=>{const u=l-n;r.forEach((d,p)=>{p<u&&r.delete(p)})},i=()=>[...r.values()].reduce((l,u)=>l+u,0);let a=!1;return(...l)=>{const u=Math.floor(Date.now()/1e3);if(s(u),i()>=e){const p=a;return a=!0,p?rLe:ZW}a=!1;const d=r.get(u)||0;return r.set(u,d+1),t(...l)}}class $l{constructor({options:e,recordingOptions:n}){$l.prototype.__init.call(this),$l.prototype.__init2.call(this),$l.prototype.__init3.call(this),$l.prototype.__init4.call(this),$l.prototype.__init5.call(this),$l.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:I2e,sessionIdleExpire:D2e},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=n,this._options=e,this._debouncedFlush=YDe(()=>this._flush(),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=sLe((a,l)=>ZIe(this,a,l),300,5);const{slowClickTimeout:r,slowClickIgnoreSelectors:s}=this.getOptions(),i=r?{threshold:Math.min(B2e,r),timeout:r,scrollTimeout:q2e,ignoreSelector:s?s.join(","):""}:void 0;if(i&&(this.clickDetector=new dIe(this,i)),xt){const a=e._experiments;St.setConfig({captureExceptions:!!a.captureExceptions,traceInternals:!!a.traceInternals})}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return!!this._canvas}getOptions(){return this._options}handleException(e){xt&&St.exception(e),this._options.onError&&this._options.onError(e)}initializeSampling(e){const{errorSampleRate:n,sessionSampleRate:r}=this._options,s=n<=0&&r<=0;if(this._requiresManualStart=s,!s){if(this._initializeSessionForSampling(e),!this.session){xt&&St.exception(new Error("Unable to initialize and create session"));return}this.session.sampled!==!1&&(this.recordingMode=this.session.sampled==="buffer"&&this.session.segmentId===0?"buffer":"session",xt&&St.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording())}}start(){if(this._isEnabled&&this.recordingMode==="session"){xt&&St.info("Recording is already in progress");return}if(this._isEnabled&&this.recordingMode==="buffer"){xt&&St.info("Buffering is in progress, call `flush()` to save the replay");return}xt&&St.infoTick("Starting replay in session mode"),this._updateUserActivity();const e=ik({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=e,this._initializeRecording()}startBuffering(){if(this._isEnabled){xt&&St.info("Buffering is in progress, call `flush()` to save the replay");return}xt&&St.infoTick("Starting replay in buffer mode");const e=ik({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=e,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{const e=this._canvas;this._stopRecording=Io({...this._recordingOptions,...this.recordingMode==="buffer"?{checkoutEveryNms:z2e}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:XDe(this),...KDe(),onMutation:this._onMutationHandler,...e?{recordCanvas:e.recordCanvas,getCanvasManager:e.getCanvasManager,sampling:e.sampling,dataURLOptions:e.dataURLOptions}:{}})}catch(e){this.handleException(e)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(e){return this.handleException(e),!1}}async stop({forceFlush:e=!1,reason:n}={}){if(this._isEnabled){this._isEnabled=!1;try{xt&&St.info(`Stopping Replay${n?` triggered by ${n}`:""}`),qW(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),e&&await this._flush({force:!0}),this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,YIe(this)}catch(r){this.handleException(r)}}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),xt&&St.info("Pausing replay"))}resume(){!this._isPaused||!this._checkSession()||(this._isPaused=!1,this.startRecording(),xt&&St.info("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:e=!0}={}){if(this.recordingMode==="session")return this.flushImmediate();const n=Date.now();xt&&St.info("Converting buffer to session"),await this.flushImmediate();const r=this.stopRecording();!e||!r||this.recordingMode!=="session"&&(this.recordingMode="session",this.session&&(this._updateUserActivity(n),this._updateSessionActivity(n),this._maybeSaveSession()),this.startRecording())}addUpdate(e){const n=e();this.recordingMode!=="buffer"&&n!==!0&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),!this._stopRecording){if(!this._checkSession())return;this.resume();return}this.checkAndHandleExpiredSession(),this._updateSessionActivity()}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return this.recordingMode==="buffer"?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(){return this.session&&this.session.id}checkAndHandleExpiredSession(){if(this._lastActivity&&oA(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&this.session.sampled==="session"){this.pause();return}return!!this._checkSession()}setInitialState(){const e=`${Tn.location.pathname}${Tn.location.hash}${Tn.location.search}`,n=`${Tn.location.origin}${e}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=n,this._context.initialTimestamp=Date.now(),this._context.urls.push(n)}throttledAddEvent(e,n){const r=this._throttledAddEvent(e,n);if(r===ZW){const s=Oa({category:"replay.throttled"});this.addUpdate(()=>!Fj(this,{type:sIe,timestamp:s.timestamp||0,data:{tag:"breadcrumb",payload:s,metric:!0}}))}return r}getCurrentRoute(){const e=this.lastActiveSpan||$r(),n=e&&Xr(e),s=(n&&nn(n).data||{})[Ma];if(!(!n||!s||!["route","custom"].includes(s)))return nn(n).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=HIe({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()}_initializeSessionForSampling(e){const n=this._options.errorSampleRate>0,r=ik({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:e},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:n});this.session=r}_checkSession(){if(!this.session)return!1;const e=this.session;return zW(e,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})?(this._refreshSession(e),!1):!0}async _refreshSession(e){this._isEnabled&&(await this.stop({reason:"refresh session"}),this.initializeSampling(e.id))}_addListeners(){try{Tn.document.addEventListener("visibilitychange",this._handleVisibilityChange),Tn.addEventListener("blur",this._handleWindowBlur),Tn.addEventListener("focus",this._handleWindowFocus),Tn.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(HDe(this),this._hasInitializedCoreListeners=!0)}catch(e){this.handleException(e)}this._performanceCleanupCallback=$Ie(this)}_removeListeners(){try{Tn.document.removeEventListener("visibilitychange",this._handleVisibilityChange),Tn.removeEventListener("blur",this._handleWindowBlur),Tn.removeEventListener("focus",this._handleWindowFocus),Tn.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(e){this.handleException(e)}}__init(){this._handleVisibilityChange=()=>{Tn.document.visibilityState==="visible"?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()}}__init2(){this._handleWindowBlur=()=>{const e=Oa({category:"ui.blur"});this._doChangeToBackgroundTasks(e)}}__init3(){this._handleWindowFocus=()=>{const e=Oa({category:"ui.focus"});this._doChangeToForegroundTasks(e)}}__init4(){this._handleKeyboardEvent=e=>{EIe(this,e)}}_doChangeToBackgroundTasks(e){!this.session||$W(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(e&&this._createCustomBreadcrumb(e),this.conditionalFlush())}_doChangeToForegroundTasks(e){if(!this.session)return;if(!this.checkAndHandleExpiredSession()){xt&&St.info("Document has become active, but session has expired");return}e&&this._createCustomBreadcrumb(e)}_updateUserActivity(e=Date.now()){this._lastActivity=e}_updateSessionActivity(e=Date.now()){this.session&&(this.session.lastActivity=e,this._maybeSaveSession())}_createCustomBreadcrumb(e){this.addUpdate(()=>{this.throttledAddEvent({type:Ut.Custom,timestamp:e.timestamp||0,data:{tag:"breadcrumb",payload:e}})})}_addPerformanceEntries(){let e=AIe(this.performanceEntries).concat(this.replayPerformanceEntries);if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){const n=this._context.initialTimestamp/1e3;e=e.filter(r=>r.start>=n)}return Promise.all(l_(this,e))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){const{session:e,eventBuffer:n}=this;if(!e||!n||this._requiresManualStart||e.segmentId)return;const r=n.getEarliestTimestamp();r&&r<this._context.initialTimestamp&&(this._context.initialTimestamp=r)}_popEventContext(){const e={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),e}async _runFlush(){const e=this.getSessionId();if(!this.session||!this.eventBuffer||!e){xt&&St.error("No session or eventBuffer found to flush.");return}if(await this._addPerformanceEntries(),!(!this.eventBuffer||!this.eventBuffer.hasEvents)&&(await GDe(this),!!this.eventBuffer&&e===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();const n=Date.now();if(n-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new Error("Session is too long, not sending replay");const r=this._popEventContext(),s=this.session.segmentId++;this._maybeSaveSession();const i=await this.eventBuffer.finish();await JW({replayId:e,recordingData:i,segmentId:s,eventContext:r,session:this.session,timestamp:n,onError:a=>this.handleException(a)})}catch(n){this.handleException(n),this.stop({reason:"sendReplay"});const r=Kt();if(r){const s=n instanceof Bj?"ratelimit_backoff":"send_error";r.recordDroppedEvent(s,"replay")}}}__init5(){this._flush=async({force:e=!1}={})=>{if(!this._isEnabled&&!e)return;if(!this.checkAndHandleExpiredSession()){xt&&St.error("Attempting to finish replay event after session expired.");return}if(!this.session)return;const n=this.session.started,s=Date.now()-n;this._debouncedFlush.cancel();const i=s<this._options.minReplayDuration,a=s>this._options.maxReplayDuration+5e3;if(i||a){xt&&St.info(`Session duration (${Math.floor(s/1e3)}s) is too ${i?"short":"long"}, not sending replay.`),i&&this._debouncedFlush();return}const l=this.eventBuffer;l&&this.session.segmentId===0&&!l.hasCheckout&&xt&&St.info("Flushing initial segment without checkout.");const u=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(d){this.handleException(d)}finally{this._flushLock=void 0,u&&this._debouncedFlush()}}}_maybeSaveSession(){this.session&&this._options.stickySession&&zj(this.session)}__init6(){this._onMutationHandler=e=>{const n=e.length,r=this._options.mutationLimit,s=this._options.mutationBreadcrumbLimit,i=r&&n>r;if(n>s||i){const a=Oa({category:"replay.mutations",data:{count:n,limit:i}});this._createCustomBreadcrumb(a)}return i?(this.stop({reason:"mutationLimit",forceFlush:this.recordingMode==="session"}),!1):!0}}}function Rp(t,e){return[...t,...e].join(",")}function iLe({mask:t,unmask:e,block:n,unblock:r,ignore:s}){const i=["base","iframe[srcdoc]:not([src])"],a=Rp(t,[".sentry-mask","[data-sentry-mask]"]),l=Rp(e,[]);return{maskTextSelector:a,unmaskTextSelector:l,blockSelector:Rp(n,[".sentry-block","[data-sentry-block]",...i]),unblockSelector:Rp(r,[]),ignoreSelector:Rp(s,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}function aLe({el:t,key:e,maskAttributes:n,maskAllText:r,privacyOptions:s,value:i}){return!r||s.unmaskTextSelector&&t.matches(s.unmaskTextSelector)?i:n.includes(e)||e==="value"&&t.tagName==="INPUT"&&["submit","button"].includes(t.getAttribute("type")||"")?i.replace(/[\S]/g,"*"):i}const Tz='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',oLe=["content-length","content-type","accept"];let Cz=!1;const lLe=t=>new u_(t);class u_{static __initStatic(){this.id="Replay"}constructor({flushMinDelay:e=L2e,flushMaxDelay:n=$2e,minReplayDuration:r=V2e,maxReplayDuration:s=iz,stickySession:i=!0,useCompression:a=!0,workerUrl:l,_experiments:u={},maskAllText:d=!0,maskAllInputs:p=!0,blockAllMedia:h=!0,mutationBreadcrumbLimit:g=750,mutationLimit:v=1e4,slowClickTimeout:x=7e3,slowClickIgnoreSelectors:b=[],networkDetailAllowUrls:E=[],networkDetailDenyUrls:S=[],networkCaptureBodies:k=!0,networkRequestHeaders:T=[],networkResponseHeaders:R=[],mask:j=[],maskAttributes:A=["title","placeholder"],unmask:N=[],block:M=[],unblock:I=[],ignore:O=[],maskFn:L,beforeAddRecordingEvent:z,beforeErrorSampling:H,onError:V}={}){this.name=u_.id;const X=iLe({mask:j,unmask:N,block:M,unblock:I,ignore:O});if(this._recordingOptions={maskAllInputs:p,maskAllText:d,maskInputOptions:{password:!0},maskTextFn:L,maskInputFn:L,maskAttributeFn:(F,W,G)=>aLe({maskAttributes:A,maskAllText:d,privacyOptions:X,key:F,value:W,el:G}),...X,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:F=>{try{F.__rrweb__=!0}catch{}}},this._initialOptions={flushMinDelay:e,flushMaxDelay:n,minReplayDuration:Math.min(r,H2e),maxReplayDuration:Math.min(s,iz),stickySession:i,useCompression:a,workerUrl:l,blockAllMedia:h,maskAllInputs:p,maskAllText:d,mutationBreadcrumbLimit:g,mutationLimit:v,slowClickTimeout:x,slowClickIgnoreSelectors:b,networkDetailAllowUrls:E,networkDetailDenyUrls:S,networkCaptureBodies:k,networkRequestHeaders:Az(T),networkResponseHeaders:Az(R),beforeAddRecordingEvent:z,beforeErrorSampling:H,onError:V,_experiments:u},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${Tz}`:Tz),this._isInitialized&&K$())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return Cz}set _isInitialized(e){Cz=e}afterAllSetup(e){!K$()||this._replay||(this._setup(e),this._initialize(e))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:this._replay.recordingMode==="session"}):Promise.resolve()}flush(e){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(e):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.getSessionId()}getRecordingMode(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.recordingMode}_initialize(e){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(e),this._replay.initializeSampling())}_setup(e){const n=cLe(this._initialOptions,e);this._replay=new $l({options:n,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(e){try{const n=e.getIntegrationByName("ReplayCanvas");if(!n)return;this._replay._canvas=n.getOptions()}catch{}}}u_.__initStatic();function cLe(t,e){const n=e.getOptions(),r={sessionSampleRate:0,errorSampleRate:0,...Rr(t)},s=Rb(n.replaysSessionSampleRate),i=Rb(n.replaysOnErrorSampleRate);return s==null&&i==null&&gc(()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}),s!=null&&(r.sessionSampleRate=s),i!=null&&(r.errorSampleRate=i),r}function Az(t){return[...oLe,...t.map(e=>e.toLowerCase())]}const Nz=new WeakMap,ak=new Map,gx={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function uLe(t,e){const{traceFetch:n,traceXHR:r,trackFetchStreamPerformance:s,shouldCreateSpanForRequest:i,enableHTTPTimings:a,tracePropagationTargets:l}={traceFetch:gx.traceFetch,traceXHR:gx.traceXHR,trackFetchStreamPerformance:gx.trackFetchStreamPerformance,...e},u=typeof i=="function"?i:h=>!0,d=h=>hLe(h,l),p={};n&&(t.addEventProcessor(h=>(h.type==="transaction"&&h.spans&&h.spans.forEach(g=>{if(g.op==="http.client"){const v=ak.get(g.span_id);v&&(g.timestamp=v/1e3,ak.delete(g.span_id))}}),h)),s&&eMe(h=>{if(h.response){const g=Nz.get(h.response);g&&h.endTimestamp&&ak.set(g,h.endTimestamp)}}),FG(h=>{const g=Wje(h,u,d,p);if(h.response&&h.fetchData.__span&&Nz.set(h.response,h.fetchData.__span),g){const v=eY(h.fetchData.url),x=v?pu(v).host:void 0;g.setAttributes({"http.url":v,"server.address":x})}a&&g&&Rz(g)})),r&&aW(h=>{const g=pLe(h,u,d,p);a&&g&&Rz(g)})}function dLe(t){return t.entryType==="resource"&&"initiatorType"in t&&typeof t.nextHopProtocol=="string"&&(t.initiatorType==="fetch"||t.initiatorType==="xmlhttprequest")}function Rz(t){const{url:e}=nn(t).data||{};if(!e||typeof e!="string")return;const n=Uf("resource",({entries:r})=>{r.forEach(s=>{dLe(s)&&s.name.endsWith(e)&&(fLe(s).forEach(a=>t.setAttribute(...a)),setTimeout(n))})})}function Ea(t=0){return((bs||performance.timeOrigin)+t)/1e3}function fLe(t){const{name:e,version:n}=rW(t.nextHopProtocol),r=[];return r.push(["network.protocol.version",n],["network.protocol.name",e]),bs?[...r,["http.request.redirect_start",Ea(t.redirectStart)],["http.request.fetch_start",Ea(t.fetchStart)],["http.request.domain_lookup_start",Ea(t.domainLookupStart)],["http.request.domain_lookup_end",Ea(t.domainLookupEnd)],["http.request.connect_start",Ea(t.connectStart)],["http.request.secure_connection_start",Ea(t.secureConnectionStart)],["http.request.connection_end",Ea(t.connectEnd)],["http.request.request_start",Ea(t.requestStart)],["http.request.response_start",Ea(t.responseStart)],["http.request.response_end",Ea(t.responseEnd)]]:r}function hLe(t,e){const n=Nt.location&&Nt.location.href;if(n){let r,s;try{r=new URL(t,n),s=new URL(n).origin}catch{return!1}const i=r.origin===s;return e?Wl(r.toString(),e)||i&&Wl(r.pathname,e):i}else{const r=!!t.match(/^\/(?!\/)/);return e?Wl(t,e):r}}function pLe(t,e,n,r){const s=t.xhr,i=s&&s[eu];if(!s||s.__sentry_own_request__||!i)return;const a=sc()&&e(i.url);if(t.endTimestamp&&a){const h=s.__sentry_xhr_span_id__;if(!h)return;const g=r[h];g&&i.status_code!==void 0&&(tG(g,i.status_code),g.end(),delete r[h]);return}const l=eY(i.url),u=l?pu(l).host:void 0,d=!!$r(),p=a&&d?Og({name:`${i.method} ${i.url}`,attributes:{type:"xhr","http.method":i.method,"http.url":l,url:i.url,"server.address":u,[Dr]:"auto.http.browser",[ju]:"http.client"}}):new fh;return s.__sentry_xhr_span_id__=p.spanContext().spanId,r[s.__sentry_xhr_span_id__]=p,n(i.url)&&mLe(s,sc()&&d?p:void 0),p}function mLe(t,e){const{"sentry-trace":n,baggage:r}=PG({span:e});n&&gLe(t,n,r)}function gLe(t,e,n){try{t.setRequestHeader("sentry-trace",e),n&&t.setRequestHeader("baggage",n)}catch{}}function eY(t){try{return new URL(t,Nt.location.origin).href}catch{return}}function vLe(){Nt&&Nt.document?Nt.document.addEventListener("visibilitychange",()=>{const t=$r();if(!t)return;const e=Xr(t);if(Nt.document.hidden&&e){const n="cancelled",{op:r,status:s}=nn(e);Ka&&ze.log(`[Tracing] Transaction: ${n} -> since tab moved to the background, op: ${r}`),s||e.setStatus({code:Pr,message:n}),e.setAttribute("sentry.cancellation_reason","document.hidden"),e.end()}}):Ka&&ze.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const yLe="BrowserTracing",xLe={...dx,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,_experiments:{},...gx},bLe=(t={})=>{QNe();const{enableInp:e,enableLongTask:n,enableLongAnimationFrame:r,_experiments:{enableInteractions:s,enableStandaloneClsSpans:i},beforeStartSpan:a,idleTimeout:l,finalTimeout:u,childSpanTimeout:d,markBackgroundSpan:p,traceFetch:h,traceXHR:g,trackFetchStreamPerformance:v,shouldCreateSpanForRequest:x,enableHTTPTimings:b,instrumentPageLoad:E,instrumentNavigation:S}={...xLe,...t},k=cOe({recordClsStandaloneSpans:i||!1});e&&POe(),r&&Xt.PerformanceObserver&&PerformanceObserver.supportedEntryTypes&&PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")?dOe():n&&uOe(),s&&fOe();const T={name:void 0,source:void 0};function R(j,A){const N=A.op==="pageload",M=a?a(A):A,I=M.attributes||{};A.name!==M.name&&(I[Ma]="custom",M.attributes=I),T.name=M.name,T.source=I[Ma];const O=_G(M,{idleTimeout:l,finalTimeout:u,childSpanTimeout:d,disableAutoFinish:N,beforeSpanEnd:z=>{k(),vOe(z,{recordClsOnPageloadSpan:!i})}});function L(){["interactive","complete"].includes(Nt.document.readyState)&&j.emit("idleSpanEnableAutoFinish",O)}return N&&Nt.document&&(Nt.document.addEventListener("readystatechange",()=>{L()}),L()),O}return{name:yLe,afterAllSetup(j){let A,N=Nt.location&&Nt.location.href;function M(){A&&!nn(A).timestamp&&(Ka&&ze.log(`[Tracing] Finishing current active span with op: ${nn(A).op}`),A.end())}j.on("startNavigationSpan",I=>{Kt()===j&&(M(),A=R(j,{op:"navigation",...I}))}),j.on("startPageLoadSpan",(I,O={})=>{if(Kt()!==j)return;M();const L=O.sentryTrace||jz("sentry-trace"),z=O.baggage||jz("baggage"),H=VNe(L,z);Nn().setPropagationContext(H),A=R(j,{op:"pageload",...I})}),j.on("spanEnd",I=>{const O=nn(I).op;if(I!==Xr(I)||O!=="navigation"&&O!=="pageload")return;const L=Nn(),z=L.getPropagationContext();L.setPropagationContext({...z,sampled:z.sampled!==void 0?z.sampled:Iu(I),dsc:z.dsc||Du(I)})}),Nt.location&&(E&&_Le(j,{name:Nt.location.pathname,startTime:bs?bs/1e3:void 0,attributes:{[Ma]:"url",[Dr]:"auto.pageload.browser"}}),S&&r_(({to:I,from:O})=>{if(O===void 0&&N&&N.indexOf(I)!==-1){N=void 0;return}O!==I&&(N=void 0,wLe(j,{name:Nt.location.pathname,attributes:{[Ma]:"url",[Dr]:"auto.navigation.browser"}}))})),p&&vLe(),s&&SLe(l,u,d,T),e&&DOe(),uLe(j,{traceFetch:h,traceXHR:g,trackFetchStreamPerformance:v,tracePropagationTargets:j.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:x,enableHTTPTimings:b})}}};function _Le(t,e,n){t.emit("startPageLoadSpan",e,n),Nn().setTransactionName(e.name);const r=$r();return(r&&nn(r).op)==="pageload"?r:void 0}function wLe(t,e){Ui().setPropagationContext({traceId:nc()}),Nn().setPropagationContext({traceId:nc()}),t.emit("startNavigationSpan",e),Nn().setTransactionName(e.name);const n=$r();return(n&&nn(n).op)==="navigation"?n:void 0}function jz(t){const e=gNe(`meta[name=${t}]`);return e?e.getAttribute("content"):void 0}function SLe(t,e,n,r){let s;const i=()=>{const a="ui.action.click",l=$r(),u=l&&Xr(l);if(u){const d=nn(u).op;if(["navigation","pageload"].includes(d)){Ka&&ze.warn(`[Tracing] Did not create ${a} span because a pageload or navigation span is in progress.`);return}}if(s&&(s.setAttribute(LC,"interactionInterrupted"),s.end(),s=void 0),!r.name){Ka&&ze.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`);return}s=_G({name:r.name,op:a,attributes:{[Ma]:r.source||"url"}},{idleTimeout:t,finalTimeout:e,childSpanTimeout:n})};Nt.document&&addEventListener("click",i,{once:!1,capture:!0})}function ELe(t){const e={...t};return OG(e,"react"),kG("react",{version:w.version}),O2e(e)}function kLe(){const{user:t}=Fi(),{isAuthenticated:e,isLoading:n}=pa(),r=b7("users:ensureUser"),s=w.useRef(null);w.useEffect(()=>{e||(s.current=null,I$(null))},[e]),w.useEffect(()=>{if(!n){if(!e&&t)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");e&&t&&s.current!==t.id&&r().then(i=>{s.current=t.id,I$({id:t.id})}).catch(i=>{console.error("[auth] ensureUser failed",i),s.current=null})}},[e,n,t,r])}function TLe(){const t=Qr(),{user:e}=Fi(),{isAuthenticated:n}=pa();w.useEffect(()=>{t&&(n&&e?(t.identify(e.id,{email:e.email,name:e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.email,first_name:e.firstName,last_name:e.lastName}),t.register({user_id:e.id})):t.reset())},[t,n,e])}function Mz({className:t,...e}){return f.jsx(JJ,{"data-slot":"avatar",className:Oe("relative flex size-8 shrink-0 overflow-hidden rounded-full",t),...e})}function Oz({className:t,...e}){return f.jsx(ZJ,{"data-slot":"avatar-image",className:Oe("aspect-square size-full",t),...e})}function Pz({className:t,...e}){return f.jsx(eZ,{"data-slot":"avatar-fallback",className:Oe("bg-muted flex size-full items-center justify-center rounded-full",t),...e})}function CLe(){const{isLoading:t}=pa(),{user:e,signIn:n,signOut:r,signUp:s}=Fi(),i=Qr();if(t)return f.jsx(Pe,{variant:"outline",size:"sm",disabled:!0,children:f.jsx(or,{className:"h-3 w-3 mr-1.5 animate-spin"})});if(!e)return f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Pe,{variant:"outline",onClick:()=>{i.capture("login_button_clicked",{location:"auth_upper_area",platform:on(),environment:void 0}),n()},children:"Sign in"}),f.jsx(Pe,{onClick:()=>{i.capture("sign_up_button_clicked",{location:"auth_upper_area",platform:on(),environment:void 0}),s()},style:{backgroundColor:"#E55A3A"},children:"Create account"})]});const a=[e.firstName,e.lastName].filter(Boolean).join(" "),l=e.email,u=KX(a),d=()=>{const h=window.location.origin,v=h.includes("://localhost")?h.replace("://localhost","://127.0.0.1"):h;r({returnTo:v})},p=e.profilePictureUrl||void 0;return f.jsxs(m0,{children:[f.jsx(g0,{asChild:!0,children:f.jsx("button",{className:"flex size-10 items-center justify-center rounded-full border border-border/60 bg-background/80 shadow-sm outline-none transition hover:ring-2 hover:ring-ring/20 focus-visible:ring-2 focus-visible:ring-ring",children:f.jsxs(Mz,{className:"size-9 cursor-pointer",children:[f.jsx(Oz,{src:p,alt:a}),f.jsx(Pz,{className:"bg-muted text-muted-foreground text-sm font-medium",children:u!=="?"?u:f.jsx(dI,{className:"size-4"})})]})})}),f.jsxs(v0,{className:"w-56",align:"end",children:[f.jsx(pae,{className:"pb-3",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs(Mz,{className:"size-10 cursor-pointer",children:[f.jsx(Oz,{src:p,alt:a}),f.jsx(Pz,{className:"bg-muted text-muted-foreground text-base font-semibold",children:u!=="?"?u:f.jsx(dI,{className:"size-5"})})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-medium leading-none truncate",children:a}),f.jsx("p",{className:"text-xs text-muted-foreground truncate",children:l})]})]})}),f.jsx(gI,{}),f.jsxs(Ro,{onClick:()=>window.location.hash="settings",className:"cursor-pointer",children:[f.jsx(rN,{className:"size-4"}),"Settings"]}),f.jsx(gI,{}),f.jsxs(Ro,{variant:"destructive",onClick:d,className:"cursor-pointer",children:[f.jsx(Jse,{className:"size-4"}),"Log out"]})]})]})}function ALe(){return f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."})]})})}function NLe(){return f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsx("div",{className:"text-center",children:f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"})})})}const Hc=l1e(t=>({shouldShowLoginPage:!1,dismissedByUser:!1,setShouldShowLoginPage:e=>t(n=>{const r=typeof e=="function"?e(n.shouldShowLoginPage):e;return{shouldShowLoginPage:r,dismissedByUser:!r}}),showLoginPage:()=>t({shouldShowLoginPage:!0,dismissedByUser:!1}),hideLoginPage:()=>t({shouldShowLoginPage:!1,dismissedByUser:!0})}));let ok=null;function tY(){const{isAuthenticated:t,isLoading:e}=pa(),n=Hc(a=>a.shouldShowLoginPage),r=Hc(a=>a.setShouldShowLoginPage),s=Hc(a=>a.showLoginPage),i=Hc(a=>a.hideLoginPage);return w.useEffect(()=>{if(!e){if(t)Hc.setState({shouldShowLoginPage:!1,dismissedByUser:!1});else{const{dismissedByUser:a}=Hc.getState();(ok===null||ok===!0)&&!a&&Hc.setState({shouldShowLoginPage:!0,dismissedByUser:!1})}ok=t}},[t,e]),{shouldShowLoginPage:n,setShouldShowLoginPage:r,showLoginPage:s,hideLoginPage:i,isAuthenticated:t,isAuthLoading:e}}function RLe(){const{signUp:t,signIn:e}=Fi(),n=Qr(),r=Of(u=>u.themeMode),{hideLoginPage:s}=tY();w.useEffect(()=>{n.capture("login_page_viewed",{location:"login_page",platform:on(),environment:void 0})},[]);const i=r==="dark"?"/mcp_jam_dark.png":"/mcp_jam_light.png",a=()=>{n.capture("sign_up_button_clicked",{location:"login_page",platform:on(),environment:void 0}),t()},l=()=>{n.capture("login_button_clicked",{location:"login_page",platform:on(),environment:void 0}),e()};return f.jsx("div",{className:"min-h-screen bg-background",children:f.jsxs("div",{className:"mx-auto flex min-h-screen max-w-xl flex-col items-center justify-center px-6 text-center",children:[f.jsx("button",{type:"button",onClick:s,"aria-label":"Close login",className:"absolute right-4 top-4 rounded-full p-2 text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring cursor-pointer",children:f.jsx(uc,{className:"h-4 w-4"})}),f.jsx("img",{src:i,alt:"MCPJam",className:"h-10 w-auto mb-2"}),f.jsx("div",{className:"space-y-4 mb-12"}),f.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm mb-6",children:[f.jsx(Pe,{size:"lg",variant:"outline",onClick:l,className:"px-16 py-6 text-lg w-full",children:"Log in"}),f.jsx(Pe,{size:"lg",onClick:a,className:"px-16 py-6 text-lg w-full",children:"Sign up"})]}),f.jsx("button",{type:"button",className:"text-sm text-muted-foreground/80 underline hover:text-muted-foreground transition-colors cursor-pointer",onClick:()=>{n.capture("continue_as_guest_button_clicked",{location:"login_page",platform:on(),environment:void 0}),s()},children:"Or continue as guest"})]})})}function jLe(){const[t,e]=w.useState("servers"),n=Qr(),{shouldShowLoginPage:r,isAuthenticated:s,isAuthLoading:i}=tY();TLe(),w.useEffect(()=>{i||n.capture("app_launched",{platform:on(),environment:void 0,user_agent:navigator.userAgent,is_authenticated:s})},[i,s]),rNe(),kLe();const a=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),l=w.useMemo(()=>window.location.pathname==="/callback",[]),u=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback"),[]),{appState:d,isLoading:p,connectedServerConfigs:h,selectedMCPConfig:g,handleConnect:v,handleDisconnect:x,handleReconnect:b,handleUpdate:E,handleRemoveServer:S,setSelectedServer:k,toggleServerSelection:T,selectedMCPConfigsMap:R,setSelectedMultipleServersToAllServers:j}=k7();w.useEffect(()=>{const M=()=>{const I=(window.location.hash||"#servers").replace("#","");e(I),I==="chat"&&j()};return M(),window.addEventListener("hashchange",M),()=>window.removeEventListener("hashchange",M)},[j]);const A=M=>{M==="chat"&&j(),window.location.hash=M,e(M)};if(a)return f.jsx(bAe,{});if(l)return w.useEffect(()=>{const M=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(M)},[]),f.jsx(ALe,{});if(p)return f.jsx(NLe,{});const N=f.jsxs(IAe,{defaultOpen:!0,children:[f.jsx(YAe,{onNavigate:A,activeTab:t}),f.jsxs($Ae,{className:"flex flex-col",children:[f.jsx("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear drag",children:f.jsxs("div",{className:"flex w-full items-center justify-between px-4 lg:px-6",children:[f.jsx("div",{className:"flex items-center gap-1 lg:gap-2",children:f.jsx(LAe,{className:"-ml-1"})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(CLe,{})})]})}),f.jsxs("div",{className:"flex-1",children:[(t==="tools"||t==="resources"||t==="prompts"||t==="auth"||t==="chat"||t==="interceptor")&&f.jsx(QAe,{connectedServerConfigs:h,selectedServer:d.selectedServer,onServerChange:k,onConnect:v,isMultiSelectEnabled:t==="chat",onMultiServerToggle:T,selectedMultipleServers:d.selectedMultipleServers}),t==="servers"&&f.jsx(tde,{connectedServerConfigs:h,onConnect:v,onDisconnect:x,onReconnect:b,onUpdate:E,onRemove:S}),t==="tools"&&f.jsx(ope,{serverConfig:g,serverName:d.selectedServer}),t==="evals"&&f.jsx(hTe,{}),t==="eval-results"&&f.jsx(Zke,{}),t==="resources"&&f.jsx(lpe,{serverConfig:g,serverName:d.selectedServer}),t==="prompts"&&f.jsx(cpe,{serverConfig:g,serverName:d.selectedServer}),t==="auth"&&f.jsx(xAe,{serverConfig:g,serverEntry:d.servers[d.selectedServer],serverName:d.selectedServer}),t==="chat"&&f.jsx(Gke,{serverConfigs:R,connectedServerConfigs:h}),t==="interceptor"&&f.jsx(pAe,{connectedServerConfigs:h,selectedServer:d.selectedServer}),t==="tracing"&&f.jsx(hAe,{}),t==="settings"&&f.jsx(lAe,{})]})]})]});return f.jsxs(u1e,{themeMode:"light",themePreset:"default",children:[f.jsx(nNe,{}),r&&!u?f.jsx(RLe,{}):N]})}function MLe({children:t,client:e,useAuth:n}){const r=OLe(n);return f.jsx(Fke,{client:e,useAuth:r,children:t})}function OLe(t){return w.useMemo(()=>function(){const{isLoading:n,user:r,getAccessToken:s}=t(),i=w.useCallback(async()=>{try{return await s()}catch{return null}},[s]);return w.useMemo(()=>({isLoading:n,isAuthenticated:!!r,fetchAccessToken:i}),[n,r,i])},[t])}const PLe={environment:"prod",sendDefaultPii:!1,tracesSampleRate:.1,tracePropagationTargets:["localhost",/^\//,/^https?:\/\/[^/]*\.convex\.(cloud|site)/]},ILe={...PLe,dsn:"https://c9df3785c734acfe9dad2d0c1e963e28@o4510109778378752.ingest.us.sentry.io/4510111435063296",replaysSessionSampleRate:.1,replaysOnErrorSampleRate:1};function DLe(){ELe({...ILe,integrations:[lLe(),bLe()]})}DLe();const LLe="https://outstanding-fennec-304.convex.cloud",$Le="client_01K4C1TVPBE7JTBFQJF9SDW9P9",zLe=(()=>{const t="mcpjam://oauth/callback";return typeof window>"u"?t:window.location.protocol==="http:"||window.location.protocol==="https:"?`${window.location.origin}/callback`:t})(),FLe=new Rke(LLe),ULe=mX.createRoot(document.getElementById("root")),BLe=f.jsx($pe,{clientId:$Le,redirectUri:zLe,children:f.jsx(MLe,{client:FLe,useAuth:Fi,children:f.jsx(jLe,{})})});ULe.render(f.jsx(w.StrictMode,{children:f.jsx(Cle,{apiKey:Ple(),options:Ile(),children:BLe})}));
1880
- //# sourceMappingURL=index-BwfV9koe.js.map
1879
+ `;if(typeof t=="string")n=`${r}${t}`;else{const i=new TextEncoder().encode(r);n=new Uint8Array(i.length+t.length),n.set(i),n.set(t,i.length)}return n}async function tLe({client:t,scope:e,replayId:n,event:r}){const s=typeof t._integrations=="object"&&t._integrations!==null&&!Array.isArray(t._integrations)?Object.keys(t._integrations):void 0,i={event_id:n,integrations:s};t.emit("preprocessEvent",r,i);const a=await wG(t.getOptions(),r,i,e,t,Ui());if(!a)return null;a.platform=a.platform||"javascript";const l=t.getSdkMetadata(),{name:u,version:d}=l&&l.sdk||{};return a.sdk={...a.sdk,name:u||"sentry.javascript.unknown",version:d||"0.0.0"},a}async function nLe({recordingData:t,replayId:e,segmentId:n,eventContext:r,timestamp:s,session:i}){const a=eLe({recordingData:t,headers:{segment_id:n}}),{urls:l,errorIds:u,traceIds:d,initialTimestamp:p}=r,h=Kt(),g=Nn(),v=h&&h.getTransport(),x=h&&h.getDsn();if(!h||!v||!x||!i.sampled)return Wo({});const b={type:P2e,replay_start_timestamp:p/1e3,timestamp:s/1e3,error_ids:u,trace_ids:d,urls:l,replay_id:e,segment_id:n,replay_type:i.sampled},E=await tLe({scope:g,client:h,replayId:e,event:b});if(!E)return h.recordDroppedEvent("event_processor","replay",b),xt&&St.info("An event processor returned `null`, will not send event."),Wo({});delete E.sdkProcessingMetadata;const S=ZDe(E,a,x,h.getOptions().tunnel);let k;try{k=await v.send(S)}catch(R){const j=new Error(Nj);try{j.cause=R}catch{}throw j}if(typeof k.statusCode=="number"&&(k.statusCode<200||k.statusCode>=300))throw new QW(k.statusCode);const T=MG({},k);if(jG(T,"replay"))throw new Bj(T);return k}class QW extends Error{constructor(e){super(`Transport returned status code ${e}`)}}class Bj extends Error{constructor(e){super("Rate limit hit"),this.rateLimits=e}}async function JW(t,e={count:0,interval:F2e}){const{recordingData:n,onError:r}=t;if(n.length)try{return await nLe(t),!0}catch(s){if(s instanceof QW||s instanceof Bj)throw s;if(kG("Replays",{_retryCount:e.count}),r&&r(s),e.count>=U2e){const i=new Error(`${Nj} - max retries exceeded`);try{i.cause=s}catch{}throw i}return e.interval*=++e.count,new Promise((i,a)=>{Bf(async()=>{try{await JW(t,e),i(!0)}catch(l){a(l)}},e.interval)})}}const ZW="__THROTTLED",rLe="__SKIPPED";function sLe(t,e,n){const r=new Map,s=l=>{const u=l-n;r.forEach((d,p)=>{p<u&&r.delete(p)})},i=()=>[...r.values()].reduce((l,u)=>l+u,0);let a=!1;return(...l)=>{const u=Math.floor(Date.now()/1e3);if(s(u),i()>=e){const p=a;return a=!0,p?rLe:ZW}a=!1;const d=r.get(u)||0;return r.set(u,d+1),t(...l)}}class $l{constructor({options:e,recordingOptions:n}){$l.prototype.__init.call(this),$l.prototype.__init2.call(this),$l.prototype.__init3.call(this),$l.prototype.__init4.call(this),$l.prototype.__init5.call(this),$l.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:I2e,sessionIdleExpire:D2e},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=n,this._options=e,this._debouncedFlush=YDe(()=>this._flush(),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=sLe((a,l)=>ZIe(this,a,l),300,5);const{slowClickTimeout:r,slowClickIgnoreSelectors:s}=this.getOptions(),i=r?{threshold:Math.min(B2e,r),timeout:r,scrollTimeout:q2e,ignoreSelector:s?s.join(","):""}:void 0;if(i&&(this.clickDetector=new dIe(this,i)),xt){const a=e._experiments;St.setConfig({captureExceptions:!!a.captureExceptions,traceInternals:!!a.traceInternals})}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return!!this._canvas}getOptions(){return this._options}handleException(e){xt&&St.exception(e),this._options.onError&&this._options.onError(e)}initializeSampling(e){const{errorSampleRate:n,sessionSampleRate:r}=this._options,s=n<=0&&r<=0;if(this._requiresManualStart=s,!s){if(this._initializeSessionForSampling(e),!this.session){xt&&St.exception(new Error("Unable to initialize and create session"));return}this.session.sampled!==!1&&(this.recordingMode=this.session.sampled==="buffer"&&this.session.segmentId===0?"buffer":"session",xt&&St.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording())}}start(){if(this._isEnabled&&this.recordingMode==="session"){xt&&St.info("Recording is already in progress");return}if(this._isEnabled&&this.recordingMode==="buffer"){xt&&St.info("Buffering is in progress, call `flush()` to save the replay");return}xt&&St.infoTick("Starting replay in session mode"),this._updateUserActivity();const e=ik({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=e,this._initializeRecording()}startBuffering(){if(this._isEnabled){xt&&St.info("Buffering is in progress, call `flush()` to save the replay");return}xt&&St.infoTick("Starting replay in buffer mode");const e=ik({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=e,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{const e=this._canvas;this._stopRecording=Io({...this._recordingOptions,...this.recordingMode==="buffer"?{checkoutEveryNms:z2e}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:XDe(this),...KDe(),onMutation:this._onMutationHandler,...e?{recordCanvas:e.recordCanvas,getCanvasManager:e.getCanvasManager,sampling:e.sampling,dataURLOptions:e.dataURLOptions}:{}})}catch(e){this.handleException(e)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(e){return this.handleException(e),!1}}async stop({forceFlush:e=!1,reason:n}={}){if(this._isEnabled){this._isEnabled=!1;try{xt&&St.info(`Stopping Replay${n?` triggered by ${n}`:""}`),qW(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),e&&await this._flush({force:!0}),this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,YIe(this)}catch(r){this.handleException(r)}}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),xt&&St.info("Pausing replay"))}resume(){!this._isPaused||!this._checkSession()||(this._isPaused=!1,this.startRecording(),xt&&St.info("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:e=!0}={}){if(this.recordingMode==="session")return this.flushImmediate();const n=Date.now();xt&&St.info("Converting buffer to session"),await this.flushImmediate();const r=this.stopRecording();!e||!r||this.recordingMode!=="session"&&(this.recordingMode="session",this.session&&(this._updateUserActivity(n),this._updateSessionActivity(n),this._maybeSaveSession()),this.startRecording())}addUpdate(e){const n=e();this.recordingMode!=="buffer"&&n!==!0&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),!this._stopRecording){if(!this._checkSession())return;this.resume();return}this.checkAndHandleExpiredSession(),this._updateSessionActivity()}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return this.recordingMode==="buffer"?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(){return this.session&&this.session.id}checkAndHandleExpiredSession(){if(this._lastActivity&&oA(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&this.session.sampled==="session"){this.pause();return}return!!this._checkSession()}setInitialState(){const e=`${Tn.location.pathname}${Tn.location.hash}${Tn.location.search}`,n=`${Tn.location.origin}${e}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=n,this._context.initialTimestamp=Date.now(),this._context.urls.push(n)}throttledAddEvent(e,n){const r=this._throttledAddEvent(e,n);if(r===ZW){const s=Oa({category:"replay.throttled"});this.addUpdate(()=>!Fj(this,{type:sIe,timestamp:s.timestamp||0,data:{tag:"breadcrumb",payload:s,metric:!0}}))}return r}getCurrentRoute(){const e=this.lastActiveSpan||$r(),n=e&&Xr(e),s=(n&&nn(n).data||{})[Ma];if(!(!n||!s||!["route","custom"].includes(s)))return nn(n).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=HIe({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()}_initializeSessionForSampling(e){const n=this._options.errorSampleRate>0,r=ik({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:e},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:n});this.session=r}_checkSession(){if(!this.session)return!1;const e=this.session;return zW(e,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})?(this._refreshSession(e),!1):!0}async _refreshSession(e){this._isEnabled&&(await this.stop({reason:"refresh session"}),this.initializeSampling(e.id))}_addListeners(){try{Tn.document.addEventListener("visibilitychange",this._handleVisibilityChange),Tn.addEventListener("blur",this._handleWindowBlur),Tn.addEventListener("focus",this._handleWindowFocus),Tn.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(HDe(this),this._hasInitializedCoreListeners=!0)}catch(e){this.handleException(e)}this._performanceCleanupCallback=$Ie(this)}_removeListeners(){try{Tn.document.removeEventListener("visibilitychange",this._handleVisibilityChange),Tn.removeEventListener("blur",this._handleWindowBlur),Tn.removeEventListener("focus",this._handleWindowFocus),Tn.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(e){this.handleException(e)}}__init(){this._handleVisibilityChange=()=>{Tn.document.visibilityState==="visible"?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()}}__init2(){this._handleWindowBlur=()=>{const e=Oa({category:"ui.blur"});this._doChangeToBackgroundTasks(e)}}__init3(){this._handleWindowFocus=()=>{const e=Oa({category:"ui.focus"});this._doChangeToForegroundTasks(e)}}__init4(){this._handleKeyboardEvent=e=>{EIe(this,e)}}_doChangeToBackgroundTasks(e){!this.session||$W(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(e&&this._createCustomBreadcrumb(e),this.conditionalFlush())}_doChangeToForegroundTasks(e){if(!this.session)return;if(!this.checkAndHandleExpiredSession()){xt&&St.info("Document has become active, but session has expired");return}e&&this._createCustomBreadcrumb(e)}_updateUserActivity(e=Date.now()){this._lastActivity=e}_updateSessionActivity(e=Date.now()){this.session&&(this.session.lastActivity=e,this._maybeSaveSession())}_createCustomBreadcrumb(e){this.addUpdate(()=>{this.throttledAddEvent({type:Ut.Custom,timestamp:e.timestamp||0,data:{tag:"breadcrumb",payload:e}})})}_addPerformanceEntries(){let e=AIe(this.performanceEntries).concat(this.replayPerformanceEntries);if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){const n=this._context.initialTimestamp/1e3;e=e.filter(r=>r.start>=n)}return Promise.all(l_(this,e))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){const{session:e,eventBuffer:n}=this;if(!e||!n||this._requiresManualStart||e.segmentId)return;const r=n.getEarliestTimestamp();r&&r<this._context.initialTimestamp&&(this._context.initialTimestamp=r)}_popEventContext(){const e={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),e}async _runFlush(){const e=this.getSessionId();if(!this.session||!this.eventBuffer||!e){xt&&St.error("No session or eventBuffer found to flush.");return}if(await this._addPerformanceEntries(),!(!this.eventBuffer||!this.eventBuffer.hasEvents)&&(await GDe(this),!!this.eventBuffer&&e===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();const n=Date.now();if(n-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new Error("Session is too long, not sending replay");const r=this._popEventContext(),s=this.session.segmentId++;this._maybeSaveSession();const i=await this.eventBuffer.finish();await JW({replayId:e,recordingData:i,segmentId:s,eventContext:r,session:this.session,timestamp:n,onError:a=>this.handleException(a)})}catch(n){this.handleException(n),this.stop({reason:"sendReplay"});const r=Kt();if(r){const s=n instanceof Bj?"ratelimit_backoff":"send_error";r.recordDroppedEvent(s,"replay")}}}__init5(){this._flush=async({force:e=!1}={})=>{if(!this._isEnabled&&!e)return;if(!this.checkAndHandleExpiredSession()){xt&&St.error("Attempting to finish replay event after session expired.");return}if(!this.session)return;const n=this.session.started,s=Date.now()-n;this._debouncedFlush.cancel();const i=s<this._options.minReplayDuration,a=s>this._options.maxReplayDuration+5e3;if(i||a){xt&&St.info(`Session duration (${Math.floor(s/1e3)}s) is too ${i?"short":"long"}, not sending replay.`),i&&this._debouncedFlush();return}const l=this.eventBuffer;l&&this.session.segmentId===0&&!l.hasCheckout&&xt&&St.info("Flushing initial segment without checkout.");const u=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(d){this.handleException(d)}finally{this._flushLock=void 0,u&&this._debouncedFlush()}}}_maybeSaveSession(){this.session&&this._options.stickySession&&zj(this.session)}__init6(){this._onMutationHandler=e=>{const n=e.length,r=this._options.mutationLimit,s=this._options.mutationBreadcrumbLimit,i=r&&n>r;if(n>s||i){const a=Oa({category:"replay.mutations",data:{count:n,limit:i}});this._createCustomBreadcrumb(a)}return i?(this.stop({reason:"mutationLimit",forceFlush:this.recordingMode==="session"}),!1):!0}}}function Rp(t,e){return[...t,...e].join(",")}function iLe({mask:t,unmask:e,block:n,unblock:r,ignore:s}){const i=["base","iframe[srcdoc]:not([src])"],a=Rp(t,[".sentry-mask","[data-sentry-mask]"]),l=Rp(e,[]);return{maskTextSelector:a,unmaskTextSelector:l,blockSelector:Rp(n,[".sentry-block","[data-sentry-block]",...i]),unblockSelector:Rp(r,[]),ignoreSelector:Rp(s,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}function aLe({el:t,key:e,maskAttributes:n,maskAllText:r,privacyOptions:s,value:i}){return!r||s.unmaskTextSelector&&t.matches(s.unmaskTextSelector)?i:n.includes(e)||e==="value"&&t.tagName==="INPUT"&&["submit","button"].includes(t.getAttribute("type")||"")?i.replace(/[\S]/g,"*"):i}const Tz='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',oLe=["content-length","content-type","accept"];let Cz=!1;const lLe=t=>new u_(t);class u_{static __initStatic(){this.id="Replay"}constructor({flushMinDelay:e=L2e,flushMaxDelay:n=$2e,minReplayDuration:r=V2e,maxReplayDuration:s=iz,stickySession:i=!0,useCompression:a=!0,workerUrl:l,_experiments:u={},maskAllText:d=!0,maskAllInputs:p=!0,blockAllMedia:h=!0,mutationBreadcrumbLimit:g=750,mutationLimit:v=1e4,slowClickTimeout:x=7e3,slowClickIgnoreSelectors:b=[],networkDetailAllowUrls:E=[],networkDetailDenyUrls:S=[],networkCaptureBodies:k=!0,networkRequestHeaders:T=[],networkResponseHeaders:R=[],mask:j=[],maskAttributes:A=["title","placeholder"],unmask:N=[],block:M=[],unblock:I=[],ignore:O=[],maskFn:L,beforeAddRecordingEvent:z,beforeErrorSampling:H,onError:V}={}){this.name=u_.id;const X=iLe({mask:j,unmask:N,block:M,unblock:I,ignore:O});if(this._recordingOptions={maskAllInputs:p,maskAllText:d,maskInputOptions:{password:!0},maskTextFn:L,maskInputFn:L,maskAttributeFn:(F,W,G)=>aLe({maskAttributes:A,maskAllText:d,privacyOptions:X,key:F,value:W,el:G}),...X,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:F=>{try{F.__rrweb__=!0}catch{}}},this._initialOptions={flushMinDelay:e,flushMaxDelay:n,minReplayDuration:Math.min(r,H2e),maxReplayDuration:Math.min(s,iz),stickySession:i,useCompression:a,workerUrl:l,blockAllMedia:h,maskAllInputs:p,maskAllText:d,mutationBreadcrumbLimit:g,mutationLimit:v,slowClickTimeout:x,slowClickIgnoreSelectors:b,networkDetailAllowUrls:E,networkDetailDenyUrls:S,networkCaptureBodies:k,networkRequestHeaders:Az(T),networkResponseHeaders:Az(R),beforeAddRecordingEvent:z,beforeErrorSampling:H,onError:V,_experiments:u},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${Tz}`:Tz),this._isInitialized&&K$())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return Cz}set _isInitialized(e){Cz=e}afterAllSetup(e){!K$()||this._replay||(this._setup(e),this._initialize(e))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:this._replay.recordingMode==="session"}):Promise.resolve()}flush(e){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(e):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.getSessionId()}getRecordingMode(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.recordingMode}_initialize(e){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(e),this._replay.initializeSampling())}_setup(e){const n=cLe(this._initialOptions,e);this._replay=new $l({options:n,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(e){try{const n=e.getIntegrationByName("ReplayCanvas");if(!n)return;this._replay._canvas=n.getOptions()}catch{}}}u_.__initStatic();function cLe(t,e){const n=e.getOptions(),r={sessionSampleRate:0,errorSampleRate:0,...Rr(t)},s=Rb(n.replaysSessionSampleRate),i=Rb(n.replaysOnErrorSampleRate);return s==null&&i==null&&gc(()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}),s!=null&&(r.sessionSampleRate=s),i!=null&&(r.errorSampleRate=i),r}function Az(t){return[...oLe,...t.map(e=>e.toLowerCase())]}const Nz=new WeakMap,ak=new Map,gx={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function uLe(t,e){const{traceFetch:n,traceXHR:r,trackFetchStreamPerformance:s,shouldCreateSpanForRequest:i,enableHTTPTimings:a,tracePropagationTargets:l}={traceFetch:gx.traceFetch,traceXHR:gx.traceXHR,trackFetchStreamPerformance:gx.trackFetchStreamPerformance,...e},u=typeof i=="function"?i:h=>!0,d=h=>hLe(h,l),p={};n&&(t.addEventProcessor(h=>(h.type==="transaction"&&h.spans&&h.spans.forEach(g=>{if(g.op==="http.client"){const v=ak.get(g.span_id);v&&(g.timestamp=v/1e3,ak.delete(g.span_id))}}),h)),s&&eMe(h=>{if(h.response){const g=Nz.get(h.response);g&&h.endTimestamp&&ak.set(g,h.endTimestamp)}}),FG(h=>{const g=Wje(h,u,d,p);if(h.response&&h.fetchData.__span&&Nz.set(h.response,h.fetchData.__span),g){const v=eY(h.fetchData.url),x=v?pu(v).host:void 0;g.setAttributes({"http.url":v,"server.address":x})}a&&g&&Rz(g)})),r&&aW(h=>{const g=pLe(h,u,d,p);a&&g&&Rz(g)})}function dLe(t){return t.entryType==="resource"&&"initiatorType"in t&&typeof t.nextHopProtocol=="string"&&(t.initiatorType==="fetch"||t.initiatorType==="xmlhttprequest")}function Rz(t){const{url:e}=nn(t).data||{};if(!e||typeof e!="string")return;const n=Uf("resource",({entries:r})=>{r.forEach(s=>{dLe(s)&&s.name.endsWith(e)&&(fLe(s).forEach(a=>t.setAttribute(...a)),setTimeout(n))})})}function Ea(t=0){return((bs||performance.timeOrigin)+t)/1e3}function fLe(t){const{name:e,version:n}=rW(t.nextHopProtocol),r=[];return r.push(["network.protocol.version",n],["network.protocol.name",e]),bs?[...r,["http.request.redirect_start",Ea(t.redirectStart)],["http.request.fetch_start",Ea(t.fetchStart)],["http.request.domain_lookup_start",Ea(t.domainLookupStart)],["http.request.domain_lookup_end",Ea(t.domainLookupEnd)],["http.request.connect_start",Ea(t.connectStart)],["http.request.secure_connection_start",Ea(t.secureConnectionStart)],["http.request.connection_end",Ea(t.connectEnd)],["http.request.request_start",Ea(t.requestStart)],["http.request.response_start",Ea(t.responseStart)],["http.request.response_end",Ea(t.responseEnd)]]:r}function hLe(t,e){const n=Nt.location&&Nt.location.href;if(n){let r,s;try{r=new URL(t,n),s=new URL(n).origin}catch{return!1}const i=r.origin===s;return e?Wl(r.toString(),e)||i&&Wl(r.pathname,e):i}else{const r=!!t.match(/^\/(?!\/)/);return e?Wl(t,e):r}}function pLe(t,e,n,r){const s=t.xhr,i=s&&s[eu];if(!s||s.__sentry_own_request__||!i)return;const a=sc()&&e(i.url);if(t.endTimestamp&&a){const h=s.__sentry_xhr_span_id__;if(!h)return;const g=r[h];g&&i.status_code!==void 0&&(tG(g,i.status_code),g.end(),delete r[h]);return}const l=eY(i.url),u=l?pu(l).host:void 0,d=!!$r(),p=a&&d?Og({name:`${i.method} ${i.url}`,attributes:{type:"xhr","http.method":i.method,"http.url":l,url:i.url,"server.address":u,[Dr]:"auto.http.browser",[ju]:"http.client"}}):new fh;return s.__sentry_xhr_span_id__=p.spanContext().spanId,r[s.__sentry_xhr_span_id__]=p,n(i.url)&&mLe(s,sc()&&d?p:void 0),p}function mLe(t,e){const{"sentry-trace":n,baggage:r}=PG({span:e});n&&gLe(t,n,r)}function gLe(t,e,n){try{t.setRequestHeader("sentry-trace",e),n&&t.setRequestHeader("baggage",n)}catch{}}function eY(t){try{return new URL(t,Nt.location.origin).href}catch{return}}function vLe(){Nt&&Nt.document?Nt.document.addEventListener("visibilitychange",()=>{const t=$r();if(!t)return;const e=Xr(t);if(Nt.document.hidden&&e){const n="cancelled",{op:r,status:s}=nn(e);Ka&&ze.log(`[Tracing] Transaction: ${n} -> since tab moved to the background, op: ${r}`),s||e.setStatus({code:Pr,message:n}),e.setAttribute("sentry.cancellation_reason","document.hidden"),e.end()}}):Ka&&ze.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const yLe="BrowserTracing",xLe={...dx,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,_experiments:{},...gx},bLe=(t={})=>{QNe();const{enableInp:e,enableLongTask:n,enableLongAnimationFrame:r,_experiments:{enableInteractions:s,enableStandaloneClsSpans:i},beforeStartSpan:a,idleTimeout:l,finalTimeout:u,childSpanTimeout:d,markBackgroundSpan:p,traceFetch:h,traceXHR:g,trackFetchStreamPerformance:v,shouldCreateSpanForRequest:x,enableHTTPTimings:b,instrumentPageLoad:E,instrumentNavigation:S}={...xLe,...t},k=cOe({recordClsStandaloneSpans:i||!1});e&&POe(),r&&Xt.PerformanceObserver&&PerformanceObserver.supportedEntryTypes&&PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")?dOe():n&&uOe(),s&&fOe();const T={name:void 0,source:void 0};function R(j,A){const N=A.op==="pageload",M=a?a(A):A,I=M.attributes||{};A.name!==M.name&&(I[Ma]="custom",M.attributes=I),T.name=M.name,T.source=I[Ma];const O=_G(M,{idleTimeout:l,finalTimeout:u,childSpanTimeout:d,disableAutoFinish:N,beforeSpanEnd:z=>{k(),vOe(z,{recordClsOnPageloadSpan:!i})}});function L(){["interactive","complete"].includes(Nt.document.readyState)&&j.emit("idleSpanEnableAutoFinish",O)}return N&&Nt.document&&(Nt.document.addEventListener("readystatechange",()=>{L()}),L()),O}return{name:yLe,afterAllSetup(j){let A,N=Nt.location&&Nt.location.href;function M(){A&&!nn(A).timestamp&&(Ka&&ze.log(`[Tracing] Finishing current active span with op: ${nn(A).op}`),A.end())}j.on("startNavigationSpan",I=>{Kt()===j&&(M(),A=R(j,{op:"navigation",...I}))}),j.on("startPageLoadSpan",(I,O={})=>{if(Kt()!==j)return;M();const L=O.sentryTrace||jz("sentry-trace"),z=O.baggage||jz("baggage"),H=VNe(L,z);Nn().setPropagationContext(H),A=R(j,{op:"pageload",...I})}),j.on("spanEnd",I=>{const O=nn(I).op;if(I!==Xr(I)||O!=="navigation"&&O!=="pageload")return;const L=Nn(),z=L.getPropagationContext();L.setPropagationContext({...z,sampled:z.sampled!==void 0?z.sampled:Iu(I),dsc:z.dsc||Du(I)})}),Nt.location&&(E&&_Le(j,{name:Nt.location.pathname,startTime:bs?bs/1e3:void 0,attributes:{[Ma]:"url",[Dr]:"auto.pageload.browser"}}),S&&r_(({to:I,from:O})=>{if(O===void 0&&N&&N.indexOf(I)!==-1){N=void 0;return}O!==I&&(N=void 0,wLe(j,{name:Nt.location.pathname,attributes:{[Ma]:"url",[Dr]:"auto.navigation.browser"}}))})),p&&vLe(),s&&SLe(l,u,d,T),e&&DOe(),uLe(j,{traceFetch:h,traceXHR:g,trackFetchStreamPerformance:v,tracePropagationTargets:j.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:x,enableHTTPTimings:b})}}};function _Le(t,e,n){t.emit("startPageLoadSpan",e,n),Nn().setTransactionName(e.name);const r=$r();return(r&&nn(r).op)==="pageload"?r:void 0}function wLe(t,e){Ui().setPropagationContext({traceId:nc()}),Nn().setPropagationContext({traceId:nc()}),t.emit("startNavigationSpan",e),Nn().setTransactionName(e.name);const n=$r();return(n&&nn(n).op)==="navigation"?n:void 0}function jz(t){const e=gNe(`meta[name=${t}]`);return e?e.getAttribute("content"):void 0}function SLe(t,e,n,r){let s;const i=()=>{const a="ui.action.click",l=$r(),u=l&&Xr(l);if(u){const d=nn(u).op;if(["navigation","pageload"].includes(d)){Ka&&ze.warn(`[Tracing] Did not create ${a} span because a pageload or navigation span is in progress.`);return}}if(s&&(s.setAttribute(LC,"interactionInterrupted"),s.end(),s=void 0),!r.name){Ka&&ze.warn(`[Tracing] Did not create ${a} transaction because _latestRouteName is missing.`);return}s=_G({name:r.name,op:a,attributes:{[Ma]:r.source||"url"}},{idleTimeout:t,finalTimeout:e,childSpanTimeout:n})};Nt.document&&addEventListener("click",i,{once:!1,capture:!0})}function ELe(t){const e={...t};return OG(e,"react"),kG("react",{version:w.version}),O2e(e)}function kLe(){const{user:t}=Fi(),{isAuthenticated:e,isLoading:n}=pa(),r=b7("users:ensureUser"),s=w.useRef(null);w.useEffect(()=>{e||(s.current=null,I$(null))},[e]),w.useEffect(()=>{if(!n){if(!e&&t)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");e&&t&&s.current!==t.id&&r().then(i=>{s.current=t.id,I$({id:t.id})}).catch(i=>{console.error("[auth] ensureUser failed",i),s.current=null})}},[e,n,t,r])}function TLe(){const t=Qr(),{user:e}=Fi(),{isAuthenticated:n}=pa();w.useEffect(()=>{t&&(n&&e?(t.identify(e.id,{email:e.email,name:e.firstName&&e.lastName?`${e.firstName} ${e.lastName}`:e.email,first_name:e.firstName,last_name:e.lastName}),t.register({user_id:e.id})):t.reset())},[t,n,e])}function Mz({className:t,...e}){return f.jsx(JJ,{"data-slot":"avatar",className:Oe("relative flex size-8 shrink-0 overflow-hidden rounded-full",t),...e})}function Oz({className:t,...e}){return f.jsx(ZJ,{"data-slot":"avatar-image",className:Oe("aspect-square size-full",t),...e})}function Pz({className:t,...e}){return f.jsx(eZ,{"data-slot":"avatar-fallback",className:Oe("bg-muted flex size-full items-center justify-center rounded-full",t),...e})}function CLe(){const{isLoading:t}=pa(),{user:e,signIn:n,signOut:r,signUp:s}=Fi(),i=Qr();if(t)return f.jsx(Pe,{variant:"outline",size:"sm",disabled:!0,children:f.jsx(or,{className:"h-3 w-3 mr-1.5 animate-spin"})});if(!e)return f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Pe,{variant:"outline",onClick:()=>{i.capture("login_button_clicked",{location:"auth_upper_area",platform:on(),environment:void 0}),n()},children:"Sign in"}),f.jsx(Pe,{onClick:()=>{i.capture("sign_up_button_clicked",{location:"auth_upper_area",platform:on(),environment:void 0}),s()},children:"Create account"})]});const a=[e.firstName,e.lastName].filter(Boolean).join(" "),l=e.email,u=KX(a),d=()=>{const h=window.location.origin,v=h.includes("://localhost")?h.replace("://localhost","://127.0.0.1"):h;r({returnTo:v})},p=e.profilePictureUrl||void 0;return f.jsxs(m0,{children:[f.jsx(g0,{asChild:!0,children:f.jsx("button",{className:"flex size-10 items-center justify-center rounded-full border border-border/60 bg-background/80 shadow-sm outline-none transition hover:ring-2 hover:ring-ring/20 focus-visible:ring-2 focus-visible:ring-ring",children:f.jsxs(Mz,{className:"size-9 cursor-pointer",children:[f.jsx(Oz,{src:p,alt:a}),f.jsx(Pz,{className:"bg-muted text-muted-foreground text-sm font-medium",children:u!=="?"?u:f.jsx(dI,{className:"size-4"})})]})})}),f.jsxs(v0,{className:"w-56",align:"end",children:[f.jsx(pae,{className:"pb-3",children:f.jsxs("div",{className:"flex items-center gap-3",children:[f.jsxs(Mz,{className:"size-10 cursor-pointer",children:[f.jsx(Oz,{src:p,alt:a}),f.jsx(Pz,{className:"bg-muted text-muted-foreground text-base font-semibold",children:u!=="?"?u:f.jsx(dI,{className:"size-5"})})]}),f.jsxs("div",{className:"min-w-0 flex-1",children:[f.jsx("p",{className:"text-sm font-medium leading-none truncate",children:a}),f.jsx("p",{className:"text-xs text-muted-foreground truncate",children:l})]})]})}),f.jsx(gI,{}),f.jsxs(Ro,{onClick:()=>window.location.hash="settings",className:"cursor-pointer",children:[f.jsx(rN,{className:"size-4"}),"Settings"]}),f.jsx(gI,{}),f.jsxs(Ro,{variant:"destructive",onClick:d,className:"cursor-pointer",children:[f.jsx(Jse,{className:"size-4"}),"Log out"]})]})]})}function ALe(){return f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsxs("div",{className:"text-center",children:[f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"}),f.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."})]})})}function NLe(){return f.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:f.jsx("div",{className:"text-center",children:f.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"})})})}const Hc=l1e(t=>({shouldShowLoginPage:!1,dismissedByUser:!1,setShouldShowLoginPage:e=>t(n=>{const r=typeof e=="function"?e(n.shouldShowLoginPage):e;return{shouldShowLoginPage:r,dismissedByUser:!r}}),showLoginPage:()=>t({shouldShowLoginPage:!0,dismissedByUser:!1}),hideLoginPage:()=>t({shouldShowLoginPage:!1,dismissedByUser:!0})}));let ok=null;function tY(){const{isAuthenticated:t,isLoading:e}=pa(),n=Hc(a=>a.shouldShowLoginPage),r=Hc(a=>a.setShouldShowLoginPage),s=Hc(a=>a.showLoginPage),i=Hc(a=>a.hideLoginPage);return w.useEffect(()=>{if(!e){if(t)Hc.setState({shouldShowLoginPage:!1,dismissedByUser:!1});else{const{dismissedByUser:a}=Hc.getState();(ok===null||ok===!0)&&!a&&Hc.setState({shouldShowLoginPage:!0,dismissedByUser:!1})}ok=t}},[t,e]),{shouldShowLoginPage:n,setShouldShowLoginPage:r,showLoginPage:s,hideLoginPage:i,isAuthenticated:t,isAuthLoading:e}}function RLe(){const{signUp:t,signIn:e}=Fi(),n=Qr(),r=Of(u=>u.themeMode),{hideLoginPage:s}=tY();w.useEffect(()=>{n.capture("login_page_viewed",{location:"login_page",platform:on(),environment:void 0})},[]);const i=r==="dark"?"/mcp_jam_dark.png":"/mcp_jam_light.png",a=()=>{n.capture("sign_up_button_clicked",{location:"login_page",platform:on(),environment:void 0}),t()},l=()=>{n.capture("login_button_clicked",{location:"login_page",platform:on(),environment:void 0}),e()};return f.jsx("div",{className:"min-h-screen bg-background",children:f.jsxs("div",{className:"mx-auto flex min-h-screen max-w-xl flex-col items-center justify-center px-6 text-center",children:[f.jsx("button",{type:"button",onClick:s,"aria-label":"Close login",className:"absolute right-4 top-4 rounded-full p-2 text-muted-foreground transition hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring cursor-pointer",children:f.jsx(uc,{className:"h-4 w-4"})}),f.jsx("img",{src:i,alt:"MCPJam",className:"h-10 w-auto mb-2"}),f.jsx("div",{className:"space-y-4 mb-12"}),f.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm mb-6",children:[f.jsx(Pe,{size:"lg",variant:"outline",onClick:l,className:"px-16 py-6 text-lg w-full",children:"Log in"}),f.jsx(Pe,{size:"lg",onClick:a,className:"px-16 py-6 text-lg w-full",children:"Sign up"})]}),f.jsx("button",{type:"button",className:"text-sm text-muted-foreground/80 underline hover:text-muted-foreground transition-colors cursor-pointer",onClick:()=>{n.capture("continue_as_guest_button_clicked",{location:"login_page",platform:on(),environment:void 0}),s()},children:"Or continue as guest"})]})})}function jLe(){const[t,e]=w.useState("servers"),n=Qr(),{shouldShowLoginPage:r,isAuthenticated:s,isAuthLoading:i}=tY();TLe(),w.useEffect(()=>{i||n.capture("app_launched",{platform:on(),environment:void 0,user_agent:navigator.userAgent,is_authenticated:s})},[i,s]),rNe(),kLe();const a=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),l=w.useMemo(()=>window.location.pathname==="/callback",[]),u=w.useMemo(()=>window.location.pathname.startsWith("/oauth/callback"),[]),{appState:d,isLoading:p,connectedServerConfigs:h,selectedMCPConfig:g,handleConnect:v,handleDisconnect:x,handleReconnect:b,handleUpdate:E,handleRemoveServer:S,setSelectedServer:k,toggleServerSelection:T,selectedMCPConfigsMap:R,setSelectedMultipleServersToAllServers:j}=k7();w.useEffect(()=>{const M=()=>{const I=(window.location.hash||"#servers").replace("#","");e(I),I==="chat"&&j()};return M(),window.addEventListener("hashchange",M),()=>window.removeEventListener("hashchange",M)},[j]);const A=M=>{M==="chat"&&j(),window.location.hash=M,e(M)};if(a)return f.jsx(bAe,{});if(l)return w.useEffect(()=>{const M=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(M)},[]),f.jsx(ALe,{});if(p)return f.jsx(NLe,{});const N=f.jsxs(IAe,{defaultOpen:!0,children:[f.jsx(YAe,{onNavigate:A,activeTab:t}),f.jsxs($Ae,{className:"flex flex-col",children:[f.jsx("header",{className:"flex h-12 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear drag",children:f.jsxs("div",{className:"flex w-full items-center justify-between px-4 lg:px-6",children:[f.jsx("div",{className:"flex items-center gap-1 lg:gap-2",children:f.jsx(LAe,{className:"-ml-1"})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsx(CLe,{})})]})}),f.jsxs("div",{className:"flex-1",children:[(t==="tools"||t==="resources"||t==="prompts"||t==="auth"||t==="chat"||t==="interceptor")&&f.jsx(QAe,{connectedServerConfigs:h,selectedServer:d.selectedServer,onServerChange:k,onConnect:v,isMultiSelectEnabled:t==="chat",onMultiServerToggle:T,selectedMultipleServers:d.selectedMultipleServers}),t==="servers"&&f.jsx(tde,{connectedServerConfigs:h,onConnect:v,onDisconnect:x,onReconnect:b,onUpdate:E,onRemove:S}),t==="tools"&&f.jsx(ope,{serverConfig:g,serverName:d.selectedServer}),t==="evals"&&f.jsx(hTe,{}),t==="eval-results"&&f.jsx(Zke,{}),t==="resources"&&f.jsx(lpe,{serverConfig:g,serverName:d.selectedServer}),t==="prompts"&&f.jsx(cpe,{serverConfig:g,serverName:d.selectedServer}),t==="auth"&&f.jsx(xAe,{serverConfig:g,serverEntry:d.servers[d.selectedServer],serverName:d.selectedServer}),t==="chat"&&f.jsx(Gke,{serverConfigs:R,connectedServerConfigs:h}),t==="interceptor"&&f.jsx(pAe,{connectedServerConfigs:h,selectedServer:d.selectedServer}),t==="tracing"&&f.jsx(hAe,{}),t==="settings"&&f.jsx(lAe,{})]})]})]});return f.jsxs(u1e,{themeMode:"light",themePreset:"default",children:[f.jsx(nNe,{}),r&&!u?f.jsx(RLe,{}):N]})}function MLe({children:t,client:e,useAuth:n}){const r=OLe(n);return f.jsx(Fke,{client:e,useAuth:r,children:t})}function OLe(t){return w.useMemo(()=>function(){const{isLoading:n,user:r,getAccessToken:s}=t(),i=w.useCallback(async()=>{try{return await s()}catch{return null}},[s]);return w.useMemo(()=>({isLoading:n,isAuthenticated:!!r,fetchAccessToken:i}),[n,r,i])},[t])}const PLe={environment:"prod",sendDefaultPii:!1,tracesSampleRate:.1,tracePropagationTargets:["localhost",/^\//,/^https?:\/\/[^/]*\.convex\.(cloud|site)/]},ILe={...PLe,dsn:"https://c9df3785c734acfe9dad2d0c1e963e28@o4510109778378752.ingest.us.sentry.io/4510111435063296",replaysSessionSampleRate:.1,replaysOnErrorSampleRate:1};function DLe(){ELe({...ILe,integrations:[lLe(),bLe()]})}DLe();const LLe="https://outstanding-fennec-304.convex.cloud",$Le="client_01K4C1TVPBE7JTBFQJF9SDW9P9",zLe=(()=>{const t="mcpjam://oauth/callback";return typeof window>"u"?t:window.location.protocol==="http:"||window.location.protocol==="https:"?`${window.location.origin}/callback`:t})(),FLe=new Rke(LLe),ULe=mX.createRoot(document.getElementById("root")),BLe=f.jsx($pe,{clientId:$Le,redirectUri:zLe,children:f.jsx(MLe,{client:FLe,useAuth:Fi,children:f.jsx(jLe,{})})});ULe.render(f.jsx(w.StrictMode,{children:f.jsx(Cle,{apiKey:Ple(),options:Ile(),children:BLe})}));
1880
+ //# sourceMappingURL=index-BiLTSE2l.js.map